@qwen-code/sdk 0.1.2 → 0.1.4

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.mjs CHANGED
@@ -1,10 +1,10 @@
1
- var ht=Object.defineProperty;var mt=(r,e)=>{for(var t in e)ht(r,t,{get:e[t],enumerable:!0})};var Be={debug:0,info:1,warn:2,error:3},R=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 Be[e]>=Be[this.effectiveLevel]}static formatTimestamp(){let e=new Date,t=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`${t}-${s}-${n} ${i}:${o}:${a}`}static formatMessage(e,t,s,n){let i=this.formatTimestamp(),o=`[${e.toUpperCase()}]`.padEnd(7),a=`${i} ${o} [${t}] ${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,t,s,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,t,s,n);this.config.stderr?this.config.stderr(i):e==="warn"||e==="error"?process.stderr.write(i+`
1
+ var ht=Object.defineProperty;var mt=(r,e)=>{for(var t in e)ht(r,t,{get:e[t],enumerable:!0})};var Be={debug:0,info:1,warn:2,error:3},R=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 Be[e]>=Be[this.effectiveLevel]}static formatTimestamp(){let e=new Date,t=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`${t}-${s}-${n} ${i}:${o}:${a}`}static formatMessage(e,t,s,n){let i=this.formatTimestamp(),o=`[${e.toUpperCase()}]`.padEnd(7),a=`${i} ${o} [${t}] ${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,t,s,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,t,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:(t,...s)=>{this.log("debug",e,t,s)},info:(t,...s)=>{this.log("info",e,t,s)},warn:(t,...s)=>{this.log("warn",e,t,s)},error:(t,...s)=>{this.log("error",e,t,s)}}}static getEffectiveLevel(){return this.effectiveLevel}};function ue(r){try{return JSON.stringify(r)+`
4
- `}catch(e){throw new Error(`Failed to serialize message to JSON: ${e instanceof Error?e.message:String(e)}`)}}function gt(r,e="JsonLines"){let t=R.createLogger(e);try{return JSON.parse(r)}catch(s){return t.warn("Failed to parse JSON line, skipping:",r.substring(0,100),s instanceof Error?s.message:String(s)),null}}function yt(r){return r!==null&&typeof r=="object"&&"type"in r&&typeof r.type=="string"}async function*Qe(r,e="JsonLines"){let t=R.createLogger(e);for await(let s of r){if(s.trim().length===0)continue;let n=gt(s,e);if(n!==null){if(!yt(n)){t.warn("Invalid message structure (missing 'type' field), skipping:",s.substring(0,100));continue}yield n}}}import{spawn as Pt}from"node:child_process";import*as Ye from"node:readline";import*as O from"node:fs";import*as b from"node:path";import{execSync as vt}from"node:child_process";import{fileURLToPath as We}from"node:url";import{createRequire as _t}from"node:module";function He(){let r=null;try{typeof import.meta<"u"&&import.meta.url&&(r=b.dirname(We(import.meta.url)))}catch{}if(!r)try{typeof __dirname<"u"&&(r=__dirname)}catch{}if(r)return b.normalize(r);throw new Error("Cannot find module directory.")}function Fe(){try{let i=_t(import.meta.url).resolve("@qwen-code/sdk/package.json"),o=b.dirname(i),a=b.join(o,"dist","cli","cli.js");if(O.existsSync(a))return o}catch{}let e=He(),t=b.parse(e).root,s=null;for(;e!==t;){let n=b.join(e,"package.json");if(O.existsSync(n)){let i=b.join(e,"dist","cli","cli.js");if(O.existsSync(i))try{if(JSON.parse(O.readFileSync(n,"utf-8")).name==="@qwen-code/sdk")return e;s||(s=e)}catch{s||(s=e)}}e=b.dirname(e)}return s}function xt(r){return r.replace(/\\/g,"/")}function bt(){try{if(typeof import.meta<"u"&&import.meta.url){let r=new URL("./cli/cli.js",import.meta.url),e=We(r);if(O.existsSync(e))return e}}catch{}return null}function Ge(){let r=[],e=bt();e&&r.push(e);try{let t=He(),s=xt(t);if(r.push(b.join(t,"cli","cli.js")),/\/src\/utils$/.test(s)){let o=b.dirname(b.dirname(t));r.push(b.join(o,"dist","cli","cli.js"))}let n=Fe();n&&r.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];r.push(b.join(o,"dist","cli.js"))}}catch{let t=Fe();t&&r.push(b.join(t,"dist","cli","cli.js"))}return r}function St(){let r=Ge();for(let e of r)if(O.existsSync(e))return e;return null}function kt(){let r=St();if(r)return r;let e=Ge();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 gt(r,e="JsonLines"){let t=R.createLogger(e);try{return JSON.parse(r)}catch(s){return t.warn("Failed to parse JSON line, skipping:",r.substring(0,100),s instanceof Error?s.message:String(s)),null}}function yt(r){return r!==null&&typeof r=="object"&&"type"in r&&typeof r.type=="string"}async function*Fe(r,e="JsonLines"){let t=R.createLogger(e);for await(let s of r){if(s.trim().length===0)continue;let n=gt(s,e);if(n!==null){if(!yt(n)){t.warn("Invalid message structure (missing 'type' field), skipping:",s.substring(0,100));continue}yield n}}}import{spawn as Pt}from"node:child_process";import*as Ye from"node:readline";import*as j from"node:fs";import*as b from"node:path";import{execSync as vt}from"node:child_process";import{fileURLToPath as We}from"node:url";import{createRequire as _t}from"node:module";function He(){let r=null;try{typeof import.meta<"u"&&import.meta.url&&(r=b.dirname(We(import.meta.url)))}catch{}if(!r)try{typeof __dirname<"u"&&(r=__dirname)}catch{}if(r)return b.normalize(r);throw new Error("Cannot find module directory.")}function Qe(){try{let i=_t(import.meta.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=He(),t=b.parse(e).root,s=null;for(;e!==t;){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 xt(r){return r.replace(/\\/g,"/")}function bt(){try{if(typeof import.meta<"u"&&import.meta.url){let r=We(import.meta.url),e=b.dirname(r),t=b.join(e,"cli","cli.js");if(j.existsSync(t))return t}}catch{}return null}function Ge(){let r=[],e=bt();e&&r.push(e);try{let t=He(),s=xt(t);if(r.push(b.join(t,"cli","cli.js")),/\/src\/utils$/.test(s)){let o=b.dirname(b.dirname(t));r.push(b.join(o,"dist","cli","cli.js"))}let n=Qe();n&&r.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];r.push(b.join(o,"dist","cli.js"))}}catch{let t=Qe();t&&r.push(b.join(t,"dist","cli","cli.js"))}return r}function St(){let r=Ge();for(let e of r)if(j.existsSync(e))return e;return null}function kt(){let r=St();if(r)return r;let e=Ge();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(t=>` - ${t}`).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 wt(r){if(!O.existsSync(r))throw new Error(`Executable file not found at '${r}'. Please check the file path and ensure the file exists.`);if(!O.statSync(r).isFile())throw new Error(`Path '${r}' exists but is not a file. Please provide a path to an executable file.`)}function Ct(r){return r.includes("/")||r.includes("\\")}function Tt(r){let e=b.extname(r).toLowerCase();return[".js",".mjs",".cjs"].includes(e)}function Rt(r){let e=b.extname(r).toLowerCase();return[".ts",".tsx"].includes(e)}function Mt(r){try{let e=process.platform==="win32"?"where":"which";return vt(`${e} ${r}`,{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Et(){return Mt("tsx")}function Je(){return typeof process<"u"&&"versions"in process&&"bun"in process.versions?"bun":"node"}function we(r){if(r!==void 0&&r.trim()==="")throw new Error("Executable path cannot be empty");if(r===void 0){let t=kt();return{command:process.execPath,args:[t],type:Je(),originalInput:""}}if(!Ct(r)){if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error(`Invalid command name '${r}'. Command names should only contain letters, numbers, dots, hyphens, and underscores.`);return{command:r,args:[],type:"native",originalInput:r}}let e=b.resolve(r);return wt(e),Tt(e)?{command:process.execPath,args:[e],type:Je(),originalInput:r}:Rt(e)&&Et()?{command:"tsx",args:[e],type:"tsx",originalInput:r}:{command:e,args:[],type:"native",originalInput:r}}var k=class r extends Error{constructor(e="Operation aborted"){super(e),this.name="AbortError",Object.setPrototypeOf(this,r.prototype)}};function It(r){return r instanceof k||typeof r=="object"&&r!==null&&"name"in r&&r.name==="AbortError"}var L=R.createLogger("ProcessTransport"),Ce=class{childProcess=null;childStdin=null;childStdout=null;options;ready=!1;_exitError=null;closed=!1;abortController;processExitHandler=null;abortHandler=null;constructor(e){this.options=e,this.abortController=this.options.abortController??new AbortController,R.configure({debug:e.debug,stderr:e.stderr,logLevel:e.logLevel}),this.initialize()}initialize(){try{if(this.abortController.signal.aborted)throw new k("Transport start aborted");let e=this.buildCliArguments(),t=this.options.cwd??process.cwd(),s={...process.env,...this.options.env},n=this.options.spawnInfo??we(this.options.pathToQwenExecutable),i=this.options.debug||this.options.stderr?"pipe":"ignore";L.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=Pt(n.command,[...n.args,...e],{cwd:t,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",a=>{L.debug(a.toString())});let o=()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGTERM")};this.processExitHandler=o,this.abortHandler=o,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.setupEventHandlers(),this.ready=!0,L.info("CLI process started successfully")}catch(e){throw this.ready=!1,L.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 k("CLI process aborted by user"):(this._exitError=new Error(`CLI process error: ${e.message}`),L.error(this._exitError.message))}),this.childProcess.on("close",(e,t)=>{if(this.ready=!1,this.abortController.signal.aborted)this._exitError=new k("CLI process aborted by user");else{let s=this.getProcessExitError(e,t);s&&(this._exitError=s,L.error(s.message))}}))}getProcessExitError(e,t){if(e!==0&&e!==null)return new Error(`CLI process exited with code ${e}`);if(t)return new Error(`CLI process terminated by signal ${t}`)}buildCliArguments(){let e=["--input-format","stream-json","--output-format","stream-json","--channel=SDK","--experimental-skills"];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"),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}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,t)=>{let s=(i,o)=>{if(this.abortController.signal.aborted){t(new k("Operation aborted"));return}let a=this.getProcessExitError(i,o);a?t(a):e()};this.childProcess.once("close",s);let n=i=>{this.childProcess.off("close",s),t(i)};this.childProcess.once("error",n),this.childProcess.once("close",()=>{this.childProcess.off("error",n)})})}write(e){if(this.abortController.signal.aborted)throw new k("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.childStdin.writableEnded)throw new Error("Cannot write to ended stream");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}`);L.debug(`Writing to stdin (${e.length} bytes): ${e.trim()}`);try{this.childStdin.write(e)?L.debug(`Write successful (${e.length} bytes)`):L.warn(`Write buffer full (${e.length} bytes), data queued. Waiting for drain event...`)}catch(t){this.ready=!1;let s=`Failed to write to stdin: ${t instanceof Error?t.message:String(t)}`;throw L.error(s),new Error(s)}}async*readMessages(){if(!this.childStdout)throw new Error("Cannot read messages: process not started");let e=Ye.createInterface({input:this.childStdout,crlfDelay:1/0,terminal:!1});try{for await(let t of Qe(e,"ProcessTransport"))yield t;await this.waitForExit()}finally{e.close()}}get isReady(){return this.ready}get exitError(){return this._exitError}endInput(){this.childStdin&&this.childStdin.end()}getInputStream(){return this.childStdin||void 0}getOutputStream(){return this.childStdout||void 0}};import{randomUUID as Xe}from"node:crypto";function je(r){return r&&typeof r=="object"&&r.type==="user"&&"message"in r}function Le(r){return r&&typeof r=="object"&&r.type==="assistant"&&"uuid"in r&&"message"in r&&"session_id"in r&&"parent_tool_use_id"in r}function Ne(r){return r&&typeof r=="object"&&r.type==="system"&&"subtype"in r&&"uuid"in r&&"session_id"in r}function De(r){return r&&typeof r=="object"&&r.type==="result"&&"subtype"in r&&"duration_ms"in r&&"is_error"in r&&"uuid"in r&&"session_id"in r}function $e(r){return r&&typeof r=="object"&&r.type==="stream_event"&&"uuid"in r&&"session_id"in r&&"event"in r&&"parent_tool_use_id"in r}function qe(r){return r&&typeof r=="object"&&r.type==="control_request"&&"request_id"in r&&"request"in r}function Ue(r){return r&&typeof r=="object"&&r.type==="control_response"&&"response"in r}function Ze(r){return r&&typeof r=="object"&&r.type==="control_cancel_request"&&"request_id"in r}function Te(r){return"type"in r&&r.type==="sdk"}var Re=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.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({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 t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};var Me=class{sendToQuery;serverName;started=!1;logger;onmessage;onerror;onclose;constructor(e){this.sendToQuery=e.sendToQuery,this.serverName=e.serverName,this.logger=R.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(t){throw this.logger.error("Error sending message:",t),this.onerror&&this.onerror(t instanceof Error?t:new Error(String(t))),t}}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 At=6e4,Ot=6e4,jt=6e4,Lt=6e4,S=R.createLogger("Query"),_e=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;constructor(e,t,s=!1){this.transport=e,this.options=t,this.sessionId=Xe(),this.inputStream=new Re,this.abortController=t.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 k("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})):this.abortController.signal.addEventListener("abort",()=>{this.inputStream.error(new k("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})}),this.initialized=this.initialize(),this.initialized.catch(()=>{}),this.startMessageRouter()}async initializeSdkMcpServers(){if(!this.options.mcpServers)return;let e=[];for(let[t,s]of Object.entries(this.options.mcpServers)){if(!Te(s))continue;let n=s.name||t,i=s.instance,o={sendToQuery:async u=>{this.handleMcpServerResponse(n,u)},serverName:n},a=new Me(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,t){if("id"in t&&t.id!==null&&t.id!==void 0){let s=`${e}:${t.id}`,n=this.pendingMcpResponses.get(s);if(n){S.debug(`Routing MCP response for server '${e}', id: ${t.id}`),n.resolve(t),this.pendingMcpResponses.delete(s);return}}S.warn(`Received MCP server response with no pending request: server='${e}'`,t)}getSdkMcpServersForCli(){let e={};for(let[t]of this.sdkMcpServers.entries())e[t]={type:"sdk",name:t};return e}getMcpServersForCli(){if(!this.options.mcpServers)return{};let e={};for(let[t,s]of Object.entries(this.options.mcpServers))Te(s)||(e[t]=s);return e}async initialize(){try{S.debug("Initializing Query"),await this.initializeSdkMcpServers();let e=this.getSdkMcpServersForCli(),t=this.getMcpServersForCli();await this.sendControlRequest("initialize",{hooks:null,sdkMcpServers:Object.keys(e).length>0?e:void 0,mcpServers:Object.keys(t).length>0?t: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 k("Query aborted")):this.inputStream.done()}catch(e){this.inputStream.error(e instanceof Error?e:new Error(String(e)))}})())}async routeMessage(e){if(qe(e)){await this.handleControlRequest(e);return}if(Ue(e)){this.handleControlResponse(e);return}if(Ze(e)){this.handleControlCancelRequest(e);return}if(Ne(e)){this.inputStream.enqueue(e);return}if(De(e)){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleTurn&&"endInput"in this.transport&&this.transport.endInput(),this.inputStream.enqueue(e);return}if(Le(e)||je(e)||$e(e)){this.inputStream.enqueue(e);return}S.warn("Unknown message type:",e),this.inputStream.enqueue(e)}async handleControlRequest(e){let{request_id:t,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(t,!0,i)}catch(i){let o=i instanceof Error?i.message:String(i);S.error(`Control request error (${s.subtype}):`,o),await this.sendControlResponse(t,!1,o)}}async handlePermissionRequest(e,t,s,n){if(!this.options.canUseTool)return{behavior:"deny",message:"Denied"};try{let i=this.options.timeout?.canUseTool??At,o,a=new Promise((u,y)=>{o=setTimeout(()=>y(new Error("Permission callback timeout")),i)}),d=await Promise.race([Promise.resolve(this.options.canUseTool(e,t,{signal:n,suggestions:s})),a]);return o&&clearTimeout(o),d.behavior==="allow"?{behavior:"allow",updatedInput:d.updatedInput??t}:{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,t){let s=this.sdkMcpTransports.get(e);if(!s)throw new Error(`MCP server '${e}' not found in SDK-embedded servers`);return"method"in t&&"id"in t&&t.id!==null?{mcp_response:await this.handleMcpRequest(e,t,s)}:(s.handleMessage(t),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}handleMcpRequest(e,t,s){let n="id"in t?t.id:null,i=`${e}:${n}`;return new Promise((o,a)=>{let d=this.options.timeout?.mcpRequest??Ot,u=setTimeout(()=>{this.pendingMcpResponses.delete(i),a(new Error("MCP request timeout"))},d),y=()=>{clearTimeout(u),this.pendingMcpResponses.delete(i)},C=F=>{y(),o(F)},ke=F=>{y(),a(F)};this.pendingMcpResponses.set(i,{resolve:C,reject:ke}),s.handleMessage(t)})}handleControlResponse(e){let{response:t}=e,s=t.request_id,n=this.pendingControlRequests.get(s);if(!n){S.warn("Received response for unknown request:",s,JSON.stringify(t));return}if(clearTimeout(n.timeout),this.pendingControlRequests.delete(s),t.subtype==="success")S.debug(`Control response success for request: ${s}: ${JSON.stringify(t.response)}`),n.resolve(t.response);else{let i=typeof t.error=="string"?t.error:t.error?.message??"Unknown error";S.error(`Control response error for request ${s}:`,i),n.reject(new Error(i))}}handleControlCancelRequest(e){let{request_id:t}=e;if(!t){S.warn("Received cancel request without request_id");return}let s=this.pendingControlRequests.get(t);s&&(S.debug(`Cancelling control request: ${t}`),s.abortController.abort(),clearTimeout(s.timeout),this.pendingControlRequests.delete(t),s.reject(new k("Request cancelled")))}async sendControlRequest(e,t={}){if(this.closed)return Promise.reject(new Error("Query is closed"));e!=="initialize"&&await this.initialized;let s=Xe(),n={type:"control_request",request_id:s,request:{subtype:e,...t}},i=new Promise((o,a)=>{let d=new AbortController,u=this.options.timeout?.controlRequest??jt,y=setTimeout(()=>{this.pendingControlRequests.delete(s),a(new Error(`Control request timeout: ${e}`))},u);this.pendingControlRequests.set(s,{resolve:o,reject:a,timeout:y,abortController:d})});return this.transport.write(ue(n)),i}async sendControlResponse(e,t,s){let n={type:"control_response",response:t?{subtype:"success",request_id:e,response:s}:{subtype:"error",request_id:e,error:s}};this.transport.write(ue(n))}async close(){if(!this.closed){this.closed=!0;for(let e of this.pendingControlRequests.values())e.abortController.abort(),clearTimeout(e.timeout),e.reject(new Error("Query is closed"));this.pendingControlRequests.clear();for(let e of this.pendingMcpResponses.values())e.reject(new Error("Query is closed"));this.pendingMcpResponses.clear(),await this.transport.close(),this.inputStream.hasError===void 0&&(this.abortController.signal.aborted?this.inputStream.error(new k("Query aborted")):this.inputStream.done());for(let e of this.sdkMcpTransports.values())try{await e.close()}catch(t){S.error("Error closing MCP transport:",t)}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 t of e){if(this.abortController.signal.aborted)break;this.transport.write(ue(t))}if(!this.isSingleTurn&&this.sdkMcpTransports.size>0&&this.firstResultReceivedPromise){let t=this.options.timeout?.streamClose??Lt,s,n=new Promise(i=>{s=setTimeout(()=>{S.info("streamCloseTimeout resolved"),i()},t)});await Promise.race([this.firstResultReceivedPromise,n]),s&&clearTimeout(s)}this.endInput()}catch(t){if(this.abortController.signal.aborted){S.info("Aborted during input streaming"),this.inputStream.error(new k("Query aborted during input streaming"));return}throw t}}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={};mt(l,{BRAND:()=>ar,DIRTY:()=>J,EMPTY_PATH:()=>qt,INVALID:()=>m,NEVER:()=>Br,OK:()=>T,ParseStatus:()=>w,Schema:()=>_,ZodAny:()=>B,ZodArray:()=>z,ZodBigInt:()=>H,ZodBoolean:()=>G,ZodBranded:()=>be,ZodCatch:()=>ce,ZodDate:()=>Y,ZodDefault:()=>ae,ZodDiscriminatedUnion:()=>Pe,ZodEffects:()=>A,ZodEnum:()=>ie,ZodError:()=>M,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>c,ZodLazy:()=>se,ZodLiteral:()=>ne,ZodMap:()=>ge,ZodNaN:()=>ve,ZodNativeEnum:()=>oe,ZodNever:()=>j,ZodNull:()=>ee,ZodNullable:()=>$,ZodNumber:()=>W,ZodObject:()=>E,ZodOptional:()=>I,ZodParsedType:()=>f,ZodPipeline:()=>Se,ZodPromise:()=>Q,ZodReadonly:()=>le,ZodRecord:()=>Ae,ZodSchema:()=>_,ZodSet:()=>ye,ZodString:()=>V,ZodSymbol:()=>he,ZodTransformer:()=>A,ZodTuple:()=>D,ZodType:()=>_,ZodUndefined:()=>X,ZodUnion:()=>te,ZodUnknown:()=>Z,ZodVoid:()=>me,addIssueToContext:()=>p,any:()=>gr,array:()=>xr,bigint:()=>dr,boolean:()=>ut,coerce:()=>Vr,custom:()=>at,date:()=>pr,datetimeRegex:()=>it,defaultErrorMap:()=>q,discriminatedUnion:()=>wr,effect:()=>Nr,enum:()=>Or,function:()=>Ir,getErrorMap:()=>de,getParsedType:()=>N,instanceof:()=>lr,intersection:()=>Cr,isAborted:()=>Ee,isAsync:()=>pe,isDirty:()=>Ie,isValid:()=>K,late:()=>cr,lazy:()=>Pr,literal:()=>Ar,makeIssue:()=>xe,map:()=>Mr,nan:()=>ur,nativeEnum:()=>jr,never:()=>vr,null:()=>mr,nullable:()=>$r,number:()=>lt,object:()=>br,objectUtil:()=>ze,oboolean:()=>Kr,onumber:()=>zr,optional:()=>Dr,ostring:()=>Zr,pipeline:()=>Ur,preprocess:()=>qr,promise:()=>Lr,quotelessJson:()=>Nt,record:()=>Rr,set:()=>Er,setErrorMap:()=>$t,strictObject:()=>Sr,string:()=>ct,symbol:()=>fr,transformer:()=>Nr,tuple:()=>Tr,undefined:()=>hr,union:()=>kr,unknown:()=>yr,util:()=>x,void:()=>_r});var x;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},r.getValidEnumValues=n=>{let i=r.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return r.objectValues(o)},r.objectValues=n=>r.objectKeys(n).map(function(i){return n[i]}),r.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},r.find=(n,i)=>{for(let o of n)if(i(o))return o},r.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)}r.joinValues=s,r.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var ze;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ze||(ze={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?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(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r 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"]),Nt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),M=class r 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=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(t(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(t(o))):a[u]=a[u]||{_errors:[]},a=a[u],d++}}};return n(this),s}static assert(e){if(!(e instanceof r))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=t=>t.message){let t={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};M.create=r=>new M(r);var Dt=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},q=Dt;var et=q;function $t(r){et=r}function de(){return et}var xe=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,i=[...t,...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}},qt=[];function p(r,e){let t=de(),s=xe({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===q?void 0:q].filter(n=>!!n)});r.common.issues.push(s)}var w=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return m;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return m;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}}},m=Object.freeze({status:"aborted"}),J=r=>({status:"dirty",value:r}),T=r=>({status:"valid",value:r}),Ee=r=>r.status==="aborted",Ie=r=>r.status==="dirty",K=r=>r.status==="valid",pe=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var P=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,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}},tt=(r,e)=>{if(K(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new M(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||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}=r;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??t??a.defaultError}},description:n}}var _=class{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(pe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parseSync({data:e,path:s.path,parent:s});return tt(s,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return K(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>K(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(pe(n)?n:Promise.resolve(n));return tt(s,i)}refine(e,t){let s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;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,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new A({schema:this,typeName:g.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:t=>this["~validate"](t)}}optional(){return I.create(this,this._def)}nullable(){return $.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return Q.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new A({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ae({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new be({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ce({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ut=/^c[^\s-]{8,}$/i,Zt=/^[0-9a-z]+$/,zt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kt=/^[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,Vt=/^[a-z0-9_-]{21}$/i,Bt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qt=/^[-+]?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)?)??$/,Ft=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Jt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ke,Wt=/^(?:(?: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])$/,Ht=/^(?:(?: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])$/,Gt=/^(([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]))$/,Yt=/^(([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])$/,Xt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,er=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,st="((\\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])))",tr=new RegExp(`^${st}$`);function nt(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rr(r){return new RegExp(`^${nt(r)}$`)}function it(r){let e=`${st}T${nt(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function sr(r,e){return!!((e==="v4"||!e)&&Wt.test(r)||(e==="v6"||!e)&&Gt.test(r))}function nr(r,e){if(!Bt.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 ir(r,e){return!!((e==="v4"||!e)&&Ht.test(r)||(e==="v6"||!e)&&Yt.test(r))}var V=class r 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}),m}let s=new w,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")Ft.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")Ke||(Ke=new RegExp(Jt,"u")),Ke.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")Kt.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")Vt.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")Ut.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")Zt.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")zt.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"?it(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"?tr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?rr(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"?Qt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?sr(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"?nr(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"?ir(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"?Xt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?er.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,t,s){return this.refinement(n=>e.test(n),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};V.create=r=>new V({checks:[],typeName:g.ZodString,coerce:r?.coerce??!1,...v(r)});function or(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,i=Number.parseInt(r.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var W=class r 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}),m}let s,n=new w;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"?or(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,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.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,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};W.create=r=>new W({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...v(r)});var H=class r 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 w;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 t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};H.create=r=>new H({checks:[],typeName:g.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var G=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}),m}return T(e.data)}};G.create=r=>new G({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var Y=class r 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}),m}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_date}),m}let s=new w,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 r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Y.create=r=>new Y({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...v(r)});var he=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}),m}return T(e.data)}};he.create=r=>new he({typeName:g.ZodSymbol,...v(r)});var X=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}),m}return T(e.data)}};X.create=r=>new X({typeName:g.ZodUndefined,...v(r)});var ee=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}),m}return T(e.data)}};ee.create=r=>new ee({typeName:g.ZodNull,...v(r)});var B=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};B.create=r=>new B({typeName:g.ZodAny,...v(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};Z.create=r=>new Z({typeName:g.ZodUnknown,...v(r)});var j=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),m}};j.create=r=>new j({typeName:g.ZodNever,...v(r)});var me=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}),m}return T(e.data)}};me.create=r=>new me({typeName:g.ZodVoid,...v(r)});var z=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return p(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),m;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(o||a)&&(p(t,{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&&t.data.length<n.minLength.value&&(p(t,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(p(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>n.type._parseAsync(new P(t,o,t.path,a)))).then(o=>w.mergeArray(s,o));let i=[...t.data].map((o,a)=>n.type._parseSync(new P(t,o,t.path,a)));return w.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};z.create=(r,e)=>new z({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function fe(r){if(r instanceof E){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=I.create(fe(s))}return new E({...r._def,shape:()=>e})}else return r instanceof z?new z({...r._def,type:fe(r.element)}):r instanceof I?I.create(fe(r.unwrap())):r instanceof $?$.create(fe(r.unwrap())):r instanceof D?D.create(r.items.map(e=>fe(e))):r}var E=class r 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(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},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}),m}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof j&&this._def.unknownKeys==="strip"))for(let u in n.data)o.includes(u)||a.push(u);let d=[];for(let u of o){let y=i[u],C=n.data[u];d.push({key:{status:"valid",value:u},value:y._parse(new P(n,C,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof j){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of a)d.push({key:{status:"valid",value:y},value:{status:"valid",value:n.data[y]}});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 y of a){let C=n.data[y];d.push({key:{status:"valid",value:y},value:u._parse(new P(n,C,n.path,y)),alwaysSet:y in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of d){let C=await y.key,ke=await y.value;u.push({key:C,value:ke,alwaysSet:y.alwaysSet})}return u}).then(u=>w.mergeObjectSync(s,u)):w.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of x.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of x.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return fe(this)}partial(e){let t={};for(let s of x.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of x.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof I;)i=i._def.innerType;t[s]=i}return new r({...this._def,shape:()=>t})}keyof(){return ot(x.objectKeys(this.shape))}};E.create=(r,e)=>new E({shape:()=>r,unknownKeys:"strip",catchall:j.create(),typeName:g.ZodObject,...v(e)});E.strictCreate=(r,e)=>new E({shape:()=>r,unknownKeys:"strict",catchall:j.create(),typeName:g.ZodObject,...v(e)});E.lazycreate=(r,e)=>new E({shape:r,unknownKeys:"strip",catchall:j.create(),typeName:g.ZodObject,...v(e)});var te=class extends _{_parse(e){let{ctx:t}=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 t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new M(a.ctx.common.issues));return p(t,{code:c.invalid_union,unionErrors:o}),m}if(t.common.async)return Promise.all(s.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let d of s){let u={...t,common:{...t.common,issues:[]},parent:null},y=d._parseSync({data:t.data,path:t.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!i&&(i={result:y,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(d=>new M(d));return p(t,{code:c.invalid_union,unionErrors:a}),m}}get options(){return this._def.options}};te.create=(r,e)=>new te({options:r,typeName:g.ZodUnion,...v(e)});var U=r=>r instanceof se?U(r.schema):r instanceof A?U(r.innerType()):r instanceof ne?[r.value]:r instanceof ie?r.options:r instanceof oe?x.objectValues(r.enum):r instanceof ae?U(r._def.innerType):r instanceof X?[void 0]:r instanceof ee?[null]:r instanceof I?[void 0,...U(r.unwrap())]:r instanceof $?[null,...U(r.unwrap())]:r instanceof be||r instanceof le?U(r.unwrap()):r instanceof ce?U(r._def.innerType):[],Pe=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),m;let s=this.discriminator,n=t.data[s],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let n=new Map;for(let i of t){let o=U(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 r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...v(s)})}};function Ve(r,e){let t=N(r),s=N(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&s===f.object){let n=x.objectKeys(e),i=x.objectKeys(r).filter(a=>n.indexOf(a)!==-1),o={...r,...e};for(let a of i){let d=Ve(r[a],e[a]);if(!d.valid)return{valid:!1};o[a]=d.data}return{valid:!0,data:o}}else if(t===f.array&&s===f.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],d=Ve(o,a);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return t===f.date&&s===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var re=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ee(i)||Ee(o))return m;let a=Ve(i.value,o.value);return a.valid?((Ie(i)||Ie(o))&&t.dirty(),{status:t.value,value:a.data}):(p(s,{code:c.invalid_intersection_types}),m)};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}))}};re.create=(r,e,t)=>new re({left:r,right:e,typeName:g.ZodIntersection,...v(t)});var D=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),m;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"}),m;!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"}),t.dirty());let i=[...s.data].map((o,a)=>{let d=this._def.items[a]||this._def.rest;return d?d._parse(new P(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>w.mergeArray(t,o)):w.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};D.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new D({items:r,typeName:g.ZodTuple,rest:null,...v(e)})};var Ae=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),m;let n=[],i=this._def.keyType,o=this._def.valueType;for(let a in s.data)n.push({key:i._parse(new P(s,a,s.path,a)),value:o._parse(new P(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?w.mergeObjectAsync(t,n):w.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...v(s)}):new r({keyType:V.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},ge=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),m;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,d],u)=>({key:n._parse(new P(s,a,s.path,[u,"key"])),value:i._parse(new P(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,y=await d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(u.value,y.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let d of o){let u=d.key,y=d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(u.value,y.value)}return{status:t.value,value:a}}}};ge.create=(r,e,t)=>new ge({valueType:e,keyType:r,typeName:g.ZodMap,...v(t)});var ye=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),m;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}),t.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}),t.dirty());let i=this._def.valueType;function o(d){let u=new Set;for(let y of d){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),u.add(y.value)}return{status:t.value,value:u}}let a=[...s.data.values()].map((d,u)=>i._parse(new P(s,d,s.path,u)));return s.common.async?Promise.all(a).then(d=>o(d)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ye.create=(r,e)=>new ye({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Oe=class r extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),m;function s(a,d){return xe({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),q].filter(u=>!!u),issueData:{code:c.invalid_arguments,argumentsError:d}})}function n(a,d){return xe({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),q].filter(u=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:d}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Q){let a=this;return T(async function(...d){let u=new M([]),y=await a._def.args.parseAsync(d,i).catch(F=>{throw u.addIssue(s(d,F)),u}),C=await Reflect.apply(o,this,y);return await a._def.returns._def.type.parseAsync(C,i).catch(F=>{throw u.addIssue(n(C,F)),u})})}else{let a=this;return T(function(...d){let u=a._def.args.safeParse(d,i);if(!u.success)throw new M([s(d,u.error)]);let y=Reflect.apply(o,this,u.data),C=a._def.returns.safeParse(y,i);if(!C.success)throw new M([n(y,C.error)]);return C.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:D.create(e).rest(Z.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||D.create([]).rest(Z.create()),returns:t||Z.create(),typeName:g.ZodFunction,...v(s)})}},se=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};se.create=(r,e)=>new se({getter:r,typeName:g.ZodLazy,...v(e)});var ne=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};ne.create=(r,e)=>new ne({value:r,typeName:g.ZodLiteral,...v(e)});function ot(r,e){return new ie({values:r,typeName:g.ZodEnum,...v(e)})}var ie=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return p(t,{expected:x.joinValues(s),received:t.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return p(t,{received:t.data,code:c.invalid_enum_value,options:s}),m}return T(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};ie.create=ot;var oe=class extends _{_parse(e){let t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=x.objectValues(t);return p(s,{expected:x.joinValues(n),received:s.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=x.objectValues(t);return p(s,{received:s.data,code:c.invalid_enum_value,options:n}),m}return T(e.data)}get enum(){return this._def.values}};oe.create=(r,e)=>new oe({values:r,typeName:g.ZodNativeEnum,...v(e)});var Q=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),m;let s=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return T(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Q.create=(r,e)=>new Q({type:r,typeName:g.ZodPromise,...v(e)});var A=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?t.abort():t.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(t.value==="aborted")return m;let d=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return d.status==="aborted"?m:d.status==="dirty"?J(d.value):t.value==="dirty"?J(d.value):d});{if(t.value==="aborted")return m;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?m:a.status==="dirty"?J(a.value):t.value==="dirty"?J(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"?m:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?m:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.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(!K(o))return m;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:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>K(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:t.value,value:a})):m);x.assertNever(n)}};A.create=(r,e,t)=>new A({schema:r,typeName:g.ZodEffects,effect:e,...v(t)});A.createWithPreprocess=(r,e,t)=>new A({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...v(t)});var I=class extends _{_parse(e){return this._getType(e)===f.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I.create=(r,e)=>new I({innerType:r,typeName:g.ZodOptional,...v(e)});var $=class extends _{_parse(e){return this._getType(e)===f.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$.create=(r,e)=>new $({innerType:r,typeName:g.ZodNullable,...v(e)});var ae=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ae.create=(r,e)=>new ae({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ce=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return pe(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new M(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new M(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ce.create=(r,e)=>new ce({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var ve=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}),m}return{status:"valid",value:e.data}}};ve.create=r=>new ve({typeName:g.ZodNaN,...v(r)});var ar=Symbol("zod_brand"),be=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},Se=class r extends _{_parse(e){let{status:t,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"?m:i.status==="dirty"?(t.dirty(),J(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"?m:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},le=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=n=>(K(n)&&(n.value=Object.freeze(n.value)),n);return pe(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};le.create=(r,e)=>new le({innerType:r,typeName:g.ZodReadonly,...v(e)});function rt(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function at(r,e={},t){return r?B.create().superRefine((s,n)=>{let i=r(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=rt(e,s),d=a.fatal??t??!0;n.addIssue({code:"custom",...a,fatal:d})}});if(!i){let o=rt(e,s),a=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:a})}}):B.create()}var cr={object:E.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var lr=(r,e={message:`Input not instance of ${r.name}`})=>at(t=>t instanceof r,e),ct=V.create,lt=W.create,ur=ve.create,dr=H.create,ut=G.create,pr=Y.create,fr=he.create,hr=X.create,mr=ee.create,gr=B.create,yr=Z.create,vr=j.create,_r=me.create,xr=z.create,br=E.create,Sr=E.strictCreate,kr=te.create,wr=Pe.create,Cr=re.create,Tr=D.create,Rr=Ae.create,Mr=ge.create,Er=ye.create,Ir=Oe.create,Pr=se.create,Ar=ne.create,Or=ie.create,jr=oe.create,Lr=Q.create,Nr=A.create,Dr=I.create,$r=$.create,qr=A.createWithPreprocess,Ur=Se.create,Zr=()=>ct().optional(),zr=()=>lt().optional(),Kr=()=>ut().optional(),Vr={string:(r=>V.create({...r,coerce:!0})),number:(r=>W.create({...r,coerce:!0})),boolean:(r=>G.create({...r,coerce:!0})),bigint:(r=>H.create({...r,coerce:!0})),date:(r=>Y.create({...r,coerce:!0}))};var Br=m;var Qr=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(),Fr=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:Qr.optional(),authProviderType:l.enum(["dynamic_discovery","google_credentials","service_account_impersonation"]).optional(),targetAudience:l.string().optional(),targetServiceAccount:l.string().optional()}),Jr=l.object({type:l.literal("sdk"),name:l.string().min(1,"name must be a non-empty string"),instance:l.custom(r=>r&&typeof r=="object"&&"connect"in r&&typeof r.connect=="function",{message:"instance must be an MCP Server with connect method"})}),Wr=l.union([Fr,Jr]),Hr=l.object({model:l.string().optional(),temp:l.number().optional(),top_p:l.number().optional()}),Gr=l.object({max_time_minutes:l.number().optional(),max_turns:l.number().optional()}),ln=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:Hr.partial().optional(),runConfig:Gr.partial().optional(),color:l.string().optional(),isBuiltin:l.boolean().optional()}),Yr=l.object({canUseTool:l.number().positive().optional(),mcpRequest:l.number().positive().optional(),controlRequest:l.number().positive().optional(),streamClose:l.number().positive().optional()}),dt=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(r=>typeof r=="function",{message:"canUseTool must be a function"}).optional(),mcpServers:l.record(l.string(),Wr).optional(),abortController:l.instanceof(AbortController).optional(),debug:l.boolean().optional(),stderr:l.custom(r=>typeof r=="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","qwen-oauth"]).optional(),agents:l.array(l.custom(r=>r&&typeof r=="object"&&"name"in r&&"description"in r&&"systemPrompt"in r&&{message:"agents must be an array of SubagentConfig objects"})).optional(),includePartialMessages:l.boolean().optional(),timeout:Yr.optional()}).strict();var pt=R.createLogger("createQuery");function Xr({prompt:r,options:e={}}){let t=es(e),s=typeof r=="string",n=e.pathToQwenExecutable,i=e.abortController??new AbortController,o=new Ce({pathToQwenExecutable:n,spawnInfo:t,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}),a={...e,abortController:i},d=new _e(o,a,s);if(s){let u=r,y={type:"user",session_id:d.getSessionId(),message:{role:"user",content:u},parent_tool_use_id:null};(async()=>{try{await d.initialized,o.write(ue(y))}catch(C){pt.error("Error sending single-turn prompt:",C)}})()}else d.streamInput(r).catch(u=>{pt.error("Error streaming input:",u)});return d}function es(r){let e=dt.safeParse(r);if(!e.success){let t=e.error.errors.map(s=>`${s.path.join(".")}: ${s.message}`).join("; ");throw new Error(`Invalid QueryOptions: ${t}`)}try{return we(r.pathToQwenExecutable)}catch(t){let s=t instanceof Error?t.message:String(t);throw new Error(`Invalid pathToQwenExecutable: ${s}`)}}function ts(r,e,t,s){if(!r||typeof r!="string")throw new Error("Tool name must be a non-empty string");if(!e||typeof e!="string")throw new Error(`Tool '${r}' must have a description (string)`);if(!t||typeof t!="object")throw new Error(`Tool '${r}' must have an inputSchema (object)`);if(!s||typeof s!="function")throw new Error(`Tool '${r}' must have a handler (function)`);return{name:r,description:e,inputSchema:t,handler:s}}function ft(r){if(!r)throw new Error("Tool name cannot be empty");if(r.length>64)throw new Error(`Tool name '${r}' is too long (max 64 characters): ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error(`Tool name '${r}' is invalid. Must start with a letter and contain only letters, numbers, and underscores.`)}import{McpServer as rs}from"@modelcontextprotocol/sdk/server/mcp.js";function ss(r){let{name:e,version:t="1.0.0",tools:s}=r;if(!e||typeof e!="string")throw new Error("MCP server name must be a non-empty string");if(!t||typeof t!="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(ft(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 rs({name:e,version:t},{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}}export{k as AbortError,_e as Query,R as SdkLogger,ss as createSdkMcpServer,It as isAbortError,Ze as isControlCancel,qe as isControlRequest,Ue as isControlResponse,Le as isSDKAssistantMessage,$e as isSDKPartialAssistantMessage,De as isSDKResultMessage,Ne as isSDKSystemMessage,je as isSDKUserMessage,Te as isSdkMcpServerConfig,Xr as query,ts as tool};
10
+ \u2022 query({ pathToQwenExecutable: "/path/to/cli.js" })`)}function wt(r){if(!j.existsSync(r))throw new Error(`Executable file not found at '${r}'. Please check the file path and ensure the file exists.`);if(!j.statSync(r).isFile())throw new Error(`Path '${r}' exists but is not a file. Please provide a path to an executable file.`)}function Ct(r){return r.includes("/")||r.includes("\\")}function Tt(r){let e=b.extname(r).toLowerCase();return[".js",".mjs",".cjs"].includes(e)}function Rt(r){let e=b.extname(r).toLowerCase();return[".ts",".tsx"].includes(e)}function Mt(r){try{let e=process.platform==="win32"?"where":"which";return vt(`${e} ${r}`,{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Et(){return Mt("tsx")}function Je(){return typeof process<"u"&&"versions"in process&&"bun"in process.versions?"bun":"node"}function we(r){if(r!==void 0&&r.trim()==="")throw new Error("Executable path cannot be empty");if(r===void 0){let t=kt();return{command:process.execPath,args:[t],type:Je(),originalInput:""}}if(!Ct(r)){if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error(`Invalid command name '${r}'. Command names should only contain letters, numbers, dots, hyphens, and underscores.`);return{command:r,args:[],type:"native",originalInput:r}}let e=b.resolve(r);return wt(e),Tt(e)?{command:process.execPath,args:[e],type:Je(),originalInput:r}:Rt(e)&&Et()?{command:"tsx",args:[e],type:"tsx",originalInput:r}:{command:e,args:[],type:"native",originalInput:r}}var k=class r extends Error{constructor(e="Operation aborted"){super(e),this.name="AbortError",Object.setPrototypeOf(this,r.prototype)}};function It(r){return r instanceof k||typeof r=="object"&&r!==null&&"name"in r&&r.name==="AbortError"}var I=R.createLogger("ProcessTransport"),Ce=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,R.configure({debug:e.debug,stderr:e.stderr,logLevel:e.logLevel}),this.initialize()}initialize(){try{if(this.abortController.signal.aborted)throw new k("Transport start aborted");let e=this.buildCliArguments(),t=this.options.cwd??process.cwd(),s={...process.env,...this.options.env},n=this.options.spawnInfo??we(this.options.pathToQwenExecutable),i=this.options.debug||this.options.stderr?"pipe":"ignore";I.debug(`Spawning CLI (${n.type}): ${n.command} ${[...n.args,...e].join(" ")}`),this.childProcess=Pt(n.command,[...n.args,...e],{cwd:t,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",a=>{I.debug(a.toString())});let o=()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGTERM")};this.processExitHandler=o,this.abortHandler=o,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.setupEventHandlers(),this.ready=!0,I.info("CLI process started successfully")}catch(e){throw this.ready=!1,I.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 k("CLI process aborted by user"):(this._exitError=new Error(`CLI process error: ${e.message}`),I.error(this._exitError.message))}),this.childProcess.on("close",(e,t)=>{if(this.ready=!1,this.abortController.signal.aborted)this._exitError=new k("CLI process aborted by user");else{let s=this.getProcessExitError(e,t);s&&(this._exitError=s,I.error(s.message))}}))}getProcessExitError(e,t){if(e!==0&&e!==null)return new Error(`CLI process exited with code ${e}`);if(t)return new Error(`CLI process terminated by signal ${t}`)}buildCliArguments(){let e=["--input-format","stream-json","--output-format","stream-json","--channel=SDK","--experimental-skills"];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"),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,t)=>{let s=(i,o)=>{if(this.abortController.signal.aborted){t(new k("Operation aborted"));return}let a=this.getProcessExitError(i,o);a?t(a):e()};this.childProcess.once("close",s);let n=i=>{this.childProcess.off("close",s),t(i)};this.childProcess.once("error",n),this.childProcess.once("close",()=>{this.childProcess.off("error",n)})})}write(e){if(this.abortController.signal.aborted)throw new k("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,I.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}`);I.debug(`Writing to stdin (${e.length} bytes): ${e.trim()}`);try{this.childStdin.write(e)?I.debug(`Write successful (${e.length} bytes)`):I.warn(`Write buffer full (${e.length} bytes), data queued. Waiting for drain event...`)}catch(t){let s=t instanceof Error?t.message:String(t);if(s.includes("EPIPE")||s.includes("ERR_STREAM_WRITE_AFTER_END")||s.includes("write after end"))throw this.inputClosed=!0,I.warn(`Stream closed, cannot write: ${s}`),new Error("Input stream closed");this.ready=!1;let i=`Failed to write to stdin: ${s}`;throw I.error(i),new Error(i)}}async*readMessages(){if(!this.childStdout)throw new Error("Cannot read messages: process not started");let e=Ye.createInterface({input:this.childStdout,crlfDelay:1/0,terminal:!1});try{for await(let t of Fe(e,"ProcessTransport"))yield t;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}};import{randomUUID as Xe}from"node:crypto";function je(r){return r&&typeof r=="object"&&r.type==="user"&&"message"in r}function Le(r){return r&&typeof r=="object"&&r.type==="assistant"&&"uuid"in r&&"message"in r&&"session_id"in r&&"parent_tool_use_id"in r}function Ne(r){return r&&typeof r=="object"&&r.type==="system"&&"subtype"in r&&"uuid"in r&&"session_id"in r}function De(r){return r&&typeof r=="object"&&r.type==="result"&&"subtype"in r&&"duration_ms"in r&&"is_error"in r&&"uuid"in r&&"session_id"in r}function $e(r){return r&&typeof r=="object"&&r.type==="stream_event"&&"uuid"in r&&"session_id"in r&&"event"in r&&"parent_tool_use_id"in r}function qe(r){return r&&typeof r=="object"&&r.type==="control_request"&&"request_id"in r&&"request"in r}function Ue(r){return r&&typeof r=="object"&&r.type==="control_response"&&"response"in r}function Ze(r){return r&&typeof r=="object"&&r.type==="control_cancel_request"&&"request_id"in r}function Te(r){return"type"in r&&r.type==="sdk"}var Re=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.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({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 t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};var Me=class{sendToQuery;serverName;started=!1;logger;onmessage;onerror;onclose;constructor(e){this.sendToQuery=e.sendToQuery,this.serverName=e.serverName,this.logger=R.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(t){throw this.logger.error("Error sending message:",t),this.onerror&&this.onerror(t instanceof Error?t:new Error(String(t))),t}}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 At=6e4,Ot=6e4,jt=6e4,Lt=6e4,S=R.createLogger("Query"),_e=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;constructor(e,t,s=!1){this.transport=e,this.options=t,this.sessionId=Xe(),this.inputStream=new Re,this.abortController=t.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 k("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})):this.abortController.signal.addEventListener("abort",()=>{this.inputStream.error(new k("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})}),this.initialized=this.initialize(),this.initialized.catch(()=>{}),this.startMessageRouter()}async initializeSdkMcpServers(){if(!this.options.mcpServers)return;let e=[];for(let[t,s]of Object.entries(this.options.mcpServers)){if(!Te(s))continue;let n=s.name||t,i=s.instance,o={sendToQuery:async d=>{this.handleMcpServerResponse(n,d)},serverName:n},a=new Me(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,t){if("id"in t&&t.id!==null&&t.id!==void 0){let s=`${e}:${t.id}`,n=this.pendingMcpResponses.get(s);if(n){S.debug(`Routing MCP response for server '${e}', id: ${t.id}`),n.resolve(t),this.pendingMcpResponses.delete(s);return}}S.warn(`Received MCP server response with no pending request: server='${e}'`,t)}getSdkMcpServersForCli(){let e={};for(let[t]of this.sdkMcpServers.entries())e[t]={type:"sdk",name:t};return e}getMcpServersForCli(){if(!this.options.mcpServers)return{};let e={};for(let[t,s]of Object.entries(this.options.mcpServers))Te(s)||(e[t]=s);return e}async initialize(){try{S.debug("Initializing Query"),await this.initializeSdkMcpServers();let e=this.getSdkMcpServersForCli(),t=this.getMcpServersForCli();await this.sendControlRequest("initialize",{hooks:null,sdkMcpServers:Object.keys(e).length>0?e:void 0,mcpServers:Object.keys(t).length>0?t: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 k("Query aborted")):this.inputStream.done()}catch(e){this.inputStream.error(e instanceof Error?e:new Error(String(e)))}})())}async routeMessage(e){if(qe(e)){await this.handleControlRequest(e);return}if(Ue(e)){this.handleControlResponse(e);return}if(Ze(e)){this.handleControlCancelRequest(e);return}if(Ne(e)){this.inputStream.enqueue(e);return}if(De(e)){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleTurn&&"endInput"in this.transport&&this.transport.endInput(),this.inputStream.enqueue(e);return}if(Le(e)||je(e)||$e(e)){this.inputStream.enqueue(e);return}S.warn("Unknown message type:",e),this.inputStream.enqueue(e)}async handleControlRequest(e){let{request_id:t,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(t,!0,i)}catch(i){let o=i instanceof Error?i.message:String(i);S.error(`Control request error (${s.subtype}):`,o),await this.sendControlResponse(t,!1,o)}}async handlePermissionRequest(e,t,s,n){if(!this.options.canUseTool)return{behavior:"deny",message:"Denied"};try{let i=this.options.timeout?.canUseTool??At,o,a=new Promise((d,y)=>{o=setTimeout(()=>y(new Error("Permission callback timeout")),i)}),u=await Promise.race([Promise.resolve(this.options.canUseTool(e,t,{signal:n,suggestions:s})),a]);return o&&clearTimeout(o),u.behavior==="allow"?{behavior:"allow",updatedInput:u.updatedInput??t}:{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,t){let s=this.sdkMcpTransports.get(e);if(!s)throw new Error(`MCP server '${e}' not found in SDK-embedded servers`);return"method"in t&&"id"in t&&t.id!==null?{mcp_response:await this.handleMcpRequest(e,t,s)}:(s.handleMessage(t),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}handleMcpRequest(e,t,s){let n="id"in t?t.id:null,i=`${e}:${n}`;return new Promise((o,a)=>{let u=this.options.timeout?.mcpRequest??Ot,d=setTimeout(()=>{this.pendingMcpResponses.delete(i),a(new Error("MCP request timeout"))},u),y=()=>{clearTimeout(d),this.pendingMcpResponses.delete(i)},C=Q=>{y(),o(Q)},ke=Q=>{y(),a(Q)};this.pendingMcpResponses.set(i,{resolve:C,reject:ke}),s.handleMessage(t)})}handleControlResponse(e){let{response:t}=e,s=t.request_id,n=this.pendingControlRequests.get(s);if(!n){S.warn("Received response for unknown request:",s,JSON.stringify(t));return}if(clearTimeout(n.timeout),this.pendingControlRequests.delete(s),t.subtype==="success")S.debug(`Control response success for request: ${s}: ${JSON.stringify(t.response)}`),n.resolve(t.response);else{let i=typeof t.error=="string"?t.error:t.error?.message??"Unknown error";S.error(`Control response error for request ${s}:`,i),n.reject(new Error(i))}}handleControlCancelRequest(e){let{request_id:t}=e;if(!t){S.warn("Received cancel request without request_id");return}let s=this.pendingControlRequests.get(t);s&&(S.debug(`Cancelling control request: ${t}`),s.abortController.abort(),clearTimeout(s.timeout),this.pendingControlRequests.delete(t),s.reject(new k("Request cancelled")))}async sendControlRequest(e,t={}){if(this.closed)return Promise.reject(new Error("Query is closed"));e!=="initialize"&&await this.initialized;let s=Xe(),n={type:"control_request",request_id:s,request:{subtype:e,...t}},i=new Promise((o,a)=>{let u=new AbortController,d=this.options.timeout?.controlRequest??jt,y=setTimeout(()=>{this.pendingControlRequests.delete(s),a(new Error(`Control request timeout: ${e}`))},d);this.pendingControlRequests.set(s,{resolve:o,reject:a,timeout:y,abortController:u})});try{this.transport.write(ue(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,t,s){let n={type:"control_response",response:t?{subtype:"success",request_id:e,response:s}:{subtype:"error",request_id:e,error:s}};try{this.transport.write(ue(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){this.closed=!0;for(let e of this.pendingControlRequests.values())e.abortController.abort(),clearTimeout(e.timeout),e.reject(new Error("Query is closed"));this.pendingControlRequests.clear();for(let e of this.pendingMcpResponses.values())e.reject(new Error("Query is closed"));this.pendingMcpResponses.clear(),await this.transport.close(),this.inputStream.hasError===void 0&&(this.abortController.signal.aborted?this.inputStream.error(new k("Query aborted")):this.inputStream.done());for(let e of this.sdkMcpTransports.values())try{await e.close()}catch(t){S.error("Error closing MCP transport:",t)}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 t of e){if(this.abortController.signal.aborted)break;this.transport.write(ue(t))}if(this.firstResultReceivedPromise){let t=this.options.timeout?.streamClose??Lt,s,n=new Promise(i=>{s=setTimeout(()=>{S.info("streamCloseTimeout resolved"),i()},t)});await Promise.race([this.firstResultReceivedPromise,n]),s&&clearTimeout(s)}this.endInput()}catch(t){if(this.abortController.signal.aborted){S.info("Aborted during input streaming"),this.inputStream.error(new k("Query aborted during input streaming"));return}throw t}}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={};mt(l,{BRAND:()=>ar,DIRTY:()=>J,EMPTY_PATH:()=>qt,INVALID:()=>m,NEVER:()=>Br,OK:()=>T,ParseStatus:()=>w,Schema:()=>_,ZodAny:()=>B,ZodArray:()=>z,ZodBigInt:()=>H,ZodBoolean:()=>G,ZodBranded:()=>be,ZodCatch:()=>ce,ZodDate:()=>Y,ZodDefault:()=>ae,ZodDiscriminatedUnion:()=>Pe,ZodEffects:()=>O,ZodEnum:()=>ie,ZodError:()=>M,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>c,ZodLazy:()=>se,ZodLiteral:()=>ne,ZodMap:()=>ge,ZodNaN:()=>ve,ZodNativeEnum:()=>oe,ZodNever:()=>L,ZodNull:()=>ee,ZodNullable:()=>$,ZodNumber:()=>W,ZodObject:()=>E,ZodOptional:()=>P,ZodParsedType:()=>f,ZodPipeline:()=>Se,ZodPromise:()=>F,ZodReadonly:()=>le,ZodRecord:()=>Ae,ZodSchema:()=>_,ZodSet:()=>ye,ZodString:()=>V,ZodSymbol:()=>he,ZodTransformer:()=>O,ZodTuple:()=>D,ZodType:()=>_,ZodUndefined:()=>X,ZodUnion:()=>te,ZodUnknown:()=>Z,ZodVoid:()=>me,addIssueToContext:()=>p,any:()=>gr,array:()=>xr,bigint:()=>dr,boolean:()=>ut,coerce:()=>Vr,custom:()=>at,date:()=>pr,datetimeRegex:()=>it,defaultErrorMap:()=>q,discriminatedUnion:()=>wr,effect:()=>Nr,enum:()=>Or,function:()=>Ir,getErrorMap:()=>de,getParsedType:()=>N,instanceof:()=>lr,intersection:()=>Cr,isAborted:()=>Ee,isAsync:()=>pe,isDirty:()=>Ie,isValid:()=>K,late:()=>cr,lazy:()=>Pr,literal:()=>Ar,makeIssue:()=>xe,map:()=>Mr,nan:()=>ur,nativeEnum:()=>jr,never:()=>vr,null:()=>mr,nullable:()=>$r,number:()=>lt,object:()=>br,objectUtil:()=>ze,oboolean:()=>Kr,onumber:()=>zr,optional:()=>Dr,ostring:()=>Zr,pipeline:()=>Ur,preprocess:()=>qr,promise:()=>Lr,quotelessJson:()=>Nt,record:()=>Rr,set:()=>Er,setErrorMap:()=>$t,strictObject:()=>Sr,string:()=>ct,symbol:()=>fr,transformer:()=>Nr,tuple:()=>Tr,undefined:()=>hr,union:()=>kr,unknown:()=>yr,util:()=>x,void:()=>_r});var x;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},r.getValidEnumValues=n=>{let i=r.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),o={};for(let a of i)o[a]=n[a];return r.objectValues(o)},r.objectValues=n=>r.objectKeys(n).map(function(i){return n[i]}),r.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},r.find=(n,i)=>{for(let o of n)if(i(o))return o},r.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)}r.joinValues=s,r.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var ze;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ze||(ze={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?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(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r 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"]),Nt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),M=class r 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=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(t(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(t(o))):a[d]=a[d]||{_errors:[]},a=a[d],u++}}};return n(this),s}static assert(e){if(!(e instanceof r))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=t=>t.message){let t={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};M.create=r=>new M(r);var Dt=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},q=Dt;var et=q;function $t(r){et=r}function de(){return et}var xe=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,i=[...t,...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}},qt=[];function p(r,e){let t=de(),s=xe({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===q?void 0:q].filter(n=>!!n)});r.common.issues.push(s)}var w=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return m;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return m;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}}},m=Object.freeze({status:"aborted"}),J=r=>({status:"dirty",value:r}),T=r=>({status:"valid",value:r}),Ee=r=>r.status==="aborted",Ie=r=>r.status==="dirty",K=r=>r.status==="valid",pe=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var A=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,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}},tt=(r,e)=>{if(K(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new M(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||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}=r;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??t??a.defaultError}},description:n}}var _=class{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(pe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parseSync({data:e,path:s.path,parent:s});return tt(s,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return K(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>K(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(pe(n)?n:Promise.resolve(n));return tt(s,i)}refine(e,t){let s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;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(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new O({schema:this,typeName:g.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:t=>this["~validate"](t)}}optional(){return P.create(this,this._def)}nullable(){return $.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return F.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new O({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ae({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new be({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ce({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ut=/^c[^\s-]{8,}$/i,Zt=/^[0-9a-z]+$/,zt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kt=/^[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,Vt=/^[a-z0-9_-]{21}$/i,Bt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ft=/^[-+]?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)?)??$/,Qt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Jt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ke,Wt=/^(?:(?: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])$/,Ht=/^(?:(?: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])$/,Gt=/^(([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]))$/,Yt=/^(([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])$/,Xt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,er=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,st="((\\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])))",tr=new RegExp(`^${st}$`);function nt(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rr(r){return new RegExp(`^${nt(r)}$`)}function it(r){let e=`${st}T${nt(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function sr(r,e){return!!((e==="v4"||!e)&&Wt.test(r)||(e==="v6"||!e)&&Gt.test(r))}function nr(r,e){if(!Bt.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 ir(r,e){return!!((e==="v4"||!e)&&Ht.test(r)||(e==="v6"||!e)&&Yt.test(r))}var V=class r 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}),m}let s=new w,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")Qt.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")Ke||(Ke=new RegExp(Jt,"u")),Ke.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")Kt.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")Vt.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")Ut.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")Zt.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")zt.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"?it(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"?tr.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:c.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?rr(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"?Ft.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?sr(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"?nr(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"?ir(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"?Xt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:c.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?er.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,t,s){return this.refinement(n=>e.test(n),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};V.create=r=>new V({checks:[],typeName:g.ZodString,coerce:r?.coerce??!1,...v(r)});function or(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,i=Number.parseInt(r.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var W=class r 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}),m}let s,n=new w;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"?or(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,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.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,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};W.create=r=>new W({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...v(r)});var H=class r 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 w;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 t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};H.create=r=>new H({checks:[],typeName:g.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var G=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}),m}return T(e.data)}};G.create=r=>new G({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var Y=class r 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}),m}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:c.invalid_date}),m}let s=new w,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 r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Y.create=r=>new Y({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...v(r)});var he=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}),m}return T(e.data)}};he.create=r=>new he({typeName:g.ZodSymbol,...v(r)});var X=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}),m}return T(e.data)}};X.create=r=>new X({typeName:g.ZodUndefined,...v(r)});var ee=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}),m}return T(e.data)}};ee.create=r=>new ee({typeName:g.ZodNull,...v(r)});var B=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};B.create=r=>new B({typeName:g.ZodAny,...v(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};Z.create=r=>new Z({typeName:g.ZodUnknown,...v(r)});var L=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),m}};L.create=r=>new L({typeName:g.ZodNever,...v(r)});var me=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}),m}return T(e.data)}};me.create=r=>new me({typeName:g.ZodVoid,...v(r)});var z=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return p(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),m;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(o||a)&&(p(t,{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&&t.data.length<n.minLength.value&&(p(t,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(p(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>n.type._parseAsync(new A(t,o,t.path,a)))).then(o=>w.mergeArray(s,o));let i=[...t.data].map((o,a)=>n.type._parseSync(new A(t,o,t.path,a)));return w.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};z.create=(r,e)=>new z({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function fe(r){if(r instanceof E){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=P.create(fe(s))}return new E({...r._def,shape:()=>e})}else return r instanceof z?new z({...r._def,type:fe(r.element)}):r instanceof P?P.create(fe(r.unwrap())):r instanceof $?$.create(fe(r.unwrap())):r instanceof D?D.create(r.items.map(e=>fe(e))):r}var E=class r 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(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let d=this._getOrReturnCtx(e);return p(d,{code:c.invalid_type,expected:f.object,received:d.parsedType}),m}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 d in n.data)o.includes(d)||a.push(d);let u=[];for(let d of o){let y=i[d],C=n.data[d];u.push({key:{status:"valid",value:d},value:y._parse(new A(n,C,n.path,d)),alwaysSet:d in n.data})}if(this._def.catchall instanceof L){let d=this._def.unknownKeys;if(d==="passthrough")for(let y of a)u.push({key:{status:"valid",value:y},value:{status:"valid",value:n.data[y]}});else if(d==="strict")a.length>0&&(p(n,{code:c.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 y of a){let C=n.data[y];u.push({key:{status:"valid",value:y},value:d._parse(new A(n,C,n.path,y)),alwaysSet:y in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let d=[];for(let y of u){let C=await y.key,ke=await y.value;d.push({key:C,value:ke,alwaysSet:y.alwaysSet})}return d}).then(d=>w.mergeObjectSync(s,d)):w.mergeObjectSync(s,u)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of x.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of x.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return fe(this)}partial(e){let t={};for(let s of x.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of x.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof P;)i=i._def.innerType;t[s]=i}return new r({...this._def,shape:()=>t})}keyof(){return ot(x.objectKeys(this.shape))}};E.create=(r,e)=>new E({shape:()=>r,unknownKeys:"strip",catchall:L.create(),typeName:g.ZodObject,...v(e)});E.strictCreate=(r,e)=>new E({shape:()=>r,unknownKeys:"strict",catchall:L.create(),typeName:g.ZodObject,...v(e)});E.lazycreate=(r,e)=>new E({shape:r,unknownKeys:"strip",catchall:L.create(),typeName:g.ZodObject,...v(e)});var te=class extends _{_parse(e){let{ctx:t}=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 t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new M(a.ctx.common.issues));return p(t,{code:c.invalid_union,unionErrors:o}),m}if(t.common.async)return Promise.all(s.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let u of s){let d={...t,common:{...t.common,issues:[]},parent:null},y=u._parseSync({data:t.data,path:t.path,parent:d});if(y.status==="valid")return y;y.status==="dirty"&&!i&&(i={result:y,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new M(u));return p(t,{code:c.invalid_union,unionErrors:a}),m}}get options(){return this._def.options}};te.create=(r,e)=>new te({options:r,typeName:g.ZodUnion,...v(e)});var U=r=>r instanceof se?U(r.schema):r instanceof O?U(r.innerType()):r instanceof ne?[r.value]:r instanceof ie?r.options:r instanceof oe?x.objectValues(r.enum):r instanceof ae?U(r._def.innerType):r instanceof X?[void 0]:r instanceof ee?[null]:r instanceof P?[void 0,...U(r.unwrap())]:r instanceof $?[null,...U(r.unwrap())]:r instanceof be||r instanceof le?U(r.unwrap()):r instanceof ce?U(r._def.innerType):[],Pe=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),m;let s=this.discriminator,n=t.data[s],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let n=new Map;for(let i of t){let o=U(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 r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...v(s)})}};function Ve(r,e){let t=N(r),s=N(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&s===f.object){let n=x.objectKeys(e),i=x.objectKeys(r).filter(a=>n.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=Ve(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===f.array&&s===f.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=Ve(o,a);if(!u.valid)return{valid:!1};n.push(u.data)}return{valid:!0,data:n}}else return t===f.date&&s===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var re=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ee(i)||Ee(o))return m;let a=Ve(i.value,o.value);return a.valid?((Ie(i)||Ie(o))&&t.dirty(),{status:t.value,value:a.data}):(p(s,{code:c.invalid_intersection_types}),m)};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}))}};re.create=(r,e,t)=>new re({left:r,right:e,typeName:g.ZodIntersection,...v(t)});var D=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return p(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),m;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"}),m;!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"}),t.dirty());let i=[...s.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new A(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>w.mergeArray(t,o)):w.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};D.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new D({items:r,typeName:g.ZodTuple,rest:null,...v(e)})};var Ae=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return p(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),m;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?w.mergeObjectAsync(t,n):w.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...v(s)}):new r({keyType:V.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},ge=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return p(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),m;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,u],d)=>({key:n._parse(new A(s,a,s.path,[d,"key"])),value:i._parse(new A(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,y=await u.value;if(d.status==="aborted"||y.status==="aborted")return m;(d.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(d.value,y.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let d=u.key,y=u.value;if(d.status==="aborted"||y.status==="aborted")return m;(d.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(d.value,y.value)}return{status:t.value,value:a}}}};ge.create=(r,e,t)=>new ge({valueType:e,keyType:r,typeName:g.ZodMap,...v(t)});var ye=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return p(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),m;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}),t.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}),t.dirty());let i=this._def.valueType;function o(u){let d=new Set;for(let y of u){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),d.add(y.value)}return{status:t.value,value:d}}let a=[...s.data.values()].map((u,d)=>i._parse(new A(s,u,s.path,d)));return s.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ye.create=(r,e)=>new ye({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Oe=class r extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),m;function s(a,u){return xe({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),q].filter(d=>!!d),issueData:{code:c.invalid_arguments,argumentsError:u}})}function n(a,u){return xe({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),q].filter(d=>!!d),issueData:{code:c.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof F){let a=this;return T(async function(...u){let d=new M([]),y=await a._def.args.parseAsync(u,i).catch(Q=>{throw d.addIssue(s(u,Q)),d}),C=await Reflect.apply(o,this,y);return await a._def.returns._def.type.parseAsync(C,i).catch(Q=>{throw d.addIssue(n(C,Q)),d})})}else{let a=this;return T(function(...u){let d=a._def.args.safeParse(u,i);if(!d.success)throw new M([s(u,d.error)]);let y=Reflect.apply(o,this,d.data),C=a._def.returns.safeParse(y,i);if(!C.success)throw new M([n(y,C.error)]);return C.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:D.create(e).rest(Z.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||D.create([]).rest(Z.create()),returns:t||Z.create(),typeName:g.ZodFunction,...v(s)})}},se=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};se.create=(r,e)=>new se({getter:r,typeName:g.ZodLazy,...v(e)});var ne=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};ne.create=(r,e)=>new ne({value:r,typeName:g.ZodLiteral,...v(e)});function ot(r,e){return new ie({values:r,typeName:g.ZodEnum,...v(e)})}var ie=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return p(t,{expected:x.joinValues(s),received:t.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return p(t,{received:t.data,code:c.invalid_enum_value,options:s}),m}return T(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};ie.create=ot;var oe=class extends _{_parse(e){let t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=x.objectValues(t);return p(s,{expected:x.joinValues(n),received:s.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=x.objectValues(t);return p(s,{received:s.data,code:c.invalid_enum_value,options:n}),m}return T(e.data)}get enum(){return this._def.values}};oe.create=(r,e)=>new oe({values:r,typeName:g.ZodNativeEnum,...v(e)});var F=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),m;let s=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return T(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};F.create=(r,e)=>new F({type:r,typeName:g.ZodPromise,...v(e)});var O=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{p(s,o),o.fatal?t.abort():t.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(t.value==="aborted")return m;let u=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return u.status==="aborted"?m:u.status==="dirty"?J(u.value):t.value==="dirty"?J(u.value):u});{if(t.value==="aborted")return m;let a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?m:a.status==="dirty"?J(a.value):t.value==="dirty"?J(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"?m:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?m:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.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(!K(o))return m;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:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>K(o)?Promise.resolve(n.transform(o.value,i)).then(a=>({status:t.value,value:a})):m);x.assertNever(n)}};O.create=(r,e,t)=>new O({schema:r,typeName:g.ZodEffects,effect:e,...v(t)});O.createWithPreprocess=(r,e,t)=>new O({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...v(t)});var P=class extends _{_parse(e){return this._getType(e)===f.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};P.create=(r,e)=>new P({innerType:r,typeName:g.ZodOptional,...v(e)});var $=class extends _{_parse(e){return this._getType(e)===f.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$.create=(r,e)=>new $({innerType:r,typeName:g.ZodNullable,...v(e)});var ae=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ae.create=(r,e)=>new ae({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ce=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return pe(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new M(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new M(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ce.create=(r,e)=>new ce({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var ve=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}),m}return{status:"valid",value:e.data}}};ve.create=r=>new ve({typeName:g.ZodNaN,...v(r)});var ar=Symbol("zod_brand"),be=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},Se=class r extends _{_parse(e){let{status:t,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"?m:i.status==="dirty"?(t.dirty(),J(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"?m:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},le=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=n=>(K(n)&&(n.value=Object.freeze(n.value)),n);return pe(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};le.create=(r,e)=>new le({innerType:r,typeName:g.ZodReadonly,...v(e)});function rt(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function at(r,e={},t){return r?B.create().superRefine((s,n)=>{let i=r(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=rt(e,s),u=a.fatal??t??!0;n.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=rt(e,s),a=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:a})}}):B.create()}var cr={object:E.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var lr=(r,e={message:`Input not instance of ${r.name}`})=>at(t=>t instanceof r,e),ct=V.create,lt=W.create,ur=ve.create,dr=H.create,ut=G.create,pr=Y.create,fr=he.create,hr=X.create,mr=ee.create,gr=B.create,yr=Z.create,vr=L.create,_r=me.create,xr=z.create,br=E.create,Sr=E.strictCreate,kr=te.create,wr=Pe.create,Cr=re.create,Tr=D.create,Rr=Ae.create,Mr=ge.create,Er=ye.create,Ir=Oe.create,Pr=se.create,Ar=ne.create,Or=ie.create,jr=oe.create,Lr=F.create,Nr=O.create,Dr=P.create,$r=$.create,qr=O.createWithPreprocess,Ur=Se.create,Zr=()=>ct().optional(),zr=()=>lt().optional(),Kr=()=>ut().optional(),Vr={string:(r=>V.create({...r,coerce:!0})),number:(r=>W.create({...r,coerce:!0})),boolean:(r=>G.create({...r,coerce:!0})),bigint:(r=>H.create({...r,coerce:!0})),date:(r=>Y.create({...r,coerce:!0}))};var Br=m;var Fr=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(),Qr=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:Fr.optional(),authProviderType:l.enum(["dynamic_discovery","google_credentials","service_account_impersonation"]).optional(),targetAudience:l.string().optional(),targetServiceAccount:l.string().optional()}),Jr=l.object({type:l.literal("sdk"),name:l.string().min(1,"name must be a non-empty string"),instance:l.custom(r=>r&&typeof r=="object"&&"connect"in r&&typeof r.connect=="function",{message:"instance must be an MCP Server with connect method"})}),Wr=l.union([Qr,Jr]),Hr=l.object({model:l.string().optional(),temp:l.number().optional(),top_p:l.number().optional()}),Gr=l.object({max_time_minutes:l.number().optional(),max_turns:l.number().optional()}),ln=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:Hr.partial().optional(),runConfig:Gr.partial().optional(),color:l.string().optional(),isBuiltin:l.boolean().optional()}),Yr=l.object({canUseTool:l.number().positive().optional(),mcpRequest:l.number().positive().optional(),controlRequest:l.number().positive().optional(),streamClose:l.number().positive().optional()}),dt=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(r=>typeof r=="function",{message:"canUseTool must be a function"}).optional(),mcpServers:l.record(l.string(),Wr).optional(),abortController:l.instanceof(AbortController).optional(),debug:l.boolean().optional(),stderr:l.custom(r=>typeof r=="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","qwen-oauth"]).optional(),agents:l.array(l.custom(r=>r&&typeof r=="object"&&"name"in r&&"description"in r&&"systemPrompt"in r&&{message:"agents must be an array of SubagentConfig objects"})).optional(),includePartialMessages:l.boolean().optional(),timeout:Yr.optional()}).strict();var pt=R.createLogger("createQuery");function Xr({prompt:r,options:e={}}){let t=es(e),s=typeof r=="string",n=e.pathToQwenExecutable,i=e.abortController??new AbortController,o=new Ce({pathToQwenExecutable:n,spawnInfo:t,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}),a={...e,abortController:i},u=new _e(o,a,s);if(s){let d=r,y={type:"user",session_id:u.getSessionId(),message:{role:"user",content:d},parent_tool_use_id:null};(async()=>{try{await u.initialized,o.write(ue(y))}catch(C){pt.error("Error sending single-turn prompt:",C)}})()}else u.streamInput(r).catch(d=>{pt.error("Error streaming input:",d)});return u}function es(r){let e=dt.safeParse(r);if(!e.success){let t=e.error.errors.map(s=>`${s.path.join(".")}: ${s.message}`).join("; ");throw new Error(`Invalid QueryOptions: ${t}`)}try{return we(r.pathToQwenExecutable)}catch(t){let s=t instanceof Error?t.message:String(t);throw new Error(`Invalid pathToQwenExecutable: ${s}`)}}function ts(r,e,t,s){if(!r||typeof r!="string")throw new Error("Tool name must be a non-empty string");if(!e||typeof e!="string")throw new Error(`Tool '${r}' must have a description (string)`);if(!t||typeof t!="object")throw new Error(`Tool '${r}' must have an inputSchema (object)`);if(!s||typeof s!="function")throw new Error(`Tool '${r}' must have a handler (function)`);return{name:r,description:e,inputSchema:t,handler:s}}function ft(r){if(!r)throw new Error("Tool name cannot be empty");if(r.length>64)throw new Error(`Tool name '${r}' is too long (max 64 characters): ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error(`Tool name '${r}' is invalid. Must start with a letter and contain only letters, numbers, and underscores.`)}import{McpServer as rs}from"@modelcontextprotocol/sdk/server/mcp.js";function ss(r){let{name:e,version:t="1.0.0",tools:s}=r;if(!e||typeof e!="string")throw new Error("MCP server name must be a non-empty string");if(!t||typeof t!="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(ft(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 rs({name:e,version:t},{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}}export{k as AbortError,_e as Query,R as SdkLogger,ss as createSdkMcpServer,It as isAbortError,Ze as isControlCancel,qe as isControlRequest,Ue as isControlResponse,Le as isSDKAssistantMessage,$e as isSDKPartialAssistantMessage,De as isSDKResultMessage,Ne as isSDKSystemMessage,je as isSDKUserMessage,Te as isSdkMcpServerConfig,Xr as query,ts as tool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qwen-code/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "TypeScript SDK for programmatic access to qwen-code CLI",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",
@@ -20,6 +20,7 @@
20
20
  ],
21
21
  "scripts": {
22
22
  "build": "node scripts/build.js",
23
+ "bundle:cli": "node scripts/bundle-cli.js",
23
24
  "test": "vitest run",
24
25
  "test:ci": "vitest run",
25
26
  "test:watch": "vitest",
@@ -28,8 +29,8 @@
28
29
  "lint:fix": "eslint src test --fix",
29
30
  "typecheck": "tsc --noEmit",
30
31
  "clean": "rm -rf dist",
31
- "prepublishOnly": "npm run clean && npm run build",
32
- "prepack": "npm run build"
32
+ "prepublishOnly": "npm run clean && npm run build && npm run bundle:cli",
33
+ "prepack": "npm run build && npm run bundle:cli"
33
34
  },
34
35
  "keywords": [
35
36
  "qwen",
@@ -46,8 +47,7 @@
46
47
  },
47
48
  "dependencies": {
48
49
  "@modelcontextprotocol/sdk": "^1.25.1",
49
- "zod": "^3.25.0",
50
- "tiktoken": "^1.0.21"
50
+ "zod": "^3.25.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^20.14.0",