@qwen-code/sdk 0.1.5-preview.2 → 0.1.6-preview.0

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/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Et=Object.create;var Re=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var Ye=(t,e)=>{for(var r in e)Re(t,r,{get:e[r],enumerable:!0})},Xe=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pt(e))!Ot.call(t,n)&&n!==r&&Re(t,n,{get:()=>e[n],enumerable:!(s=It(e,n))||s.enumerable});return t};var Be=(t,e,r)=>(r=t!=null?Et(At(t)):{},Xe(e||!t||!t.__esModule?Re(r,"default",{value:t,enumerable:!0}):r,t)),jt=t=>Xe(Re({},"__esModule",{value:!0}),t);var ys={};Ye(ys,{AbortError:()=>w,Query:()=>fe,SdkLogger:()=>T,createSdkMcpServer:()=>Mt,isAbortError:()=>ct,isControlCancel:()=>Ne,isControlRequest:()=>Le,isControlResponse:()=>De,isSDKAssistantMessage:()=>Pe,isSDKPartialAssistantMessage:()=>je,isSDKResultMessage:()=>Oe,isSDKSystemMessage:()=>Ae,isSDKUserMessage:()=>Ie,isSdkMcpServerConfig:()=>ke,query:()=>wt,tool:()=>Ct});module.exports=jt(ys);var et={debug:0,info:1,warn:2,error:3},T=class{static config={};static effectiveLevel="error";static configure(e){this.config=e,this.effectiveLevel=this.determineLogLevel()}static determineLogLevel(){if(this.config.logLevel)return this.config.logLevel;if(this.config.debug)return"debug";let e=process.env.DEBUG_QWEN_CODE_SDK_LEVEL;return e&&this.isValidLogLevel(e)?e:process.env.DEBUG_QWEN_CODE_SDK?"debug":"error"}static isValidLogLevel(e){return["debug","info","warn","error"].includes(e)}static shouldLog(e){return et[e]>=et[this.effectiveLevel]}static formatTimestamp(){let e=new Date,r=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`${r}-${s}-${n} ${i}:${o}:${a}`}static formatMessage(e,r,s,n){let i=this.formatTimestamp(),o=`[${e.toUpperCase()}]`.padEnd(7),a=`${i} ${o} [${r}] ${s}`;if(n.length>0){let d=n.map(u=>{if(typeof u=="string")return u;if(u instanceof Error)return u.message;try{return JSON.stringify(u)}catch{return String(u)}}).join(" ");a+=` ${d}`}return a}static log(e,r,s,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,r,s,n);this.config.stderr?this.config.stderr(i):e==="warn"||e==="error"?process.stderr.write(i+`
1
+ "use strict";var Et=Object.create;var Re=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var Ye=(t,e)=>{for(var r in e)Re(t,r,{get:e[r],enumerable:!0})},Xe=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pt(e))!Ot.call(t,n)&&n!==r&&Re(t,n,{get:()=>e[n],enumerable:!(s=It(e,n))||s.enumerable});return t};var Be=(t,e,r)=>(r=t!=null?Et(At(t)):{},Xe(e||!t||!t.__esModule?Re(r,"default",{value:t,enumerable:!0}):r,t)),jt=t=>Xe(Re({},"__esModule",{value:!0}),t);var _s={};Ye(_s,{AbortError:()=>w,Query:()=>fe,SdkLogger:()=>T,createSdkMcpServer:()=>Mt,isAbortError:()=>ct,isControlCancel:()=>Ne,isControlRequest:()=>Le,isControlResponse:()=>De,isSDKAssistantMessage:()=>Pe,isSDKPartialAssistantMessage:()=>je,isSDKResultMessage:()=>Oe,isSDKSystemMessage:()=>Ae,isSDKUserMessage:()=>Ie,isSdkMcpServerConfig:()=>ke,query:()=>wt,tool:()=>Ct});module.exports=jt(_s);var et={debug:0,info:1,warn:2,error:3},T=class{static config={};static effectiveLevel="error";static configure(e){this.config=e,this.effectiveLevel=this.determineLogLevel()}static determineLogLevel(){if(this.config.logLevel)return this.config.logLevel;if(this.config.debug)return"debug";let e=process.env.DEBUG_QWEN_CODE_SDK_LEVEL;return e&&this.isValidLogLevel(e)?e:process.env.DEBUG_QWEN_CODE_SDK?"debug":"error"}static isValidLogLevel(e){return["debug","info","warn","error"].includes(e)}static shouldLog(e){return et[e]>=et[this.effectiveLevel]}static formatTimestamp(){let e=new Date,r=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`${r}-${s}-${n} ${i}:${o}:${a}`}static formatMessage(e,r,s,n){let i=this.formatTimestamp(),o=`[${e.toUpperCase()}]`.padEnd(7),a=`${i} ${o} [${r}] ${s}`;if(n.length>0){let u=n.map(d=>{if(typeof d=="string")return d;if(d instanceof Error)return d.message;try{return JSON.stringify(d)}catch{return String(d)}}).join(" ");a+=` ${u}`}return a}static log(e,r,s,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,r,s,n);this.config.stderr?this.config.stderr(i):e==="warn"||e==="error"?process.stderr.write(i+`
2
2
  `):process.stdout.write(i+`
3
3
  `)}static createLogger(e){return{debug:(r,...s)=>{this.log("debug",e,r,s)},info:(r,...s)=>{this.log("info",e,r,s)},warn:(r,...s)=>{this.log("warn",e,r,s)},error:(r,...s)=>{this.log("error",e,r,s)}}}static getEffectiveLevel(){return this.effectiveLevel}};function pe(t){try{return JSON.stringify(t)+`
4
- `}catch(e){throw new Error(`Failed to serialize message to JSON: ${e instanceof Error?e.message:String(e)}`)}}function Lt(t,e="JsonLines"){let r=T.createLogger(e);try{return JSON.parse(t)}catch(s){return r.warn("Failed to parse JSON line, skipping:",t.substring(0,100),s instanceof Error?s.message:String(s)),null}}function Dt(t){return t!==null&&typeof t=="object"&&"type"in t&&typeof t.type=="string"}async function*tt(t,e="JsonLines"){let r=T.createLogger(e);for await(let s of t){if(s.trim().length===0)continue;let n=Lt(s,e);if(n!==null){if(!Dt(n)){r.warn("Invalid message structure (missing 'type' field), skipping:",s.substring(0,100));continue}yield n}}}var Se=require("node:child_process"),lt=Be(require("node:readline"),1);var j=Be(require("node:fs"),1),b=Be(require("node:path"),1),nt=require("node:child_process"),Fe=require("node:url"),it=require("node:module"),W={};function ot(){let t=null;try{typeof W<"u"&&W.url&&(t=b.dirname((0,Fe.fileURLToPath)(W.url)))}catch{}if(!t)try{typeof __dirname<"u"&&(t=__dirname)}catch{}if(t)return b.normalize(t);throw new Error("Cannot find module directory.")}function rt(){try{let i=(0,it.createRequire)(W.url).resolve("@qwen-code/sdk/package.json"),o=b.dirname(i),a=b.join(o,"dist","cli","cli.js");if(j.existsSync(a))return o}catch{}let e=ot(),r=b.parse(e).root,s=null;for(;e!==r;){let n=b.join(e,"package.json");if(j.existsSync(n)){let i=b.join(e,"dist","cli","cli.js");if(j.existsSync(i))try{if(JSON.parse(j.readFileSync(n,"utf-8")).name==="@qwen-code/sdk")return e;s||(s=e)}catch{s||(s=e)}}e=b.dirname(e)}return s}function Nt(t){return t.replace(/\\/g,"/")}function $t(){try{if(typeof W<"u"&&W.url){let t=(0,Fe.fileURLToPath)(W.url),e=b.dirname(t),r=b.join(e,"cli","cli.js");if(j.existsSync(r))return r}}catch{}return null}function at(){let t=[],e=$t();e&&t.push(e);try{let r=ot(),s=Nt(r);if(t.push(b.join(r,"cli","cli.js")),/\/src\/utils$/.test(s)){let o=b.dirname(b.dirname(r));t.push(b.join(o,"dist","cli","cli.js"))}let n=rt();n&&t.push(b.join(n,"dist","cli","cli.js"));let i=s.match(/^(.+?)\/packages\/sdk-typescript/);if(i&&i[1]){let o=process.platform==="win32"?i[1].replace(/\//g,"\\"):i[1];t.push(b.join(o,"dist","cli.js"))}}catch{let r=rt();r&&t.push(b.join(r,"dist","cli","cli.js"))}return t}function qt(){let t=at();for(let e of t)if(j.existsSync(e))return e;return null}function Ut(){let t=qt();if(t)return t;let e=at();throw new Error(`Bundled qwen CLI not found. The CLI should be included in the SDK package.
4
+ `}catch(e){throw new Error(`Failed to serialize message to JSON: ${e instanceof Error?e.message:String(e)}`)}}function Lt(t,e="JsonLines"){let r=T.createLogger(e);try{return JSON.parse(t)}catch(s){return r.warn("Failed to parse JSON line, skipping:",t.substring(0,100),s instanceof Error?s.message:String(s)),null}}function Dt(t){return t!==null&&typeof t=="object"&&"type"in t&&typeof t.type=="string"}async function*tt(t,e="JsonLines"){let r=T.createLogger(e);for await(let s of t){if(s.trim().length===0)continue;let n=Lt(s,e);if(n!==null){if(!Dt(n)){r.warn("Invalid message structure (missing 'type' field), skipping:",s.substring(0,100));continue}yield n}}}var Se=require("node:child_process"),lt=Be(require("node:readline"),1);var L=Be(require("node:fs"),1),b=Be(require("node:path"),1),nt=require("node:child_process"),Qe=require("node:url"),it=require("node:module"),W={};function ot(){let t=null;try{typeof W<"u"&&W.url&&(t=b.dirname((0,Qe.fileURLToPath)(W.url)))}catch{}if(!t)try{typeof __dirname<"u"&&(t=__dirname)}catch{}if(t)return b.normalize(t);throw new Error("Cannot find module directory.")}function rt(){try{let i=(0,it.createRequire)(W.url).resolve("@qwen-code/sdk/package.json"),o=b.dirname(i),a=b.join(o,"dist","cli","cli.js");if(L.existsSync(a))return o}catch{}let e=ot(),r=b.parse(e).root,s=null;for(;e!==r;){let n=b.join(e,"package.json");if(L.existsSync(n)){let i=b.join(e,"dist","cli","cli.js");if(L.existsSync(i))try{if(JSON.parse(L.readFileSync(n,"utf-8")).name==="@qwen-code/sdk")return e;s||(s=e)}catch{s||(s=e)}}e=b.dirname(e)}return s}function Nt(t){return t.replace(/\\/g,"/")}function $t(){try{if(typeof W<"u"&&W.url){let t=(0,Qe.fileURLToPath)(W.url),e=b.dirname(t),r=b.join(e,"cli","cli.js");if(L.existsSync(r))return r}}catch{}return null}function at(){let t=[],e=$t();e&&t.push(e);try{let r=ot(),s=Nt(r);if(t.push(b.join(r,"cli","cli.js")),/\/src\/utils$/.test(s)){let o=b.dirname(b.dirname(r));t.push(b.join(o,"dist","cli","cli.js"))}let n=rt();n&&t.push(b.join(n,"dist","cli","cli.js"));let i=s.match(/^(.+?)\/packages\/sdk-typescript/);if(i&&i[1]){let o=process.platform==="win32"?i[1].replace(/\//g,"\\"):i[1];t.push(b.join(o,"dist","cli.js"))}}catch{let r=rt();r&&t.push(b.join(r,"dist","cli","cli.js"))}return t}function qt(){let t=at();for(let e of t)if(L.existsSync(e))return e;return null}function Ut(){let t=qt();if(t)return t;let e=at();throw new Error(`Bundled qwen CLI not found. The CLI should be included in the SDK package.
5
5
  Searched locations:
6
6
  `+e.map(r=>` - ${r}`).join(`
7
7
  `)+`
8
8
 
9
9
  If you need to use a custom CLI, provide explicit path:
10
- \u2022 query({ pathToQwenExecutable: "/path/to/cli.js" })`)}function Zt(t){if(!j.existsSync(t))throw new Error(`Executable file not found at '${t}'. Please check the file path and ensure the file exists.`);if(!j.statSync(t).isFile())throw new Error(`Path '${t}' exists but is not a file. Please provide a path to an executable file.`)}function zt(t){return t.includes("/")||t.includes("\\")}function Kt(t){let e=b.extname(t).toLowerCase();return[".js",".mjs",".cjs"].includes(e)}function Vt(t){let e=b.extname(t).toLowerCase();return[".ts",".tsx"].includes(e)}function Bt(t){try{let e=process.platform==="win32"?"where":"which";return(0,nt.execSync)(`${e} ${t}`,{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Ft(){return Bt("tsx")}function st(){return typeof process<"u"&&"versions"in process&&"bun"in process.versions?"bun":"node"}function Me(t){if(t!==void 0&&t.trim()==="")throw new Error("Executable path cannot be empty");if(t===void 0){let r=Ut();return{command:process.execPath,args:[r],type:st(),originalInput:""}}if(!zt(t)){if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error(`Invalid command name '${t}'. Command names should only contain letters, numbers, dots, hyphens, and underscores.`);return{command:t,args:[],type:"native",originalInput:t}}let e=b.resolve(t);return Zt(e),Kt(e)?{command:process.execPath,args:[e],type:st(),originalInput:t}:Vt(e)&&Ft()?{command:"tsx",args:[e],type:"tsx",originalInput:t}:{command:e,args:[],type:"native",originalInput:t}}var w=class t extends Error{constructor(e="Operation aborted"){super(e),this.name="AbortError",Object.setPrototypeOf(this,t.prototype)}};function ct(t){return t instanceof w||typeof t=="object"&&t!==null&&"name"in t&&t.name==="AbortError"}var M=T.createLogger("ProcessTransport"),Ee=class{childProcess=null;childStdin=null;childStdout=null;options;ready=!1;_exitError=null;closed=!1;inputClosed=!1;abortController;processExitHandler=null;abortHandler=null;constructor(e){this.options=e,this.abortController=this.options.abortController??new AbortController,T.configure({debug:e.debug,stderr:e.stderr,logLevel:e.logLevel}),this.initialize()}initialize(){try{if(this.abortController.signal.aborted)throw new w("Transport start aborted");let e=this.buildCliArguments(),r=this.options.cwd??process.cwd(),s={...process.env,...this.options.env},n=this.options.spawnInfo??Me(this.options.pathToQwenExecutable),i=this.options.debug||this.options.stderr?"pipe":"ignore";if(s.FORK_MODE==="1"){let d=typeof process<"u"&&process.versions&&!!process.versions.electron,u=n.args.length>0&&(n.args[0]?.endsWith(".js")||n.args[0]?.endsWith(".mjs")||n.args[0]?.endsWith(".cjs")),m,k,D;if(d&&u?(m=n.args[0]??"",k=[...n.args.slice(1),...e]):(n.type==="node"||n.type==="bun")&&n.args.length>0?(m=n.args[0]??"",k=[...n.args.slice(1),...e],D=n.command):(M.debug(`FORK_MODE enabled but CLI type '${n.type}' does not support fork. Falling back to spawn.`),m="",k=[]),m){M.debug(`Forking CLI (${n.type}): ${m} ${k.join(" ")}`);let N={cwd:r,env:s,stdio:i==="pipe"?["pipe","pipe","pipe","ipc"]:["pipe","pipe","ignore","ipc"],signal:this.abortController.signal};D&&(N.execPath=D),this.childProcess=(0,Se.fork)(m,k,N)}else M.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=(0,Se.spawn)(n.command,[...n.args,...e],{cwd:r,env:s,stdio:["pipe","pipe",i],signal:this.abortController.signal})}else M.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=(0,Se.spawn)(n.command,[...n.args,...e],{cwd:r,env:s,stdio:["pipe","pipe",i],signal:this.abortController.signal});this.childStdin=this.childProcess.stdin,this.childStdout=this.childProcess.stdout,(this.options.debug||this.options.stderr)&&this.childProcess.stderr?.on("data",d=>{M.debug(d.toString())});let a=()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGTERM")};this.processExitHandler=a,this.abortHandler=a,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.setupEventHandlers(),this.ready=!0,M.info("CLI process started successfully")}catch(e){throw this.ready=!1,M.error("Failed to initialize CLI process:",e),e}}setupEventHandlers(){this.childProcess&&(this.childProcess.on("error",e=>{this.ready=!1,this.abortController.signal.aborted?this._exitError=new w("CLI process aborted by user"):(this._exitError=new Error(`CLI process error: ${e.message}`),M.error(this._exitError.message))}),this.childProcess.on("close",(e,r)=>{if(this.ready=!1,this.abortController.signal.aborted)this._exitError=new w("CLI process aborted by user");else{let s=this.getProcessExitError(e,r);s&&(this._exitError=s,M.error(s.message))}}))}getProcessExitError(e,r){if(e!==0&&e!==null)return new Error(`CLI process exited with code ${e}`);if(r)return new Error(`CLI process terminated by signal ${r}`)}buildCliArguments(){let e=["--input-format","stream-json","--output-format","stream-json","--channel=SDK"];return this.options.model&&e.push("--model",this.options.model),this.options.permissionMode&&e.push("--approval-mode",this.options.permissionMode),this.options.maxSessionTurns!==void 0&&e.push("--max-session-turns",String(this.options.maxSessionTurns)),this.options.coreTools&&this.options.coreTools.length>0&&e.push("--core-tools",this.options.coreTools.join(",")),this.options.excludeTools&&this.options.excludeTools.length>0&&e.push("--exclude-tools",this.options.excludeTools.join(",")),this.options.allowedTools&&this.options.allowedTools.length>0&&e.push("--allowed-tools",this.options.allowedTools.join(",")),this.options.authType&&e.push("--auth-type",this.options.authType),this.options.includePartialMessages&&e.push("--include-partial-messages"),this.options.resume?e.push("--resume",this.options.resume):this.options.continue?e.push("--continue"):this.options.sessionId&&e.push("--session-id",this.options.sessionId),e}async close(){this.childStdin&&(this.childStdin.end(),this.childStdin=null),this.processExitHandler&&(process.off("exit",this.processExitHandler),this.processExitHandler=null),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.childProcess&&!this.childProcess.killed&&(this.childProcess.kill("SIGTERM"),setTimeout(()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGKILL")},5e3)),this.ready=!1,this.closed=!0,this.inputClosed=!0}async waitForExit(){if(!this.childProcess){if(this._exitError)throw this._exitError;return}if(this.childProcess.exitCode!==null||this.childProcess.killed){if(this._exitError)throw this._exitError;return}return new Promise((e,r)=>{let s=(i,o)=>{if(this.abortController.signal.aborted){r(new w("Operation aborted"));return}let a=this.getProcessExitError(i,o);a?r(a):e()};this.childProcess.once("close",s);let n=i=>{this.childProcess.off("close",s),r(i)};this.childProcess.once("error",n),this.childProcess.once("close",()=>{this.childProcess.off("error",n)})})}write(e){if(this.abortController.signal.aborted)throw new w("Cannot write: operation aborted");if(!this.ready||!this.childStdin)throw new Error("Transport not ready for writing");if(this.closed)throw new Error("Cannot write to closed transport");if(this.inputClosed)throw new Error("Input stream closed");if(this.childStdin.writableEnded||this.childStdin.destroyed)throw this.inputClosed=!0,M.warn(`Cannot write to ${this.childStdin.writableEnded?"ended":"destroyed"} stdin stream`),new Error("Input stream closed");if(this.childProcess?.killed||this.childProcess?.exitCode!==null)throw new Error("Cannot write to terminated process");if(this._exitError)throw new Error(`Cannot write to process that exited with error: ${this._exitError.message}`);M.debug(`Writing to stdin (${e.length} bytes): ${e.trim()}`);try{this.childStdin.write(e)?M.debug(`Write successful (${e.length} bytes)`):M.warn(`Write buffer full (${e.length} bytes), data queued. Waiting for drain event...`)}catch(r){let s=r instanceof Error?r.message:String(r);if(s.includes("EPIPE")||s.includes("ERR_STREAM_WRITE_AFTER_END")||s.includes("write after end"))throw this.inputClosed=!0,M.warn(`Stream closed, cannot write: ${s}`),new Error("Input stream closed");this.ready=!1;let i=`Failed to write to stdin: ${s}`;throw M.error(i),new Error(i)}}async*readMessages(){if(!this.childStdout)throw new Error("Cannot read messages: process not started");let e=lt.createInterface({input:this.childStdout,crlfDelay:1/0,terminal:!1});try{for await(let r of tt(e,"ProcessTransport"))yield r;await this.waitForExit()}finally{e.close()}}get isReady(){return this.ready}get exitError(){return this._exitError}endInput(){this.childStdin&&(this.childStdin.end(),this.inputClosed=!0)}getInputStream(){return this.childStdin||void 0}getOutputStream(){return this.childStdout||void 0}};var Qe=require("node:crypto");function Ie(t){return t&&typeof t=="object"&&t.type==="user"&&"message"in t}function Pe(t){return t&&typeof t=="object"&&t.type==="assistant"&&"uuid"in t&&"message"in t&&"session_id"in t&&"parent_tool_use_id"in t}function Ae(t){return t&&typeof t=="object"&&t.type==="system"&&"subtype"in t&&"uuid"in t&&"session_id"in t}function Oe(t){return t&&typeof t=="object"&&t.type==="result"&&"subtype"in t&&"duration_ms"in t&&"is_error"in t&&"uuid"in t&&"session_id"in t}function je(t){return t&&typeof t=="object"&&t.type==="stream_event"&&"uuid"in t&&"session_id"in t&&"event"in t&&"parent_tool_use_id"in t}function Le(t){return t&&typeof t=="object"&&t.type==="control_request"&&"request_id"in t&&"request"in t}function De(t){return t&&typeof t=="object"&&t.type==="control_response"&&"response"in t}function Ne(t){return t&&typeof t=="object"&&t.type==="control_cancel_request"&&"request_id"in t}function ke(t){return"type"in t&&t.type==="sdk"}var $e=class{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}[Symbol.asyncIterator](){if(this.started)throw new Error("Stream can only be iterated once");return this.started=!0,this}async next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.hasError?Promise.reject(this.hasError):this.isDone?Promise.resolve({done:!0,value:void 0}):new Promise((e,r)=>{this.readResolve=e,this.readReject=r})}enqueue(e){if(this.readResolve){let r=this.readResolve;this.readResolve=void 0,this.readReject=void 0,r({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let r=this.readReject;this.readResolve=void 0,this.readReject=void 0,r(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};var qe=class{sendToQuery;serverName;started=!1;logger;onmessage;onerror;onclose;constructor(e){this.sendToQuery=e.sendToQuery,this.serverName=e.serverName,this.logger=T.createLogger(`SdkControlServerTransport:${e.serverName}`)}async start(){this.started=!0,this.logger.debug("Transport started")}async send(e){if(!this.started)throw new Error(`SdkControlServerTransport (${this.serverName}) not started. Call start() first.`);try{this.logger.debug("Sending message to Query",e),await this.sendToQuery(e)}catch(r){throw this.logger.error("Error sending message:",r),this.onerror&&this.onerror(r instanceof Error?r:new Error(String(r))),r}}async close(){this.started&&(this.started=!1,this.logger.debug("Transport closed"),this.onclose&&this.onclose())}handleMessage(e){if(!this.started){this.logger.warn("Received message for closed transport");return}this.logger.debug("Handling message from CLI",e),this.onmessage?this.onmessage(e):this.logger.warn("No onmessage handler set")}handleError(e){this.logger.error("Transport error:",e),this.onerror&&this.onerror(e)}isStarted(){return this.started}getServerName(){return this.serverName}};var Qt=6e4,Jt=6e4,Wt=6e4,Ht=6e4,S=T.createLogger("Query"),fe=class{transport;options;sessionId;inputStream;sdkMessages;abortController;pendingControlRequests=new Map;pendingMcpResponses=new Map;sdkMcpTransports=new Map;sdkMcpServers=new Map;initialized;closed=!1;messageRouterStarted=!1;firstResultReceivedPromise;firstResultReceivedResolve;isSingleTurn;abortHandler=null;constructor(e,r,s=!1){this.transport=e,this.options=r,this.sessionId=r.resume??r.sessionId??(0,Qe.randomUUID)(),this.inputStream=new $e,this.abortController=r.abortController??new AbortController,this.isSingleTurn=s,this.sdkMessages=this.readSdkMessages(),this.firstResultReceivedPromise=new Promise(n=>{this.firstResultReceivedResolve=n}),this.abortController.signal.aborted?(this.inputStream.error(new w("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})):(this.abortHandler=()=>{this.inputStream.error(new w("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})},this.abortController.signal.addEventListener("abort",this.abortHandler)),this.initialized=this.initialize(),this.initialized.catch(n=>{let i=n instanceof Error?n.message:String(n);i.includes("Query is closed")&&this.transport.exitError?this.inputStream.error(this.transport.exitError):this.inputStream.error(n instanceof Error?n:new Error(i))}),this.startMessageRouter()}async initializeSdkMcpServers(){if(!this.options.mcpServers)return;let e=[];for(let[r,s]of Object.entries(this.options.mcpServers)){if(!ke(s))continue;let n=s.name||r,i=s.instance,o={sendToQuery:async u=>{this.handleMcpServerResponse(n,u)},serverName:n},a=new qe(o),d=i.connect(a).then(()=>{this.sdkMcpServers.set(n,i),this.sdkMcpTransports.set(n,a),S.debug(`SDK MCP server '${n}' connected to transport`)}).catch(u=>{S.error(`Failed to connect SDK MCP server '${n}' to transport:`,u)});e.push(d)}await Promise.all(e),this.sdkMcpServers.size>0&&S.info(`Initialized ${this.sdkMcpServers.size} SDK MCP server(s): ${Array.from(this.sdkMcpServers.keys()).join(", ")}`)}handleMcpServerResponse(e,r){if("id"in r&&r.id!==null&&r.id!==void 0){let s=`${e}:${r.id}`,n=this.pendingMcpResponses.get(s);if(n){S.debug(`Routing MCP response for server '${e}', id: ${r.id}`),n.resolve(r),this.pendingMcpResponses.delete(s);return}}S.warn(`Received MCP server response with no pending request: server='${e}'`,r)}getSdkMcpServersForCli(){let e={};for(let[r]of this.sdkMcpServers.entries())e[r]={type:"sdk",name:r};return e}getMcpServersForCli(){if(!this.options.mcpServers)return{};let e={};for(let[r,s]of Object.entries(this.options.mcpServers))ke(s)||(e[r]=s);return e}async initialize(){try{S.debug("Initializing Query"),await this.initializeSdkMcpServers();let e=this.getSdkMcpServersForCli(),r=this.getMcpServersForCli();await this.sendControlRequest("initialize",{hooks:null,sdkMcpServers:Object.keys(e).length>0?e:void 0,mcpServers:Object.keys(r).length>0?r:void 0,agents:this.options.agents}),S.info("Query initialized successfully")}catch(e){throw S.error("Initialization error:",e),e}}startMessageRouter(){this.messageRouterStarted||(this.messageRouterStarted=!0,(async()=>{try{for await(let e of this.transport.readMessages())if(await this.routeMessage(e),this.closed)break;this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done()}catch(e){this.inputStream.error(e instanceof Error?e:new Error(String(e)))}})())}async routeMessage(e){if(Le(e)){await this.handleControlRequest(e);return}if(De(e)){this.handleControlResponse(e);return}if(Ne(e)){this.handleControlCancelRequest(e);return}if(Ae(e)){this.inputStream.enqueue(e);return}if(Oe(e)){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleTurn&&"endInput"in this.transport&&this.transport.endInput(),this.inputStream.enqueue(e);return}if(Pe(e)||Ie(e)||je(e)){this.inputStream.enqueue(e);return}S.warn("Unknown message type:",e),this.inputStream.enqueue(e)}async handleControlRequest(e){let{request_id:r,request:s}=e;S.debug(`Handling control request: ${s.subtype}`);let n=new AbortController;try{let i=null;switch(s.subtype){case"can_use_tool":i=await this.handlePermissionRequest(s.tool_name,s.input,s.permission_suggestions,n.signal);break;case"mcp_message":i=await this.handleMcpMessage(s.server_name,s.message);break;default:throw new Error(`Unknown control request subtype: ${s.subtype}`)}await this.sendControlResponse(r,!0,i)}catch(i){let o=i instanceof Error?i.message:String(i);S.error(`Control request error (${s.subtype}):`,o),await this.sendControlResponse(r,!1,o)}}async handlePermissionRequest(e,r,s,n){if(!this.options.canUseTool)return{behavior:"deny",message:"Denied"};try{let i=this.options.timeout?.canUseTool??Qt,o,a=new Promise((u,m)=>{o=setTimeout(()=>m(new Error("Permission callback timeout")),i)}),d=await Promise.race([Promise.resolve(this.options.canUseTool(e,r,{signal:n,suggestions:s})),a]);return o&&clearTimeout(o),d.behavior==="allow"?{behavior:"allow",updatedInput:d.updatedInput??r}:{behavior:"deny",message:d.message??"Denied",...d.interrupt!==void 0?{interrupt:d.interrupt}:{}}}catch(i){let o=i instanceof Error?i.message:String(i);return S.warn("Permission callback error (denying by default):",o),{behavior:"deny",message:`Permission check failed: ${o}`}}}async handleMcpMessage(e,r){let s=this.sdkMcpTransports.get(e);if(!s)throw new Error(`MCP server '${e}' not found in SDK-embedded servers`);return"method"in r&&"id"in r&&r.id!==null?{mcp_response:await this.handleMcpRequest(e,r,s)}:(s.handleMessage(r),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}handleMcpRequest(e,r,s){let n="id"in r?r.id:null,i=`${e}:${n}`;return new Promise((o,a)=>{let d=this.options.timeout?.mcpRequest??Jt,u=setTimeout(()=>{this.pendingMcpResponses.delete(i),a(new Error("MCP request timeout"))},d),m=()=>{clearTimeout(u),this.pendingMcpResponses.delete(i)},k=N=>{m(),o(N)},D=N=>{m(),a(N)};this.pendingMcpResponses.set(i,{resolve:k,reject:D}),s.handleMessage(r)})}handleControlResponse(e){let{response:r}=e,s=r.request_id,n=this.pendingControlRequests.get(s);if(!n){S.warn("Received response for unknown request:",s,JSON.stringify(r));return}if(clearTimeout(n.timeout),this.pendingControlRequests.delete(s),r.subtype==="success")S.debug(`Control response success for request: ${s}: ${JSON.stringify(r.response)}`),n.resolve(r.response);else{let i=typeof r.error=="string"?r.error:r.error?.message??"Unknown error";S.error(`Control response error for request ${s}:`,i),n.reject(new Error(i))}}handleControlCancelRequest(e){let{request_id:r}=e;if(!r){S.warn("Received cancel request without request_id");return}let s=this.pendingControlRequests.get(r);s&&(S.debug(`Cancelling control request: ${r}`),s.abortController.abort(),clearTimeout(s.timeout),this.pendingControlRequests.delete(r),s.reject(new w("Request cancelled")))}async sendControlRequest(e,r={}){if(this.closed)return Promise.reject(new Error("Query is closed"));if(this.transport.exitError)return Promise.reject(this.transport.exitError);e!=="initialize"&&await this.initialized;let s=(0,Qe.randomUUID)(),n={type:"control_request",request_id:s,request:{subtype:e,...r}},i=new Promise((o,a)=>{let d=new AbortController,u=this.options.timeout?.controlRequest??Wt,m=setTimeout(()=>{this.pendingControlRequests.delete(s),a(new Error(`Control request timeout: ${e}`))},u);this.pendingControlRequests.set(s,{resolve:o,reject:a,timeout:m,abortController:d})});try{this.transport.write(pe(n))}catch(o){let a=this.pendingControlRequests.get(s);a&&(clearTimeout(a.timeout),this.pendingControlRequests.delete(s));let d=o instanceof Error?o.message:String(o);return S.error(`Failed to send control request: ${d}`),Promise.reject(new Error(`Failed to send control request: ${d}`))}return i}async sendControlResponse(e,r,s){let n={type:"control_response",response:r?{subtype:"success",request_id:e,response:s}:{subtype:"error",request_id:e,error:s}};try{this.transport.write(pe(n))}catch(i){let o=i instanceof Error?i.message:String(i);S.warn(`Failed to send control response for request ${e}: ${o}`)}}async close(){if(this.closed)return;this.closed=!0,this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null);let r=this.transport.exitError??new Error("Query is closed");for(let s of this.pendingControlRequests.values())s.abortController.abort(),clearTimeout(s.timeout),s.reject(r);this.pendingControlRequests.clear();for(let s of this.pendingMcpResponses.values())s.reject(r);this.pendingMcpResponses.clear(),await this.transport.close(),this.inputStream.hasError===void 0&&(this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done());for(let s of this.sdkMcpTransports.values())try{await s.close()}catch(n){S.error("Error closing MCP transport:",n)}this.sdkMcpTransports.clear(),S.info("Query is closed")}async*readSdkMessages(){for await(let e of this.inputStream)yield e}async next(...e){return this.sdkMessages.next(...e)}async return(e){return this.sdkMessages.return(e)}async throw(e){return this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async streamInput(e){if(this.closed)throw new Error("Query is closed");try{await this.initialized;for await(let r of e){if(this.abortController.signal.aborted)break;this.transport.write(pe(r))}if(this.firstResultReceivedPromise){let r=this.options.timeout?.streamClose??Ht,s,n=new Promise(i=>{s=setTimeout(()=>{S.info("streamCloseTimeout resolved"),i()},r)});await Promise.race([this.firstResultReceivedPromise,n]),s&&clearTimeout(s)}this.endInput()}catch(r){if(this.abortController.signal.aborted){S.info("Aborted during input streaming"),this.inputStream.error(new w("Query aborted during input streaming"));return}throw r}}endInput(){if(this.closed)throw new Error("Query is closed");"endInput"in this.transport&&typeof this.transport.endInput=="function"&&this.transport.endInput()}async interrupt(){await this.sendControlRequest("interrupt")}async setPermissionMode(e){await this.sendControlRequest("set_permission_mode",{mode:e})}async setModel(e){await this.sendControlRequest("set_model",{model:e})}async supportedCommands(){return this.sendControlRequest("supported_commands")}async mcpServerStatus(){return this.sendControlRequest("mcp_server_status")}getSessionId(){return this.sessionId}isClosed(){return this.closed}};var l={};Ye(l,{BRAND:()=>Sr,DIRTY:()=>H,EMPTY_PATH:()=>er,INVALID:()=>g,NEVER:()=>os,OK:()=>R,ParseStatus:()=>C,Schema:()=>_,ZodAny:()=>Q,ZodArray:()=>V,ZodBigInt:()=>Y,ZodBoolean:()=>X,ZodBranded:()=>Ce,ZodCatch:()=>ue,ZodDate:()=>ee,ZodDefault:()=>le,ZodDiscriminatedUnion:()=>ze,ZodEffects:()=>O,ZodEnum:()=>ae,ZodError:()=>E,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Ve,ZodIntersection:()=>ne,ZodIssueCode:()=>c,ZodLazy:()=>ie,ZodLiteral:()=>oe,ZodMap:()=>_e,ZodNaN:()=>be,ZodNativeEnum:()=>ce,ZodNever:()=>L,ZodNull:()=>re,ZodNullable:()=>U,ZodNumber:()=>G,ZodObject:()=>I,ZodOptional:()=>P,ZodParsedType:()=>f,ZodPipeline:()=>Te,ZodPromise:()=>J,ZodReadonly:()=>de,ZodRecord:()=>Ke,ZodSchema:()=>_,ZodSet:()=>xe,ZodString:()=>F,ZodSymbol:()=>ye,ZodTransformer:()=>O,ZodTuple:()=>q,ZodType:()=>_,ZodUndefined:()=>te,ZodUnion:()=>se,ZodUnknown:()=>K,ZodVoid:()=>ve,addIssueToContext:()=>p,any:()=>Pr,array:()=>Lr,bigint:()=>Tr,boolean:()=>xt,coerce:()=>is,custom:()=>yt,date:()=>Rr,datetimeRegex:()=>mt,defaultErrorMap:()=>Z,discriminatedUnion:()=>qr,effect:()=>Gr,enum:()=>Jr,function:()=>Br,getErrorMap:()=>he,getParsedType:()=>$,instanceof:()=>wr,intersection:()=>Ur,isAborted:()=>Ue,isAsync:()=>me,isDirty:()=>Ze,isValid:()=>B,late:()=>kr,lazy:()=>Fr,literal:()=>Qr,makeIssue:()=>we,map:()=>Kr,nan:()=>Cr,nativeEnum:()=>Wr,never:()=>Or,null:()=>Ir,nullable:()=>Xr,number:()=>_t,object:()=>Dr,objectUtil:()=>Je,oboolean:()=>ns,onumber:()=>ss,optional:()=>Yr,ostring:()=>rs,pipeline:()=>ts,preprocess:()=>es,promise:()=>Hr,quotelessJson:()=>Gt,record:()=>zr,set:()=>Vr,setErrorMap:()=>Xt,strictObject:()=>Nr,string:()=>vt,symbol:()=>Mr,transformer:()=>Gr,tuple:()=>Zr,undefined:()=>Er,union:()=>$r,unknown:()=>Ar,util:()=>x,void:()=>jr});var x;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(let o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var Je;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Je||(Je={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$=t=>{switch(typeof t){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(t)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(t)?f.array:t===null?f.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?f.promise:typeof Map<"u"&&t instanceof Map?f.map:typeof Set<"u"&&t instanceof Set?f.set:typeof Date<"u"&&t instanceof Date?f.date:f.object;default:return f.unknown}};var c=x.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"]),Gt=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),E=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,d=0;for(;d<o.path.length;){let u=o.path[d];d===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],d++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};E.create=t=>new E(t);var Yt=(t,e)=>{let r;switch(t.code){case c.invalid_type:t.received===f.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:x.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case c.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case c.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=e.defaultError,x.assertNever(t)}return{message:r}},Z=Yt;var ut=Z;function Xt(t){ut=t}function he(){return ut}var we=t=>{let{data:e,path:r,errorMaps:s,issueData:n}=t,i=[...r,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",d=s.filter(u=>!!u).slice().reverse();for(let u of d)a=u(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},er=[];function p(t,e){let r=he(),s=we({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Z?void 0:Z].filter(n=>!!n)});t.common.issues.push(s)}var C=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let n of r){if(n.status==="aborted")return g;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let n of r){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let n of r){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return g;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},g=Object.freeze({status:"aborted"}),H=t=>({status:"dirty",value:t}),R=t=>({status:"valid",value:t}),Ue=t=>t.status==="aborted",Ze=t=>t.status==="dirty",B=t=>t.status==="valid",me=t=>typeof Promise<"u"&&t instanceof Promise;var h;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var A=class{constructor(e,r,s,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=n}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}},dt=(t,e)=>{if(B(e))return{success:!0,data:e.value};if(!t.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 E(t.common.issues);return this._error=r,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:n}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,a)=>{let{message:d}=t;return o.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:d??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:d??r??a.defaultError}},description:n}}var _=class{get description(){return this._def.description}_getType(e){return $(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(me(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)},n=this._parseSync({data:e,path:s.path,parent:s});return dt(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return B(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>B(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(me(n)?n:Promise.resolve(n));return dt(s,i)}refine(e,r){let s=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let o=e(n),a=()=>i.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof r=="function"?r(s,n):r),!1))}_refinement(e){return new O({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 P.create(this,this._def)}nullable(){return U.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this)}promise(){return J.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return ne.create(this,e,this._def)}transform(e){return new O({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new le({...v(this._def),innerType:this,defaultValue:r,typeName:y.ZodDefault})}brand(){return new Ce({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ue({...v(this._def),innerType:this,catchValue:r,typeName:y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Te.create(this,e)}readonly(){return de.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tr=/^c[^\s-]{8,}$/i,rr=/^[0-9a-z]+$/,sr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nr=/^[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,ir=/^[a-z0-9_-]{21}$/i,or=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ar=/^[-+]?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)?)??$/,cr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",We,ur=/^(?:(?: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])$/,dr=/^(?:(?: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])$/,pr=/^(([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]))$/,fr=/^(([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])$/,hr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ft="((\\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])))",gr=new RegExp(`^${ft}$`);function ht(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function yr(t){return new RegExp(`^${ht(t)}$`)}function mt(t){let e=`${ft}T${ht(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vr(t,e){return!!((e==="v4"||!e)&&ur.test(t)||(e==="v6"||!e)&&pr.test(t))}function _r(t,e){if(!or.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function xr(t,e){return!!((e==="v4"||!e)&&dr.test(t)||(e==="v6"||!e)&&fr.test(t))}var F=class t extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_type,expected:f.string,received:i.parsedType}),g}let s=new C,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(n=this._getOrReturnCtx(e,n),o?p(n,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&p(n,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")cr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")We||(We=new RegExp(lr,"u")),We.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")nr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ir.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")tr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")rr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")sr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:c.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:c.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:c.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?mt(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?gr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?yr(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ar.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?vr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?_r(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?xr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?hr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?mr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:c.invalid_string,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(n=>e.test(n),{validation:r,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};F.create=t=>new F({checks:[],typeName:y.ZodString,coerce:t?.coerce??!1,...v(t)});function br(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=r>s?r:s,i=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var G=class t extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_type,expected:f.number,received:i.parsedType}),g}let s,n=new C;for(let i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:c.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?br(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:c.not_finite,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};G.create=t=>new G({checks:[],typeName:y.ZodNumber,coerce:t?.coerce||!1,...v(t)});var Y=class t extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s,n=new C;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),p(s,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return p(r,{code:c.invalid_type,expected:f.bigint,received:r.parsedType}),g}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Y.create=t=>new Y({checks:[],typeName:y.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var X=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.boolean,received:s.parsedType}),g}return R(e.data)}};X.create=t=>new X({typeName:y.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var ee=class t extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_type,expected:f.date,received:i.parsedType}),g}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_date}),g}let s=new C,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:c.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:c.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):x.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ee.create=t=>new ee({checks:[],coerce:t?.coerce||!1,typeName:y.ZodDate,...v(t)});var ye=class extends _{_parse(e){if(this._getType(e)!==f.symbol){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.symbol,received:s.parsedType}),g}return R(e.data)}};ye.create=t=>new ye({typeName:y.ZodSymbol,...v(t)});var te=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.undefined,received:s.parsedType}),g}return R(e.data)}};te.create=t=>new te({typeName:y.ZodUndefined,...v(t)});var re=class extends _{_parse(e){if(this._getType(e)!==f.null){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.null,received:s.parsedType}),g}return R(e.data)}};re.create=t=>new re({typeName:y.ZodNull,...v(t)});var Q=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return R(e.data)}};Q.create=t=>new Q({typeName:y.ZodAny,...v(t)});var K=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return R(e.data)}};K.create=t=>new K({typeName:y.ZodUnknown,...v(t)});var L=class extends _{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:c.invalid_type,expected:f.never,received:r.parsedType}),g}};L.create=t=>new L({typeName:y.ZodNever,...v(t)});var ve=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.void,received:s.parsedType}),g}return R(e.data)}};ve.create=t=>new ve({typeName:y.ZodVoid,...v(t)});var V=class t extends _{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),n=this._def;if(r.parsedType!==f.array)return p(r,{code:c.invalid_type,expected:f.array,received:r.parsedType}),g;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(o||a)&&(p(r,{code:o?c.too_big:c.too_small,minimum:a?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(p(r,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(p(r,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>n.type._parseAsync(new A(r,o,r.path,a)))).then(o=>C.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new A(r,o,r.path,a)));return C.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};V.create=(t,e)=>new V({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function ge(t){if(t instanceof I){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=P.create(ge(s))}return new I({...t._def,shape:()=>e})}else return t instanceof V?new V({...t._def,type:ge(t.element)}):t instanceof P?P.create(ge(t.unwrap())):t instanceof U?U.create(ge(t.unwrap())):t instanceof q?q.create(t.items.map(e=>ge(e))):t}var I=class t extends _{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=x.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:c.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof L&&this._def.unknownKeys==="strip"))for(let u in n.data)o.includes(u)||a.push(u);let d=[];for(let u of o){let m=i[u],k=n.data[u];d.push({key:{status:"valid",value:u},value:m._parse(new A(n,k,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof L){let u=this._def.unknownKeys;if(u==="passthrough")for(let m of a)d.push({key:{status:"valid",value:m},value:{status:"valid",value:n.data[m]}});else if(u==="strict")a.length>0&&(p(n,{code:c.unrecognized_keys,keys:a}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let m of a){let k=n.data[m];d.push({key:{status:"valid",value:m},value:u._parse(new A(n,k,n.path,m)),alwaysSet:m in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let m of d){let k=await m.key,D=await m.value;u.push({key:k,value:D,alwaysSet:m.alwaysSet})}return u}).then(u=>C.mergeObjectSync(s,u)):C.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let n=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of x.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of x.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return ge(this)}partial(e){let r={};for(let s of x.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?r[s]=n:r[s]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of x.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof P;)i=i._def.innerType;r[s]=i}return new t({...this._def,shape:()=>r})}keyof(){return gt(x.objectKeys(this.shape))}};I.create=(t,e)=>new I({shape:()=>t,unknownKeys:"strip",catchall:L.create(),typeName:y.ZodObject,...v(e)});I.strictCreate=(t,e)=>new I({shape:()=>t,unknownKeys:"strict",catchall:L.create(),typeName:y.ZodObject,...v(e)});I.lazycreate=(t,e)=>new I({shape:t,unknownKeys:"strip",catchall:L.create(),typeName:y.ZodObject,...v(e)});var se=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new E(a.ctx.common.issues));return p(r,{code:c.invalid_union,unionErrors:o}),g}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let d of s){let u={...r,common:{...r.common,issues:[]},parent:null},m=d._parseSync({data:r.data,path:r.path,parent:u});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(d=>new E(d));return p(r,{code:c.invalid_union,unionErrors:a}),g}}get options(){return this._def.options}};se.create=(t,e)=>new se({options:t,typeName:y.ZodUnion,...v(e)});var z=t=>t instanceof ie?z(t.schema):t instanceof O?z(t.innerType()):t instanceof oe?[t.value]:t instanceof ae?t.options:t instanceof ce?x.objectValues(t.enum):t instanceof le?z(t._def.innerType):t instanceof te?[void 0]:t instanceof re?[null]:t instanceof P?[void 0,...z(t.unwrap())]:t instanceof U?[null,...z(t.unwrap())]:t instanceof Ce||t instanceof de?z(t.unwrap()):t instanceof ue?z(t._def.innerType):[],ze=class t extends _{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:c.invalid_type,expected:f.object,received:r.parsedType}),g;let s=this.discriminator,n=r.data[s],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(p(r,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let n=new Map;for(let i of r){let o=z(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...v(s)})}};function He(t,e){let r=$(t),s=$(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=x.objectKeys(e),i=x.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let d=He(t[a],e[a]);if(!d.valid)return{valid:!1};o[a]=d.data}return{valid:!0,data:o}}else if(r===f.array&&s===f.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],d=He(o,a);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return r===f.date&&s===f.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ne=class extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ue(i)||Ue(o))return g;let a=He(i.value,o.value);return a.valid?((Ze(i)||Ze(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:c.invalid_intersection_types}),g)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ne.create=(t,e,r)=>new ne({left:t,right:e,typeName:y.ZodIntersection,...v(r)});var q=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),g;if(s.data.length<this._def.items.length)return p(s,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...s.data].map((o,a)=>{let d=this._def.items[a]||this._def.rest;return d?d._parse(new A(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>C.mergeArray(r,o)):C.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};q.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new q({items:t,typeName:y.ZodTuple,rest:null,...v(e)})};var Ke=class t extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),g;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new A(s,a,s.path,a)),value:o._parse(new A(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?C.mergeObjectAsync(r,n):C.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof _?new t({keyType:e,valueType:r,typeName:y.ZodRecord,...v(s)}):new t({keyType:F.create(),valueType:e,typeName:y.ZodRecord,...v(r)})}},_e=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),g;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,d],u)=>({key:n._parse(new A(s,a,s.path,[u,"key"])),value:i._parse(new A(s,d,s.path,[u,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let d of o){let u=await d.key,m=await d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&r.dirty(),a.set(u.value,m.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let d of o){let u=d.key,m=d.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&r.dirty(),a.set(u.value,m.value)}return{status:r.value,value:a}}}};_e.create=(t,e,r)=>new _e({valueType:e,keyType:t,typeName:y.ZodMap,...v(r)});var xe=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),g;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(p(s,{code:c.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(p(s,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function o(d){let u=new Set;for(let m of d){if(m.status==="aborted")return g;m.status==="dirty"&&r.dirty(),u.add(m.value)}return{status:r.value,value:u}}let a=[...s.data.values()].map((d,u)=>i._parse(new A(s,d,s.path,u)));return s.common.async?Promise.all(a).then(d=>o(d)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};xe.create=(t,e)=>new xe({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var Ve=class t extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.function)return p(r,{code:c.invalid_type,expected:f.function,received:r.parsedType}),g;function s(a,d){return we({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,he(),Z].filter(u=>!!u),issueData:{code:c.invalid_arguments,argumentsError:d}})}function n(a,d){return we({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,he(),Z].filter(u=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:d}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof J){let a=this;return R(async function(...d){let u=new E([]),m=await a._def.args.parseAsync(d,i).catch(N=>{throw u.addIssue(s(d,N)),u}),k=await Reflect.apply(o,this,m);return await a._def.returns._def.type.parseAsync(k,i).catch(N=>{throw u.addIssue(n(k,N)),u})})}else{let a=this;return R(function(...d){let u=a._def.args.safeParse(d,i);if(!u.success)throw new E([s(d,u.error)]);let m=Reflect.apply(o,this,u.data),k=a._def.returns.safeParse(m,i);if(!k.success)throw new E([n(m,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:q.create(e).rest(K.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||q.create([]).rest(K.create()),returns:r||K.create(),typeName:y.ZodFunction,...v(s)})}},ie=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ie.create=(t,e)=>new ie({getter:t,typeName:y.ZodLazy,...v(e)});var oe=class extends _{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return p(r,{received:r.data,code:c.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};oe.create=(t,e)=>new oe({value:t,typeName:y.ZodLiteral,...v(e)});function gt(t,e){return new ae({values:t,typeName:y.ZodEnum,...v(e)})}var ae=class t extends _{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:x.joinValues(s),received:r.parsedType,code:c.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{received:r.data,code:c.invalid_enum_value,options:s}),g}return R(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};ae.create=gt;var ce=class extends _{_parse(e){let r=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=x.objectValues(r);return p(s,{expected:x.joinValues(n),received:s.parsedType,code:c.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=x.objectValues(r);return p(s,{received:s.data,code:c.invalid_enum_value,options:n}),g}return R(e.data)}get enum(){return this._def.values}};ce.create=(t,e)=>new ce({values:t,typeName:y.ZodNativeEnum,...v(e)});var J=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.promise&&r.common.async===!1)return p(r,{code:c.invalid_type,expected:f.promise,received:r.parsedType}),g;let s=r.parsedType===f.promise?r.data:Promise.resolve(r.data);return R(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};J.create=(t,e)=>new J({type:t,typeName:y.ZodPromise,...v(e)});var O=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return g;let d=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return d.status==="aborted"?g:d.status==="dirty"?H(d.value):r.value==="dirty"?H(d.value):d});{if(r.value==="aborted")return g;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?g:a.status==="dirty"?H(a.value):r.value==="dirty"?H(a.value):a}}if(n.type==="refinement"){let o=a=>{let d=n.refinement(a,i);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?g:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?g:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!B(o))return g;let a=n.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>B(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):g);x.assertNever(n)}};O.create=(t,e,r)=>new O({schema:t,typeName:y.ZodEffects,effect:e,...v(r)});O.createWithPreprocess=(t,e,r)=>new O({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,...v(r)});var P=class extends _{_parse(e){return this._getType(e)===f.undefined?R(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};P.create=(t,e)=>new P({innerType:t,typeName:y.ZodOptional,...v(e)});var U=class extends _{_parse(e){return this._getType(e)===f.null?R(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};U.create=(t,e)=>new U({innerType:t,typeName:y.ZodNullable,...v(e)});var le=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};le.create=(t,e)=>new le({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ue=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return me(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ue.create=(t,e)=>new ue({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var be=class extends _{_parse(e){if(this._getType(e)!==f.nan){let s=this._getOrReturnCtx(e);return p(s,{code:c.invalid_type,expected:f.nan,received:s.parsedType}),g}return{status:"valid",value:e.data}}};be.create=t=>new be({typeName:y.ZodNaN,...v(t)});var Sr=Symbol("zod_brand"),Ce=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Te=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?g:i.status==="dirty"?(r.dirty(),H(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?g:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:y.ZodPipeline})}},de=class extends _{_parse(e){let r=this._def.innerType._parse(e),s=n=>(B(n)&&(n.value=Object.freeze(n.value)),n);return me(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};de.create=(t,e)=>new de({innerType:t,typeName:y.ZodReadonly,...v(e)});function pt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function yt(t,e={},r){return t?Q.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=pt(e,s),d=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:d})}});if(!i){let o=pt(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):Q.create()}var kr={object:I.lazycreate},y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));var wr=(t,e={message:`Input not instance of ${t.name}`})=>yt(r=>r instanceof t,e),vt=F.create,_t=G.create,Cr=be.create,Tr=Y.create,xt=X.create,Rr=ee.create,Mr=ye.create,Er=te.create,Ir=re.create,Pr=Q.create,Ar=K.create,Or=L.create,jr=ve.create,Lr=V.create,Dr=I.create,Nr=I.strictCreate,$r=se.create,qr=ze.create,Ur=ne.create,Zr=q.create,zr=Ke.create,Kr=_e.create,Vr=xe.create,Br=Ve.create,Fr=ie.create,Qr=oe.create,Jr=ae.create,Wr=ce.create,Hr=J.create,Gr=O.create,Yr=P.create,Xr=U.create,es=O.createWithPreprocess,ts=Te.create,rs=()=>vt().optional(),ss=()=>_t().optional(),ns=()=>xt().optional(),is={string:(t=>F.create({...t,coerce:!0})),number:(t=>G.create({...t,coerce:!0})),boolean:(t=>X.create({...t,coerce:!0})),bigint:(t=>Y.create({...t,coerce:!0})),date:(t=>ee.create({...t,coerce:!0}))};var os=g;var as=l.object({enabled:l.boolean().optional(),clientId:l.string().min(1,"clientId must be a non-empty string").optional(),clientSecret:l.string().optional(),scopes:l.array(l.string()).optional(),redirectUri:l.string().optional(),authorizationUrl:l.string().optional(),tokenUrl:l.string().optional(),audiences:l.array(l.string()).optional(),tokenParamName:l.string().optional(),registrationUrl:l.string().optional()}).strict(),cs=l.object({command:l.string().optional(),args:l.array(l.string()).optional(),env:l.record(l.string(),l.string()).optional(),cwd:l.string().optional(),url:l.string().optional(),httpUrl:l.string().optional(),headers:l.record(l.string(),l.string()).optional(),tcp:l.string().optional(),timeout:l.number().optional(),trust:l.boolean().optional(),description:l.string().optional(),includeTools:l.array(l.string()).optional(),excludeTools:l.array(l.string()).optional(),extensionName:l.string().optional(),oauth:as.optional(),authProviderType:l.enum(["dynamic_discovery","google_credentials","service_account_impersonation"]).optional(),targetAudience:l.string().optional(),targetServiceAccount:l.string().optional()}),ls=l.object({type:l.literal("sdk"),name:l.string().min(1,"name must be a non-empty string"),instance:l.custom(t=>t&&typeof t=="object"&&"connect"in t&&typeof t.connect=="function",{message:"instance must be an MCP Server with connect method"})}),us=l.union([cs,ls]),ds=l.object({model:l.string().optional(),temp:l.number().optional(),top_p:l.number().optional()}),ps=l.object({max_time_minutes:l.number().optional(),max_turns:l.number().optional()}),vn=l.object({name:l.string().min(1,"Name must be a non-empty string"),description:l.string().min(1,"Description must be a non-empty string"),tools:l.array(l.string()).optional(),systemPrompt:l.string().min(1,"System prompt must be a non-empty string"),modelConfig:ds.partial().optional(),runConfig:ps.partial().optional(),color:l.string().optional(),isBuiltin:l.boolean().optional()}),fs=l.object({canUseTool:l.number().positive().optional(),mcpRequest:l.number().positive().optional(),controlRequest:l.number().positive().optional(),streamClose:l.number().positive().optional()}),bt=l.object({cwd:l.string().optional(),model:l.string().optional(),pathToQwenExecutable:l.string().optional(),env:l.record(l.string(),l.string()).optional(),permissionMode:l.enum(["default","plan","auto-edit","yolo"]).optional(),canUseTool:l.custom(t=>typeof t=="function",{message:"canUseTool must be a function"}).optional(),mcpServers:l.record(l.string(),us).optional(),abortController:l.instanceof(AbortController).optional(),debug:l.boolean().optional(),stderr:l.custom(t=>typeof t=="function",{message:"stderr must be a function"}).optional(),logLevel:l.enum(["debug","info","warn","error"]).optional(),maxSessionTurns:l.number().optional(),coreTools:l.array(l.string()).optional(),excludeTools:l.array(l.string()).optional(),allowedTools:l.array(l.string()).optional(),authType:l.enum(["openai","anthropic","qwen-oauth","gemini","vertex-ai"]).optional(),agents:l.array(l.custom(t=>t&&typeof t=="object"&&"name"in t&&"description"in t&&"systemPrompt"in t&&{message:"agents must be an array of SubagentConfig objects"})).optional(),includePartialMessages:l.boolean().optional(),resume:l.string().optional(),sessionId:l.string().optional(),timeout:fs.optional()}).strict();var kt=require("node:crypto");var hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ms(t){return hs.test(t)}function Ge(t,e="sessionId"){if(!ms(t))throw new Error(`Invalid ${e}: "${t}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`)}var St=T.createLogger("createQuery");function wt({prompt:t,options:e={}}){let r=gs(e),s=typeof t=="string",n=e.pathToQwenExecutable,i=e.abortController??new AbortController,o=e.resume??e.sessionId??(0,kt.randomUUID)(),a=new Ee({pathToQwenExecutable:n,spawnInfo:r,cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,env:e.env,abortController:i,debug:e.debug,stderr:e.stderr,logLevel:e.logLevel,maxSessionTurns:e.maxSessionTurns,coreTools:e.coreTools,excludeTools:e.excludeTools,allowedTools:e.allowedTools,authType:e.authType,includePartialMessages:e.includePartialMessages,resume:e.resume,sessionId:o}),d={...e,abortController:i,sessionId:o},u=new fe(a,d,s);if(s){let m=t,k={type:"user",session_id:u.getSessionId(),message:{role:"user",content:m},parent_tool_use_id:null};(async()=>{try{if(await u.initialized,a.exitError)return;a.write(pe(k))}catch(D){a.exitError||St.error("Error sending single-turn prompt:",D)}})()}else u.streamInput(t).catch(m=>{St.error("Error streaming input:",m)});return u}function gs(t){let e=bt.safeParse(t);if(!e.success){let r=e.error.errors.map(s=>`${s.path.join(".")}: ${s.message}`).join("; ");throw new Error(`Invalid QueryOptions: ${r}`)}t.sessionId&&Ge(t.sessionId,"sessionId"),t.resume&&Ge(t.resume,"resume");try{return Me(t.pathToQwenExecutable)}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`Invalid pathToQwenExecutable: ${s}`)}}function Ct(t,e,r,s){if(!t||typeof t!="string")throw new Error("Tool name must be a non-empty string");if(!e||typeof e!="string")throw new Error(`Tool '${t}' must have a description (string)`);if(!r||typeof r!="object")throw new Error(`Tool '${t}' must have an inputSchema (object)`);if(!s||typeof s!="function")throw new Error(`Tool '${t}' must have a handler (function)`);return{name:t,description:e,inputSchema:r,handler:s}}function Tt(t){if(!t)throw new Error("Tool name cannot be empty");if(t.length>64)throw new Error(`Tool name '${t}' is too long (max 64 characters): ${t.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(t))throw new Error(`Tool name '${t}' is invalid. Must start with a letter and contain only letters, numbers, and underscores.`)}var Rt=require("@modelcontextprotocol/sdk/server/mcp.js");function Mt(t){let{name:e,version:r="1.0.0",tools:s}=t;if(!e||typeof e!="string")throw new Error("MCP server name must be a non-empty string");if(!r||typeof r!="string")throw new Error("MCP server version must be a non-empty string");if(s!==void 0&&!Array.isArray(s))throw new Error("Tools must be an array");let n=new Set;if(s)for(let o of s){if(Tt(o.name),n.has(o.name))throw new Error(`Duplicate tool name '${o.name}' in MCP server '${e}'`);n.add(o.name)}let i=new Rt.McpServer({name:e,version:r},{capabilities:{tools:s?{}:void 0}});return s&&s.forEach(o=>{i.tool(o.name,o.description,o.inputSchema,o.handler)}),{type:"sdk",name:e,instance:i}}0&&(module.exports={AbortError,Query,SdkLogger,createSdkMcpServer,isAbortError,isControlCancel,isControlRequest,isControlResponse,isSDKAssistantMessage,isSDKPartialAssistantMessage,isSDKResultMessage,isSDKSystemMessage,isSDKUserMessage,isSdkMcpServerConfig,query,tool});
10
+ \u2022 query({ pathToQwenExecutable: "/path/to/cli.js" })`)}function Zt(t){if(!L.existsSync(t))throw new Error(`Executable file not found at '${t}'. Please check the file path and ensure the file exists.`);if(!L.statSync(t).isFile())throw new Error(`Path '${t}' exists but is not a file. Please provide a path to an executable file.`)}function zt(t){return t.includes("/")||t.includes("\\")}function Kt(t){let e=b.extname(t).toLowerCase();return[".js",".mjs",".cjs"].includes(e)}function Vt(t){let e=b.extname(t).toLowerCase();return[".ts",".tsx"].includes(e)}function Bt(t){try{let e=process.platform==="win32"?"where":"which";return(0,nt.execSync)(`${e} ${t}`,{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Qt(){return Bt("tsx")}function st(){return typeof process<"u"&&"versions"in process&&"bun"in process.versions?"bun":"node"}function Me(t){if(t!==void 0&&t.trim()==="")throw new Error("Executable path cannot be empty");if(t===void 0){let r=Ut();return{command:process.execPath,args:[r],type:st(),originalInput:""}}if(!zt(t)){if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error(`Invalid command name '${t}'. Command names should only contain letters, numbers, dots, hyphens, and underscores.`);return{command:t,args:[],type:"native",originalInput:t}}let e=b.resolve(t);return Zt(e),Kt(e)?{command:process.execPath,args:[e],type:st(),originalInput:t}:Vt(e)&&Qt()?{command:"tsx",args:[e],type:"tsx",originalInput:t}:{command:e,args:[],type:"native",originalInput:t}}var w=class t extends Error{constructor(e="Operation aborted"){super(e),this.name="AbortError",Object.setPrototypeOf(this,t.prototype)}};function ct(t){return t instanceof w||typeof t=="object"&&t!==null&&"name"in t&&t.name==="AbortError"}var M=T.createLogger("ProcessTransport"),Ee=class{childProcess=null;childStdin=null;childStdout=null;options;ready=!1;_exitError=null;closed=!1;inputClosed=!1;abortController;processExitHandler=null;abortHandler=null;constructor(e){this.options=e,this.abortController=this.options.abortController??new AbortController,T.configure({debug:e.debug,stderr:e.stderr,logLevel:e.logLevel}),this.initialize()}initialize(){try{if(this.abortController.signal.aborted)throw new w("Transport start aborted");let e=this.buildCliArguments(),r=this.options.cwd??process.cwd(),s={...process.env,...this.options.env},n=this.options.spawnInfo??Me(this.options.pathToQwenExecutable),i=this.options.debug||this.options.stderr?"pipe":"ignore";if(s.FORK_MODE==="1"){let u=typeof process<"u"&&process.versions&&!!process.versions.electron,d=n.args.length>0&&(n.args[0]?.endsWith(".js")||n.args[0]?.endsWith(".mjs")||n.args[0]?.endsWith(".cjs")),m,k,N;if(u&&d?(m=n.args[0]??"",k=[...n.args.slice(1),...e]):(n.type==="node"||n.type==="bun")&&n.args.length>0?(m=n.args[0]??"",k=[...n.args.slice(1),...e],N=n.command):(M.debug(`FORK_MODE enabled but CLI type '${n.type}' does not support fork. Falling back to spawn.`),m="",k=[]),m){M.debug(`Forking CLI (${n.type}): ${m} ${k.join(" ")}`);let P={cwd:r,env:s,stdio:i==="pipe"?["pipe","pipe","pipe","ipc"]:["pipe","pipe","ignore","ipc"],signal:this.abortController.signal};N&&(P.execPath=N),this.childProcess=(0,Se.fork)(m,k,P)}else M.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=(0,Se.spawn)(n.command,[...n.args,...e],{cwd:r,env:s,stdio:["pipe","pipe",i],signal:this.abortController.signal})}else M.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=(0,Se.spawn)(n.command,[...n.args,...e],{cwd:r,env:s,stdio:["pipe","pipe",i],signal:this.abortController.signal});this.childStdin=this.childProcess.stdin,this.childStdout=this.childProcess.stdout,(this.options.debug||this.options.stderr)&&this.childProcess.stderr?.on("data",u=>{M.debug(u.toString())});let a=()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGTERM")};this.processExitHandler=a,this.abortHandler=a,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.setupEventHandlers(),this.ready=!0,M.info("CLI process started successfully")}catch(e){throw this.ready=!1,M.error("Failed to initialize CLI process:",e),e}}setupEventHandlers(){this.childProcess&&(this.childProcess.on("error",e=>{this.ready=!1,this.abortController.signal.aborted?this._exitError=new w("CLI process aborted by user"):(this._exitError=new Error(`CLI process error: ${e.message}`),M.error(this._exitError.message))}),this.childProcess.on("close",(e,r)=>{if(this.ready=!1,this.abortController.signal.aborted)this._exitError=new w("CLI process aborted by user");else{let s=this.getProcessExitError(e,r);s&&(this._exitError=s,M.error(s.message))}}))}getProcessExitError(e,r){if(e!==0&&e!==null)return new Error(`CLI process exited with code ${e}`);if(r)return new Error(`CLI process terminated by signal ${r}`)}buildCliArguments(){let e=["--input-format","stream-json","--output-format","stream-json","--channel=SDK"];return this.options.model&&e.push("--model",this.options.model),this.options.systemPrompt&&e.push("--system-prompt",this.options.systemPrompt),this.options.appendSystemPrompt&&e.push("--append-system-prompt",this.options.appendSystemPrompt),this.options.permissionMode&&e.push("--approval-mode",this.options.permissionMode),this.options.maxSessionTurns!==void 0&&e.push("--max-session-turns",String(this.options.maxSessionTurns)),this.options.coreTools&&this.options.coreTools.length>0&&e.push("--core-tools",this.options.coreTools.join(",")),this.options.excludeTools&&this.options.excludeTools.length>0&&e.push("--exclude-tools",this.options.excludeTools.join(",")),this.options.allowedTools&&this.options.allowedTools.length>0&&e.push("--allowed-tools",this.options.allowedTools.join(",")),this.options.authType&&e.push("--auth-type",this.options.authType),this.options.includePartialMessages&&e.push("--include-partial-messages"),this.options.resume?e.push("--resume",this.options.resume):this.options.continue?e.push("--continue"):this.options.sessionId&&e.push("--session-id",this.options.sessionId),e}async close(){this.childStdin&&(this.childStdin.end(),this.childStdin=null),this.processExitHandler&&(process.off("exit",this.processExitHandler),this.processExitHandler=null),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.childProcess&&!this.childProcess.killed&&(this.childProcess.kill("SIGTERM"),setTimeout(()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGKILL")},5e3)),this.ready=!1,this.closed=!0,this.inputClosed=!0}async waitForExit(){if(!this.childProcess){if(this._exitError)throw this._exitError;return}if(this.childProcess.exitCode!==null||this.childProcess.killed){if(this._exitError)throw this._exitError;return}return new Promise((e,r)=>{let s=(i,o)=>{if(this.abortController.signal.aborted){r(new w("Operation aborted"));return}let a=this.getProcessExitError(i,o);a?r(a):e()};this.childProcess.once("close",s);let n=i=>{this.childProcess.off("close",s),r(i)};this.childProcess.once("error",n),this.childProcess.once("close",()=>{this.childProcess.off("error",n)})})}write(e){if(this.abortController.signal.aborted)throw new w("Cannot write: operation aborted");if(!this.ready||!this.childStdin)throw new Error("Transport not ready for writing");if(this.closed)throw new Error("Cannot write to closed transport");if(this.inputClosed)throw new Error("Input stream closed");if(this.childStdin.writableEnded||this.childStdin.destroyed)throw this.inputClosed=!0,M.warn(`Cannot write to ${this.childStdin.writableEnded?"ended":"destroyed"} stdin stream`),new Error("Input stream closed");if(this.childProcess?.killed||this.childProcess?.exitCode!==null)throw new Error("Cannot write to terminated process");if(this._exitError)throw new Error(`Cannot write to process that exited with error: ${this._exitError.message}`);M.debug(`Writing to stdin (${e.length} bytes): ${e.trim()}`);try{this.childStdin.write(e)?M.debug(`Write successful (${e.length} bytes)`):M.warn(`Write buffer full (${e.length} bytes), data queued. Waiting for drain event...`)}catch(r){let s=r instanceof Error?r.message:String(r);if(s.includes("EPIPE")||s.includes("ERR_STREAM_WRITE_AFTER_END")||s.includes("write after end"))throw this.inputClosed=!0,M.warn(`Stream closed, cannot write: ${s}`),new Error("Input stream closed");this.ready=!1;let i=`Failed to write to stdin: ${s}`;throw M.error(i),new Error(i)}}async*readMessages(){if(!this.childStdout)throw new Error("Cannot read messages: process not started");let e=lt.createInterface({input:this.childStdout,crlfDelay:1/0,terminal:!1});try{for await(let r of tt(e,"ProcessTransport"))yield r;await this.waitForExit()}finally{e.close()}}get isReady(){return this.ready}get exitError(){return this._exitError}endInput(){this.childStdin&&(this.childStdin.end(),this.inputClosed=!0)}getInputStream(){return this.childStdin||void 0}getOutputStream(){return this.childStdout||void 0}};var Fe=require("node:crypto");function Ie(t){return t&&typeof t=="object"&&t.type==="user"&&"message"in t}function Pe(t){return t&&typeof t=="object"&&t.type==="assistant"&&"uuid"in t&&"message"in t&&"session_id"in t&&"parent_tool_use_id"in t}function Ae(t){return t&&typeof t=="object"&&t.type==="system"&&"subtype"in t&&"uuid"in t&&"session_id"in t}function Oe(t){return t&&typeof t=="object"&&t.type==="result"&&"subtype"in t&&"duration_ms"in t&&"is_error"in t&&"uuid"in t&&"session_id"in t}function je(t){return t&&typeof t=="object"&&t.type==="stream_event"&&"uuid"in t&&"session_id"in t&&"event"in t&&"parent_tool_use_id"in t}function Le(t){return t&&typeof t=="object"&&t.type==="control_request"&&"request_id"in t&&"request"in t}function De(t){return t&&typeof t=="object"&&t.type==="control_response"&&"response"in t}function Ne(t){return t&&typeof t=="object"&&t.type==="control_cancel_request"&&"request_id"in t}function ke(t){return"type"in t&&t.type==="sdk"}var $e=class{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}[Symbol.asyncIterator](){if(this.started)throw new Error("Stream can only be iterated once");return this.started=!0,this}async next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.hasError?Promise.reject(this.hasError):this.isDone?Promise.resolve({done:!0,value:void 0}):new Promise((e,r)=>{this.readResolve=e,this.readReject=r})}enqueue(e){if(this.readResolve){let r=this.readResolve;this.readResolve=void 0,this.readReject=void 0,r({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let r=this.readReject;this.readResolve=void 0,this.readReject=void 0,r(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};var qe=class{sendToQuery;serverName;started=!1;logger;onmessage;onerror;onclose;constructor(e){this.sendToQuery=e.sendToQuery,this.serverName=e.serverName,this.logger=T.createLogger(`SdkControlServerTransport:${e.serverName}`)}async start(){this.started=!0,this.logger.debug("Transport started")}async send(e){if(!this.started)throw new Error(`SdkControlServerTransport (${this.serverName}) not started. Call start() first.`);try{this.logger.debug("Sending message to Query",e),await this.sendToQuery(e)}catch(r){throw this.logger.error("Error sending message:",r),this.onerror&&this.onerror(r instanceof Error?r:new Error(String(r))),r}}async close(){this.started&&(this.started=!1,this.logger.debug("Transport closed"),this.onclose&&this.onclose())}handleMessage(e){if(!this.started){this.logger.warn("Received message for closed transport");return}this.logger.debug("Handling message from CLI",e),this.onmessage?this.onmessage(e):this.logger.warn("No onmessage handler set")}handleError(e){this.logger.error("Transport error:",e),this.onerror&&this.onerror(e)}isStarted(){return this.started}getServerName(){return this.serverName}};var Ft=6e4,Jt=6e4,Wt=6e4,Ht=6e4,S=T.createLogger("Query"),fe=class{transport;options;sessionId;inputStream;sdkMessages;abortController;pendingControlRequests=new Map;pendingMcpResponses=new Map;sdkMcpTransports=new Map;sdkMcpServers=new Map;initialized;closed=!1;messageRouterStarted=!1;firstResultReceivedPromise;firstResultReceivedResolve;isSingleTurn;abortHandler=null;constructor(e,r,s=!1){this.transport=e,this.options=r,this.sessionId=r.resume??r.sessionId??(0,Fe.randomUUID)(),this.inputStream=new $e,this.abortController=r.abortController??new AbortController,this.isSingleTurn=s,this.sdkMessages=this.readSdkMessages(),this.firstResultReceivedPromise=new Promise(n=>{this.firstResultReceivedResolve=n}),this.abortController.signal.aborted?(this.inputStream.error(new w("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})):(this.abortHandler=()=>{this.inputStream.error(new w("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})},this.abortController.signal.addEventListener("abort",this.abortHandler)),this.initialized=this.initialize(),this.initialized.catch(n=>{let i=n instanceof Error?n.message:String(n);i.includes("Query is closed")&&this.transport.exitError?this.inputStream.error(this.transport.exitError):this.inputStream.error(n instanceof Error?n:new Error(i))}),this.startMessageRouter()}async initializeSdkMcpServers(){if(!this.options.mcpServers)return;let e=[];for(let[r,s]of Object.entries(this.options.mcpServers)){if(!ke(s))continue;let n=s.name||r,i=s.instance,o={sendToQuery:async d=>{this.handleMcpServerResponse(n,d)},serverName:n},a=new qe(o),u=i.connect(a).then(()=>{this.sdkMcpServers.set(n,i),this.sdkMcpTransports.set(n,a),S.debug(`SDK MCP server '${n}' connected to transport`)}).catch(d=>{S.error(`Failed to connect SDK MCP server '${n}' to transport:`,d)});e.push(u)}await Promise.all(e),this.sdkMcpServers.size>0&&S.info(`Initialized ${this.sdkMcpServers.size} SDK MCP server(s): ${Array.from(this.sdkMcpServers.keys()).join(", ")}`)}handleMcpServerResponse(e,r){if("id"in r&&r.id!==null&&r.id!==void 0){let s=`${e}:${r.id}`,n=this.pendingMcpResponses.get(s);if(n){S.debug(`Routing MCP response for server '${e}', id: ${r.id}`),n.resolve(r),this.pendingMcpResponses.delete(s);return}}S.warn(`Received MCP server response with no pending request: server='${e}'`,r)}getSdkMcpServersForCli(){let e={};for(let[r]of this.sdkMcpServers.entries())e[r]={type:"sdk",name:r};return e}getMcpServersForCli(){if(!this.options.mcpServers)return{};let e={};for(let[r,s]of Object.entries(this.options.mcpServers))ke(s)||(e[r]=s);return e}async initialize(){try{S.debug("Initializing Query"),await this.initializeSdkMcpServers();let e=this.getSdkMcpServersForCli(),r=this.getMcpServersForCli();await this.sendControlRequest("initialize",{hooks:null,sdkMcpServers:Object.keys(e).length>0?e:void 0,mcpServers:Object.keys(r).length>0?r:void 0,agents:this.options.agents}),S.info("Query initialized successfully")}catch(e){throw S.error("Initialization error:",e),e}}startMessageRouter(){this.messageRouterStarted||(this.messageRouterStarted=!0,(async()=>{try{for await(let e of this.transport.readMessages())if(await this.routeMessage(e),this.closed)break;this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done()}catch(e){this.inputStream.error(e instanceof Error?e:new Error(String(e)))}})())}async routeMessage(e){if(Le(e)){await this.handleControlRequest(e);return}if(De(e)){this.handleControlResponse(e);return}if(Ne(e)){this.handleControlCancelRequest(e);return}if(Ae(e)){this.inputStream.enqueue(e);return}if(Oe(e)){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleTurn&&"endInput"in this.transport&&this.transport.endInput(),this.inputStream.enqueue(e);return}if(Pe(e)||Ie(e)||je(e)){this.inputStream.enqueue(e);return}S.warn("Unknown message type:",e),this.inputStream.enqueue(e)}async handleControlRequest(e){let{request_id:r,request:s}=e;S.debug(`Handling control request: ${s.subtype}`);let n=new AbortController;try{let i=null;switch(s.subtype){case"can_use_tool":i=await this.handlePermissionRequest(s.tool_name,s.input,s.permission_suggestions,n.signal);break;case"mcp_message":i=await this.handleMcpMessage(s.server_name,s.message);break;default:throw new Error(`Unknown control request subtype: ${s.subtype}`)}await this.sendControlResponse(r,!0,i)}catch(i){let o=i instanceof Error?i.message:String(i);S.error(`Control request error (${s.subtype}):`,o),await this.sendControlResponse(r,!1,o)}}async handlePermissionRequest(e,r,s,n){if(!this.options.canUseTool)return{behavior:"deny",message:"Denied"};try{let i=this.options.timeout?.canUseTool??Ft,o,a=new Promise((d,m)=>{o=setTimeout(()=>m(new Error("Permission callback timeout")),i)}),u=await Promise.race([Promise.resolve(this.options.canUseTool(e,r,{signal:n,suggestions:s})),a]);return o&&clearTimeout(o),u.behavior==="allow"?{behavior:"allow",updatedInput:u.updatedInput??r}:{behavior:"deny",message:u.message??"Denied",...u.interrupt!==void 0?{interrupt:u.interrupt}:{}}}catch(i){let o=i instanceof Error?i.message:String(i);return S.warn("Permission callback error (denying by default):",o),{behavior:"deny",message:`Permission check failed: ${o}`}}}async handleMcpMessage(e,r){let s=this.sdkMcpTransports.get(e);if(!s)throw new Error(`MCP server '${e}' not found in SDK-embedded servers`);return"method"in r&&"id"in r&&r.id!==null?{mcp_response:await this.handleMcpRequest(e,r,s)}:(s.handleMessage(r),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}handleMcpRequest(e,r,s){let n="id"in r?r.id:null,i=`${e}:${n}`;return new Promise((o,a)=>{let u=this.options.timeout?.mcpRequest??Jt,d=setTimeout(()=>{this.pendingMcpResponses.delete(i),a(new Error("MCP request timeout"))},u),m=()=>{clearTimeout(d),this.pendingMcpResponses.delete(i)},k=P=>{m(),o(P)},N=P=>{m(),a(P)};this.pendingMcpResponses.set(i,{resolve:k,reject:N}),s.handleMessage(r)})}handleControlResponse(e){let{response:r}=e,s=r.request_id,n=this.pendingControlRequests.get(s);if(!n){S.warn("Received response for unknown request:",s,JSON.stringify(r));return}if(clearTimeout(n.timeout),this.pendingControlRequests.delete(s),r.subtype==="success")S.debug(`Control response success for request: ${s}: ${JSON.stringify(r.response)}`),n.resolve(r.response);else{let i=typeof r.error=="string"?r.error:r.error?.message??"Unknown error";S.error(`Control response error for request ${s}:`,i),n.reject(new Error(i))}}handleControlCancelRequest(e){let{request_id:r}=e;if(!r){S.warn("Received cancel request without request_id");return}let s=this.pendingControlRequests.get(r);s&&(S.debug(`Cancelling control request: ${r}`),s.abortController.abort(),clearTimeout(s.timeout),this.pendingControlRequests.delete(r),s.reject(new w("Request cancelled")))}async sendControlRequest(e,r={}){if(this.closed)return Promise.reject(new Error("Query is closed"));if(this.transport.exitError)return Promise.reject(this.transport.exitError);e!=="initialize"&&await this.initialized;let s=(0,Fe.randomUUID)(),n={type:"control_request",request_id:s,request:{subtype:e,...r}},i=new Promise((o,a)=>{let u=new AbortController,d=this.options.timeout?.controlRequest??Wt,m=setTimeout(()=>{this.pendingControlRequests.delete(s),a(new Error(`Control request timeout: ${e}`))},d);this.pendingControlRequests.set(s,{resolve:o,reject:a,timeout:m,abortController:u})});try{this.transport.write(pe(n))}catch(o){let a=this.pendingControlRequests.get(s);a&&(clearTimeout(a.timeout),this.pendingControlRequests.delete(s));let u=o instanceof Error?o.message:String(o);return S.error(`Failed to send control request: ${u}`),Promise.reject(new Error(`Failed to send control request: ${u}`))}return i}async sendControlResponse(e,r,s){let n={type:"control_response",response:r?{subtype:"success",request_id:e,response:s}:{subtype:"error",request_id:e,error:s}};try{this.transport.write(pe(n))}catch(i){let o=i instanceof Error?i.message:String(i);S.warn(`Failed to send control response for request ${e}: ${o}`)}}async close(){if(this.closed)return;this.closed=!0,this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null);let r=this.transport.exitError??new Error("Query is closed");for(let s of this.pendingControlRequests.values())s.abortController.abort(),clearTimeout(s.timeout),s.reject(r);this.pendingControlRequests.clear();for(let s of this.pendingMcpResponses.values())s.reject(r);this.pendingMcpResponses.clear(),await this.transport.close(),this.inputStream.hasError===void 0&&(this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done());for(let s of this.sdkMcpTransports.values())try{await s.close()}catch(n){S.error("Error closing MCP transport:",n)}this.sdkMcpTransports.clear(),S.info("Query is closed")}async*readSdkMessages(){for await(let e of this.inputStream)yield e}async next(...e){return this.sdkMessages.next(...e)}async return(e){return this.sdkMessages.return(e)}async throw(e){return this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async streamInput(e){if(this.closed)throw new Error("Query is closed");try{await this.initialized;for await(let r of e){if(this.abortController.signal.aborted)break;this.transport.write(pe(r))}if(this.firstResultReceivedPromise){let r=this.options.timeout?.streamClose??Ht,s,n=new Promise(i=>{s=setTimeout(()=>{S.info("streamCloseTimeout resolved"),i()},r)});await Promise.race([this.firstResultReceivedPromise,n]),s&&clearTimeout(s)}this.endInput()}catch(r){if(this.abortController.signal.aborted){S.info("Aborted during input streaming"),this.inputStream.error(new w("Query aborted during input streaming"));return}throw r}}endInput(){if(this.closed)throw new Error("Query is closed");"endInput"in this.transport&&typeof this.transport.endInput=="function"&&this.transport.endInput()}async interrupt(){await this.sendControlRequest("interrupt")}async setPermissionMode(e){await this.sendControlRequest("set_permission_mode",{mode:e})}async setModel(e){await this.sendControlRequest("set_model",{model:e})}async supportedCommands(){return this.sendControlRequest("supported_commands")}async mcpServerStatus(){return this.sendControlRequest("mcp_server_status")}getSessionId(){return this.sessionId}isClosed(){return this.closed}};var c={};Ye(c,{BRAND:()=>Sr,DIRTY:()=>H,EMPTY_PATH:()=>er,INVALID:()=>g,NEVER:()=>os,OK:()=>R,ParseStatus:()=>C,Schema:()=>_,ZodAny:()=>F,ZodArray:()=>V,ZodBigInt:()=>Y,ZodBoolean:()=>X,ZodBranded:()=>Ce,ZodCatch:()=>ue,ZodDate:()=>ee,ZodDefault:()=>le,ZodDiscriminatedUnion:()=>ze,ZodEffects:()=>j,ZodEnum:()=>ae,ZodError:()=>E,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Ve,ZodIntersection:()=>ne,ZodIssueCode:()=>l,ZodLazy:()=>ie,ZodLiteral:()=>oe,ZodMap:()=>_e,ZodNaN:()=>be,ZodNativeEnum:()=>ce,ZodNever:()=>D,ZodNull:()=>re,ZodNullable:()=>U,ZodNumber:()=>G,ZodObject:()=>I,ZodOptional:()=>A,ZodParsedType:()=>f,ZodPipeline:()=>Te,ZodPromise:()=>J,ZodReadonly:()=>de,ZodRecord:()=>Ke,ZodSchema:()=>_,ZodSet:()=>xe,ZodString:()=>Q,ZodSymbol:()=>ye,ZodTransformer:()=>j,ZodTuple:()=>q,ZodType:()=>_,ZodUndefined:()=>te,ZodUnion:()=>se,ZodUnknown:()=>K,ZodVoid:()=>ve,addIssueToContext:()=>p,any:()=>Pr,array:()=>Lr,bigint:()=>Tr,boolean:()=>xt,coerce:()=>is,custom:()=>yt,date:()=>Rr,datetimeRegex:()=>mt,defaultErrorMap:()=>Z,discriminatedUnion:()=>qr,effect:()=>Gr,enum:()=>Jr,function:()=>Br,getErrorMap:()=>he,getParsedType:()=>$,instanceof:()=>wr,intersection:()=>Ur,isAborted:()=>Ue,isAsync:()=>me,isDirty:()=>Ze,isValid:()=>B,late:()=>kr,lazy:()=>Qr,literal:()=>Fr,makeIssue:()=>we,map:()=>Kr,nan:()=>Cr,nativeEnum:()=>Wr,never:()=>Or,null:()=>Ir,nullable:()=>Xr,number:()=>_t,object:()=>Dr,objectUtil:()=>Je,oboolean:()=>ns,onumber:()=>ss,optional:()=>Yr,ostring:()=>rs,pipeline:()=>ts,preprocess:()=>es,promise:()=>Hr,quotelessJson:()=>Gt,record:()=>zr,set:()=>Vr,setErrorMap:()=>Xt,strictObject:()=>Nr,string:()=>vt,symbol:()=>Mr,transformer:()=>Gr,tuple:()=>Zr,undefined:()=>Er,union:()=>$r,unknown:()=>Ar,util:()=>x,void:()=>jr});var x;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(let o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var Je;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Je||(Je={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$=t=>{switch(typeof t){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(t)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(t)?f.array:t===null?f.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?f.promise:typeof Map<"u"&&t instanceof Map?f.map:typeof Set<"u"&&t instanceof Set?f.set:typeof Date<"u"&&t instanceof Date?f.date:f.object;default:return f.unknown}};var l=x.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"]),Gt=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),E=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(r(o));else{let a=s,u=0;for(;u<o.path.length;){let d=o.path[u];u===o.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(o))):a[d]=a[d]||{_errors:[]},a=a[d],u++}}};return n(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};E.create=t=>new E(t);var Yt=(t,e)=>{let r;switch(t.code){case l.invalid_type:t.received===f.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:r=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case l.invalid_union:r="Invalid input";break;case l.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case l.invalid_enum_value:r=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:r="Invalid function arguments";break;case l.invalid_return_type:r="Invalid function return type";break;case l.invalid_date:r="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:x.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case l.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case l.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case l.custom:r="Invalid input";break;case l.invalid_intersection_types:r="Intersection results could not be merged";break;case l.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:r="Number must be finite";break;default:r=e.defaultError,x.assertNever(t)}return{message:r}},Z=Yt;var ut=Z;function Xt(t){ut=t}function he(){return ut}var we=t=>{let{data:e,path:r,errorMaps:s,issueData:n}=t,i=[...r,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",u=s.filter(d=>!!d).slice().reverse();for(let d of u)a=d(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},er=[];function p(t,e){let r=he(),s=we({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Z?void 0:Z].filter(n=>!!n)});t.common.issues.push(s)}var C=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let n of r){if(n.status==="aborted")return g;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let n of r){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let n of r){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return g;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},g=Object.freeze({status:"aborted"}),H=t=>({status:"dirty",value:t}),R=t=>({status:"valid",value:t}),Ue=t=>t.status==="aborted",Ze=t=>t.status==="dirty",B=t=>t.status==="valid",me=t=>typeof Promise<"u"&&t instanceof Promise;var h;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var O=class{constructor(e,r,s,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=n}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}},dt=(t,e)=>{if(B(e))return{success:!0,data:e.value};if(!t.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 E(t.common.issues);return this._error=r,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:n}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,a)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:n}}var _=class{get description(){return this._def.description}_getType(e){return $(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(me(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)},n=this._parseSync({data:e,path:s.path,parent:s});return dt(s,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return B(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>B(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:$(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(me(n)?n:Promise.resolve(n));return dt(s,i)}refine(e,r){let s=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let o=e(n),a=()=>i.addIssue({code:l.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof r=="function"?r(s,n):r),!1))}_refinement(e){return new j({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 A.create(this,this._def)}nullable(){return U.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this)}promise(){return J.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return ne.create(this,e,this._def)}transform(e){return new j({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new le({...v(this._def),innerType:this,defaultValue:r,typeName:y.ZodDefault})}brand(){return new Ce({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ue({...v(this._def),innerType:this,catchValue:r,typeName:y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Te.create(this,e)}readonly(){return de.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tr=/^c[^\s-]{8,}$/i,rr=/^[0-9a-z]+$/,sr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nr=/^[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,ir=/^[a-z0-9_-]{21}$/i,or=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ar=/^[-+]?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)?)??$/,cr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",We,ur=/^(?:(?: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])$/,dr=/^(?:(?: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])$/,pr=/^(([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]))$/,fr=/^(([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])$/,hr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ft="((\\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])))",gr=new RegExp(`^${ft}$`);function ht(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function yr(t){return new RegExp(`^${ht(t)}$`)}function mt(t){let e=`${ft}T${ht(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vr(t,e){return!!((e==="v4"||!e)&&ur.test(t)||(e==="v6"||!e)&&pr.test(t))}function _r(t,e){if(!or.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function xr(t,e){return!!((e==="v4"||!e)&&dr.test(t)||(e==="v6"||!e)&&fr.test(t))}var Q=class t extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:f.string,received:i.parsedType}),g}let s=new C,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(n=this._getOrReturnCtx(e,n),o?p(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&p(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")cr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")We||(We=new RegExp(lr,"u")),We.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")nr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ir.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")tr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")rr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")sr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:l.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:l.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:l.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?mt(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?gr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?yr(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ar.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:l.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?vr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:l.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?_r(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:l.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?xr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:l.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?hr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:l.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?mr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:l.invalid_string,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(n=>e.test(n),{validation:r,code:l.invalid_string,...h.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Q.create=t=>new Q({checks:[],typeName:y.ZodString,coerce:t?.coerce??!1,...v(t)});function br(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=r>s?r:s,i=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var G=class t extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:f.number,received:i.parsedType}),g}let s,n=new C;for(let i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:l.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?br(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:l.not_finite,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};G.create=t=>new G({checks:[],typeName:y.ZodNumber,coerce:t?.coerce||!1,...v(t)});var Y=class t extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s,n=new C;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),p(s,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:f.bigint,received:r.parsedType}),g}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,s,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Y.create=t=>new Y({checks:[],typeName:y.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var X=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.boolean,received:s.parsedType}),g}return R(e.data)}};X.create=t=>new X({typeName:y.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var ee=class t extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:f.date,received:i.parsedType}),g}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_date}),g}let s=new C,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):x.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ee.create=t=>new ee({checks:[],coerce:t?.coerce||!1,typeName:y.ZodDate,...v(t)});var ye=class extends _{_parse(e){if(this._getType(e)!==f.symbol){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.symbol,received:s.parsedType}),g}return R(e.data)}};ye.create=t=>new ye({typeName:y.ZodSymbol,...v(t)});var te=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.undefined,received:s.parsedType}),g}return R(e.data)}};te.create=t=>new te({typeName:y.ZodUndefined,...v(t)});var re=class extends _{_parse(e){if(this._getType(e)!==f.null){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.null,received:s.parsedType}),g}return R(e.data)}};re.create=t=>new re({typeName:y.ZodNull,...v(t)});var F=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return R(e.data)}};F.create=t=>new F({typeName:y.ZodAny,...v(t)});var K=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return R(e.data)}};K.create=t=>new K({typeName:y.ZodUnknown,...v(t)});var D=class extends _{_parse(e){let r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:f.never,received:r.parsedType}),g}};D.create=t=>new D({typeName:y.ZodNever,...v(t)});var ve=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.void,received:s.parsedType}),g}return R(e.data)}};ve.create=t=>new ve({typeName:y.ZodVoid,...v(t)});var V=class t extends _{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),n=this._def;if(r.parsedType!==f.array)return p(r,{code:l.invalid_type,expected:f.array,received:r.parsedType}),g;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(o||a)&&(p(r,{code:o?l.too_big:l.too_small,minimum:a?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(p(r,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(p(r,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>n.type._parseAsync(new O(r,o,r.path,a)))).then(o=>C.mergeArray(s,o));let i=[...r.data].map((o,a)=>n.type._parseSync(new O(r,o,r.path,a)));return C.mergeArray(s,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};V.create=(t,e)=>new V({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function ge(t){if(t instanceof I){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=A.create(ge(s))}return new I({...t._def,shape:()=>e})}else return t instanceof V?new V({...t._def,type:ge(t.element)}):t instanceof A?A.create(ge(t.unwrap())):t instanceof U?U.create(ge(t.unwrap())):t instanceof q?q.create(t.items.map(e=>ge(e))):t}var I=class t extends _{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=x.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==f.object){let d=this._getOrReturnCtx(e);return p(d,{code:l.invalid_type,expected:f.object,received:d.parsedType}),g}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof D&&this._def.unknownKeys==="strip"))for(let d in n.data)o.includes(d)||a.push(d);let u=[];for(let d of o){let m=i[d],k=n.data[d];u.push({key:{status:"valid",value:d},value:m._parse(new O(n,k,n.path,d)),alwaysSet:d in n.data})}if(this._def.catchall instanceof D){let d=this._def.unknownKeys;if(d==="passthrough")for(let m of a)u.push({key:{status:"valid",value:m},value:{status:"valid",value:n.data[m]}});else if(d==="strict")a.length>0&&(p(n,{code:l.unrecognized_keys,keys:a}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let m of a){let k=n.data[m];u.push({key:{status:"valid",value:m},value:d._parse(new O(n,k,n.path,m)),alwaysSet:m in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let d=[];for(let m of u){let k=await m.key,N=await m.value;d.push({key:k,value:N,alwaysSet:m.alwaysSet})}return d}).then(d=>C.mergeObjectSync(s,d)):C.mergeObjectSync(s,u)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let n=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of x.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of x.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return ge(this)}partial(e){let r={};for(let s of x.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?r[s]=n:r[s]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of x.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof A;)i=i._def.innerType;r[s]=i}return new t({...this._def,shape:()=>r})}keyof(){return gt(x.objectKeys(this.shape))}};I.create=(t,e)=>new I({shape:()=>t,unknownKeys:"strip",catchall:D.create(),typeName:y.ZodObject,...v(e)});I.strictCreate=(t,e)=>new I({shape:()=>t,unknownKeys:"strict",catchall:D.create(),typeName:y.ZodObject,...v(e)});I.lazycreate=(t,e)=>new I({shape:t,unknownKeys:"strip",catchall:D.create(),typeName:y.ZodObject,...v(e)});var se=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new E(a.ctx.common.issues));return p(r,{code:l.invalid_union,unionErrors:o}),g}if(r.common.async)return Promise.all(s.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let u of s){let d={...r,common:{...r.common,issues:[]},parent:null},m=u._parseSync({data:r.data,path:r.path,parent:d});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new E(u));return p(r,{code:l.invalid_union,unionErrors:a}),g}}get options(){return this._def.options}};se.create=(t,e)=>new se({options:t,typeName:y.ZodUnion,...v(e)});var z=t=>t instanceof ie?z(t.schema):t instanceof j?z(t.innerType()):t instanceof oe?[t.value]:t instanceof ae?t.options:t instanceof ce?x.objectValues(t.enum):t instanceof le?z(t._def.innerType):t instanceof te?[void 0]:t instanceof re?[null]:t instanceof A?[void 0,...z(t.unwrap())]:t instanceof U?[null,...z(t.unwrap())]:t instanceof Ce||t instanceof de?z(t.unwrap()):t instanceof ue?z(t._def.innerType):[],ze=class t extends _{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:l.invalid_type,expected:f.object,received:r.parsedType}),g;let s=this.discriminator,n=r.data[s],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(p(r,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let n=new Map;for(let i of r){let o=z(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...v(s)})}};function He(t,e){let r=$(t),s=$(e);if(t===e)return{valid:!0,data:t};if(r===f.object&&s===f.object){let n=x.objectKeys(e),i=x.objectKeys(t).filter(a=>n.indexOf(a)!==-1),o={...t,...e};for(let a of i){let u=He(t[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(r===f.array&&s===f.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],u=He(o,a);if(!u.valid)return{valid:!1};n.push(u.data)}return{valid:!0,data:n}}else return r===f.date&&s===f.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ne=class extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ue(i)||Ue(o))return g;let a=He(i.value,o.value);return a.valid?((Ze(i)||Ze(o))&&r.dirty(),{status:r.value,value:a.data}):(p(s,{code:l.invalid_intersection_types}),g)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ne.create=(t,e,r)=>new ne({left:t,right:e,typeName:y.ZodIntersection,...v(r)});var q=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:l.invalid_type,expected:f.array,received:s.parsedType}),g;if(s.data.length<this._def.items.length)return p(s,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...s.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new O(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>C.mergeArray(r,o)):C.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};q.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new q({items:t,typeName:y.ZodTuple,rest:null,...v(e)})};var Ke=class t extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:l.invalid_type,expected:f.object,received:s.parsedType}),g;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new O(s,a,s.path,a)),value:o._parse(new O(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?C.mergeObjectAsync(r,n):C.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof _?new t({keyType:e,valueType:r,typeName:y.ZodRecord,...v(s)}):new t({keyType:Q.create(),valueType:e,typeName:y.ZodRecord,...v(r)})}},_e=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:l.invalid_type,expected:f.map,received:s.parsedType}),g;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,u],d)=>({key:n._parse(new O(s,a,s.path,[d,"key"])),value:i._parse(new O(s,u,s.path,[d,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let d=await u.key,m=await u.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),a.set(d.value,m.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of o){let d=u.key,m=u.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),a.set(d.value,m.value)}return{status:r.value,value:a}}}};_e.create=(t,e,r)=>new _e({valueType:e,keyType:t,typeName:y.ZodMap,...v(r)});var xe=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:l.invalid_type,expected:f.set,received:s.parsedType}),g;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(p(s,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(p(s,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function o(u){let d=new Set;for(let m of u){if(m.status==="aborted")return g;m.status==="dirty"&&r.dirty(),d.add(m.value)}return{status:r.value,value:d}}let a=[...s.data.values()].map((u,d)=>i._parse(new O(s,u,s.path,d)));return s.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};xe.create=(t,e)=>new xe({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var Ve=class t extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.function)return p(r,{code:l.invalid_type,expected:f.function,received:r.parsedType}),g;function s(a,u){return we({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,he(),Z].filter(d=>!!d),issueData:{code:l.invalid_arguments,argumentsError:u}})}function n(a,u){return we({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,he(),Z].filter(d=>!!d),issueData:{code:l.invalid_return_type,returnTypeError:u}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof J){let a=this;return R(async function(...u){let d=new E([]),m=await a._def.args.parseAsync(u,i).catch(P=>{throw d.addIssue(s(u,P)),d}),k=await Reflect.apply(o,this,m);return await a._def.returns._def.type.parseAsync(k,i).catch(P=>{throw d.addIssue(n(k,P)),d})})}else{let a=this;return R(function(...u){let d=a._def.args.safeParse(u,i);if(!d.success)throw new E([s(u,d.error)]);let m=Reflect.apply(o,this,d.data),k=a._def.returns.safeParse(m,i);if(!k.success)throw new E([n(m,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:q.create(e).rest(K.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||q.create([]).rest(K.create()),returns:r||K.create(),typeName:y.ZodFunction,...v(s)})}},ie=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ie.create=(t,e)=>new ie({getter:t,typeName:y.ZodLazy,...v(e)});var oe=class extends _{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return p(r,{received:r.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};oe.create=(t,e)=>new oe({value:t,typeName:y.ZodLiteral,...v(e)});function gt(t,e){return new ae({values:t,typeName:y.ZodEnum,...v(e)})}var ae=class t extends _{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{expected:x.joinValues(s),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return p(r,{received:r.data,code:l.invalid_enum_value,options:s}),g}return R(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};ae.create=gt;var ce=class extends _{_parse(e){let r=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=x.objectValues(r);return p(s,{expected:x.joinValues(n),received:s.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=x.objectValues(r);return p(s,{received:s.data,code:l.invalid_enum_value,options:n}),g}return R(e.data)}get enum(){return this._def.values}};ce.create=(t,e)=>new ce({values:t,typeName:y.ZodNativeEnum,...v(e)});var J=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==f.promise&&r.common.async===!1)return p(r,{code:l.invalid_type,expected:f.promise,received:r.parsedType}),g;let s=r.parsedType===f.promise?r.data:Promise.resolve(r.data);return R(s.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};J.create=(t,e)=>new J({type:t,typeName:y.ZodPromise,...v(e)});var j=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return g;let u=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return u.status==="aborted"?g:u.status==="dirty"?H(u.value):r.value==="dirty"?H(u.value):u});{if(r.value==="aborted")return g;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?g:a.status==="dirty"?H(a.value):r.value==="dirty"?H(a.value):a}}if(n.type==="refinement"){let o=a=>{let u=n.refinement(a,i);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?g:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?g:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!B(o))return g;let a=n.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>B(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:r.value,value:a})):g);x.assertNever(n)}};j.create=(t,e,r)=>new j({schema:t,typeName:y.ZodEffects,effect:e,...v(r)});j.createWithPreprocess=(t,e,r)=>new j({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,...v(r)});var A=class extends _{_parse(e){return this._getType(e)===f.undefined?R(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A.create=(t,e)=>new A({innerType:t,typeName:y.ZodOptional,...v(e)});var U=class extends _{_parse(e){return this._getType(e)===f.null?R(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};U.create=(t,e)=>new U({innerType:t,typeName:y.ZodNullable,...v(e)});var le=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};le.create=(t,e)=>new le({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ue=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return me(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ue.create=(t,e)=>new ue({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var be=class extends _{_parse(e){if(this._getType(e)!==f.nan){let s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:f.nan,received:s.parsedType}),g}return{status:"valid",value:e.data}}};be.create=t=>new be({typeName:y.ZodNaN,...v(t)});var Sr=Symbol("zod_brand"),Ce=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Te=class t extends _{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?g:i.status==="dirty"?(r.dirty(),H(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?g:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:y.ZodPipeline})}},de=class extends _{_parse(e){let r=this._def.innerType._parse(e),s=n=>(B(n)&&(n.value=Object.freeze(n.value)),n);return me(r)?r.then(n=>s(n)):s(r)}unwrap(){return this._def.innerType}};de.create=(t,e)=>new de({innerType:t,typeName:y.ZodReadonly,...v(e)});function pt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function yt(t,e={},r){return t?F.create().superRefine((s,n)=>{let i=t(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=pt(e,s),u=a.fatal??r??!0;n.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=pt(e,s),a=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:a})}}):F.create()}var kr={object:I.lazycreate},y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));var wr=(t,e={message:`Input not instance of ${t.name}`})=>yt(r=>r instanceof t,e),vt=Q.create,_t=G.create,Cr=be.create,Tr=Y.create,xt=X.create,Rr=ee.create,Mr=ye.create,Er=te.create,Ir=re.create,Pr=F.create,Ar=K.create,Or=D.create,jr=ve.create,Lr=V.create,Dr=I.create,Nr=I.strictCreate,$r=se.create,qr=ze.create,Ur=ne.create,Zr=q.create,zr=Ke.create,Kr=_e.create,Vr=xe.create,Br=Ve.create,Qr=ie.create,Fr=oe.create,Jr=ae.create,Wr=ce.create,Hr=J.create,Gr=j.create,Yr=A.create,Xr=U.create,es=j.createWithPreprocess,ts=Te.create,rs=()=>vt().optional(),ss=()=>_t().optional(),ns=()=>xt().optional(),is={string:(t=>Q.create({...t,coerce:!0})),number:(t=>G.create({...t,coerce:!0})),boolean:(t=>X.create({...t,coerce:!0})),bigint:(t=>Y.create({...t,coerce:!0})),date:(t=>ee.create({...t,coerce:!0}))};var os=g;var as=c.object({enabled:c.boolean().optional(),clientId:c.string().min(1,"clientId must be a non-empty string").optional(),clientSecret:c.string().optional(),scopes:c.array(c.string()).optional(),redirectUri:c.string().optional(),authorizationUrl:c.string().optional(),tokenUrl:c.string().optional(),audiences:c.array(c.string()).optional(),tokenParamName:c.string().optional(),registrationUrl:c.string().optional()}).strict(),cs=c.object({command:c.string().optional(),args:c.array(c.string()).optional(),env:c.record(c.string(),c.string()).optional(),cwd:c.string().optional(),url:c.string().optional(),httpUrl:c.string().optional(),headers:c.record(c.string(),c.string()).optional(),tcp:c.string().optional(),timeout:c.number().optional(),trust:c.boolean().optional(),description:c.string().optional(),includeTools:c.array(c.string()).optional(),excludeTools:c.array(c.string()).optional(),extensionName:c.string().optional(),oauth:as.optional(),authProviderType:c.enum(["dynamic_discovery","google_credentials","service_account_impersonation"]).optional(),targetAudience:c.string().optional(),targetServiceAccount:c.string().optional()}),ls=c.object({type:c.literal("sdk"),name:c.string().min(1,"name must be a non-empty string"),instance:c.custom(t=>t&&typeof t=="object"&&"connect"in t&&typeof t.connect=="function",{message:"instance must be an MCP Server with connect method"})}),us=c.union([cs,ls]),ds=c.object({model:c.string().optional(),temp:c.number().optional(),top_p:c.number().optional()}),ps=c.object({max_time_minutes:c.number().optional(),max_turns:c.number().optional()}),xn=c.object({name:c.string().min(1,"Name must be a non-empty string"),description:c.string().min(1,"Description must be a non-empty string"),tools:c.array(c.string()).optional(),systemPrompt:c.string().min(1,"System prompt must be a non-empty string"),modelConfig:ds.partial().optional(),runConfig:ps.partial().optional(),color:c.string().optional(),isBuiltin:c.boolean().optional()}),fs=c.object({canUseTool:c.number().positive().optional(),mcpRequest:c.number().positive().optional(),controlRequest:c.number().positive().optional(),streamClose:c.number().positive().optional()}),hs=c.object({type:c.literal("preset"),preset:c.literal("qwen_code"),append:c.string().min(1,"systemPrompt.append must be a non-empty string").optional()}).strict(),bt=c.object({cwd:c.string().optional(),model:c.string().optional(),pathToQwenExecutable:c.string().optional(),env:c.record(c.string(),c.string()).optional(),systemPrompt:c.union([c.string().min(1,"systemPrompt must be a non-empty string"),hs]).optional(),permissionMode:c.enum(["default","plan","auto-edit","yolo"]).optional(),canUseTool:c.custom(t=>typeof t=="function",{message:"canUseTool must be a function"}).optional(),mcpServers:c.record(c.string(),us).optional(),abortController:c.instanceof(AbortController).optional(),debug:c.boolean().optional(),stderr:c.custom(t=>typeof t=="function",{message:"stderr must be a function"}).optional(),logLevel:c.enum(["debug","info","warn","error"]).optional(),maxSessionTurns:c.number().optional(),coreTools:c.array(c.string()).optional(),excludeTools:c.array(c.string()).optional(),allowedTools:c.array(c.string()).optional(),authType:c.enum(["openai","anthropic","qwen-oauth","gemini","vertex-ai"]).optional(),agents:c.array(c.custom(t=>t&&typeof t=="object"&&"name"in t&&"description"in t&&"systemPrompt"in t&&{message:"agents must be an array of SubagentConfig objects"})).optional(),includePartialMessages:c.boolean().optional(),resume:c.string().optional(),sessionId:c.string().optional(),timeout:fs.optional()}).strict();var kt=require("node:crypto");var ms=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function gs(t){return ms.test(t)}function Ge(t,e="sessionId"){if(!gs(t))throw new Error(`Invalid ${e}: "${t}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`)}var St=T.createLogger("createQuery");function wt({prompt:t,options:e={}}){let r=vs(e),s=typeof t=="string",n=e.pathToQwenExecutable,i=e.abortController??new AbortController,o=e.resume??e.sessionId??(0,kt.randomUUID)(),a=ys(e.systemPrompt),u=new Ee({pathToQwenExecutable:n,spawnInfo:r,cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,env:e.env,...a,abortController:i,debug:e.debug,stderr:e.stderr,logLevel:e.logLevel,maxSessionTurns:e.maxSessionTurns,coreTools:e.coreTools,excludeTools:e.excludeTools,allowedTools:e.allowedTools,authType:e.authType,includePartialMessages:e.includePartialMessages,resume:e.resume,sessionId:o}),d={...e,abortController:i,sessionId:o},m=new fe(u,d,s);if(s){let k=t,N={type:"user",session_id:m.getSessionId(),message:{role:"user",content:k},parent_tool_use_id:null};(async()=>{try{if(await m.initialized,u.exitError)return;u.write(pe(N))}catch(P){u.exitError||St.error("Error sending single-turn prompt:",P)}})()}else m.streamInput(t).catch(k=>{St.error("Error streaming input:",k)});return m}function ys(t){return t?typeof t=="string"?{systemPrompt:t}:t.append?{appendSystemPrompt:t.append}:{}:{}}function vs(t){let e=bt.safeParse(t);if(!e.success){let r=e.error.errors.map(s=>`${s.path.join(".")}: ${s.message}`).join("; ");throw new Error(`Invalid QueryOptions: ${r}`)}t.sessionId&&Ge(t.sessionId,"sessionId"),t.resume&&Ge(t.resume,"resume");try{return Me(t.pathToQwenExecutable)}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`Invalid pathToQwenExecutable: ${s}`)}}function Ct(t,e,r,s){if(!t||typeof t!="string")throw new Error("Tool name must be a non-empty string");if(!e||typeof e!="string")throw new Error(`Tool '${t}' must have a description (string)`);if(!r||typeof r!="object")throw new Error(`Tool '${t}' must have an inputSchema (object)`);if(!s||typeof s!="function")throw new Error(`Tool '${t}' must have a handler (function)`);return{name:t,description:e,inputSchema:r,handler:s}}function Tt(t){if(!t)throw new Error("Tool name cannot be empty");if(t.length>64)throw new Error(`Tool name '${t}' is too long (max 64 characters): ${t.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(t))throw new Error(`Tool name '${t}' is invalid. Must start with a letter and contain only letters, numbers, and underscores.`)}var Rt=require("@modelcontextprotocol/sdk/server/mcp.js");function Mt(t){let{name:e,version:r="1.0.0",tools:s}=t;if(!e||typeof e!="string")throw new Error("MCP server name must be a non-empty string");if(!r||typeof r!="string")throw new Error("MCP server version must be a non-empty string");if(s!==void 0&&!Array.isArray(s))throw new Error("Tools must be an array");let n=new Set;if(s)for(let o of s){if(Tt(o.name),n.has(o.name))throw new Error(`Duplicate tool name '${o.name}' in MCP server '${e}'`);n.add(o.name)}let i=new Rt.McpServer({name:e,version:r},{capabilities:{tools:s?{}:void 0}});return s&&s.forEach(o=>{i.tool(o.name,o.description,o.inputSchema,o.handler)}),{type:"sdk",name:e,instance:i}}0&&(module.exports={AbortError,Query,SdkLogger,createSdkMcpServer,isAbortError,isControlCancel,isControlRequest,isControlResponse,isSDKAssistantMessage,isSDKPartialAssistantMessage,isSDKResultMessage,isSDKSystemMessage,isSDKUserMessage,isSdkMcpServerConfig,query,tool});
package/dist/index.d.ts CHANGED
@@ -397,6 +397,12 @@ export interface Transport {
397
397
  readonly isReady: boolean;
398
398
  readonly exitError: Error | null;
399
399
  }
400
+ export interface QuerySystemPromptPreset {
401
+ type: "preset";
402
+ preset: "qwen_code";
403
+ append?: string;
404
+ }
405
+ export type QuerySystemPrompt = string | QuerySystemPromptPreset;
400
406
  export type ToolInput = Record<string, unknown>;
401
407
  export type CanUseTool = (toolName: string, input: ToolInput, options: {
402
408
  signal: AbortSignal;
@@ -544,6 +550,15 @@ export interface QueryOptions {
544
550
  * These variables will be merged with the current process environment.
545
551
  */
546
552
  env?: Record<string, string>;
553
+ /**
554
+ * System prompt configuration for the Qwen CLI session.
555
+ *
556
+ * - `string`: fully overrides the main session system prompt
557
+ * - `{ type: 'preset', preset: 'qwen_code', append?: string }`:
558
+ * uses Qwen Code's built-in prompt as the base and optionally appends extra
559
+ * instructions for the main session
560
+ */
561
+ systemPrompt?: QuerySystemPrompt;
547
562
  /**
548
563
  * Permission mode controlling how the SDK handles tool execution approval.
549
564
  *