@papert-code/sdk-typescript 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +372 -0
- package/dist/LICENSE +203 -0
- package/dist/agent.d.ts +47 -0
- package/dist/cli/cli.js +77 -0
- package/dist/cli/sandbox-macos-permissive-closed.sb +32 -0
- package/dist/cli/sandbox-macos-permissive-open.sb +25 -0
- package/dist/cli/sandbox-macos-permissive-proxied.sb +37 -0
- package/dist/cli/sandbox-macos-restrictive-closed.sb +93 -0
- package/dist/cli/sandbox-macos-restrictive-open.sb +96 -0
- package/dist/cli/sandbox-macos-restrictive-proxied.sb +98 -0
- package/dist/cli/vendor/ripgrep/COPYING +3 -0
- package/dist/cli/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/dist/cli/vendor/ripgrep/arm64-linux/rg +0 -0
- package/dist/cli/vendor/ripgrep/x64-darwin/rg +0 -0
- package/dist/cli/vendor/ripgrep/x64-linux/rg +0 -0
- package/dist/cli/vendor/ripgrep/x64-win32/rg.exe +0 -0
- package/dist/client.d.ts +32 -0
- package/dist/index.cjs +20 -0
- package/dist/index.d.ts +839 -0
- package/dist/index.mjs +20 -0
- package/package.json +76 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";var qt=Object.create;var Ie=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty;var st=(r,e)=>{for(var t in e)Ie(r,t,{get:e[t],enumerable:!0})},nt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $t(e))!Zt.call(r,n)&&n!==t&&Ie(r,n,{get:()=>e[n],enumerable:!(s=Nt(e,n))||s.enumerable});return r};var Se=(r,e,t)=>(t=r!=null?qt(Ut(r)):{},nt(e||!r||!r.__esModule?Ie(t,"default",{value:r,enumerable:!0}):t,r)),zt=r=>nt(Ie({},"__esModule",{value:!0}),r);var xs={};st(xs,{AbortError:()=>w,HttpSseTransport:()=>He,PapertClient:()=>Ee,PapertClientSession:()=>Pe,Query:()=>fe,SdkLogger:()=>T,createClient:()=>Pt,createPapertAgent:()=>At,isAbortError:()=>dt,isControlCancel:()=>$e,isControlRequest:()=>qe,isControlResponse:()=>Ne,isSDKAssistantMessage:()=>Oe,isSDKPartialAssistantMessage:()=>De,isSDKResultMessage:()=>je,isSDKSystemMessage:()=>Le,isSDKUserMessage:()=>Ae,query:()=>Qe});module.exports=zt(xs);var it={debug:0,info:1,warn:2,error:3},T=class{static config={};static effectiveLevel="info";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_PAPERT_CODE_SDK_LEVEL;return e&&this.isValidLogLevel(e)?e:process.env.DEBUG_PAPERT_CODE_SDK?"debug":"info"}static isValidLogLevel(e){return["debug","info","warn","error"].includes(e)}static shouldLog(e){return it[e]>=it[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 c=n.map(l=>{if(typeof l=="string")return l;if(l instanceof Error)return l.message;try{return JSON.stringify(l)}catch{return String(l)}}).join(" ");a+=` ${c}`}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
|
+
`):process.stdout.write(i+`
|
|
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 he(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 Bt(r,e="JsonLines"){let t=T.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 Kt(r){return r!==null&&typeof r=="object"&&"type"in r&&typeof r.type=="string"}async function*ot(r,e="JsonLines"){let t=T.createLogger(e);for await(let s of r){if(s.trim().length===0)continue;let n=Bt(s,e);if(n!==null){if(!Kt(n)){t.warn("Invalid message structure (missing 'type' field), skipping:",s.substring(0,100));continue}yield n}}}var ht=require("node:child_process"),We=Se(require("node:path"),1),ft=Se(require("node:readline"),1);var F=Se(require("node:fs"),1),k=Se(require("node:path"),1),at=require("node:child_process"),ct=require("node:module"),Gt={};function Vt(){try{let e=(0,ct.createRequire)(Gt.url).resolve("@papert-code/sdk-typescript/package.json"),t=k.dirname(e),s=k.join(t,"dist","cli","cli.js");if(F.existsSync(s))return s}catch{}}function Qt(){let r=process.env.HOME||process.env.USERPROFILE||"",e=[process.env.PAPERT_CODE_CLI_PATH,Vt(),k.join(r,".volta","bin","papert"),k.join(r,".npm-global","bin","papert"),"/usr/local/bin/papert",k.join(r,".local","bin","papert"),k.join(r,"node_modules",".bin","papert"),k.join(r,".yarn","bin","papert")];for(let t of e)if(t&&F.existsSync(t))return k.resolve(t);throw new Error(`papert CLI not found. Please:
|
|
5
|
+
1. Install papert globally: npm install -g papert
|
|
6
|
+
2. Or provide explicit executable: query({ pathToPapertExecutable: "/path/to/papert" })
|
|
7
|
+
3. Or set environment variable: PAPERT_CODE_CLI_PATH="/path/to/papert"
|
|
8
|
+
4. Or ensure the SDK package was published with bundled CLI assets
|
|
9
|
+
|
|
10
|
+
For development/testing, you can also use:
|
|
11
|
+
\u2022 TypeScript source: query({ pathToPapertExecutable: "/path/to/index.ts" })
|
|
12
|
+
\u2022 Node.js bundle: query({ pathToPapertExecutable: "/path/to/cli.js" })
|
|
13
|
+
\u2022 Force specific runtime: query({ pathToPapertExecutable: "bun:/path/to/cli.js" })`)}function ut(r){try{let e=process.platform==="win32"?"where":"which";return(0,at.execSync)(`${e} ${r}`,{stdio:"ignore",timeout:5e3}),!0}catch{return!1}}function Ht(r){return r==="node"?!0:ut(r)}function Ft(r,e){let t=k.extname(r).toLowerCase();switch(e){case"node":case"bun":return[".js",".mjs",".cjs"].includes(t);case"tsx":return[".ts",".tsx"].includes(t);case"deno":return[".ts",".tsx",".js",".mjs"].includes(t);default:return!0}}function Fe(r){if(r===""||r&&r.trim()==="")throw new Error("Command name cannot be empty");if(!r)return{executablePath:Qt(),isExplicitRuntime:!1};let e=r.match(/^([^:]+):(.+)$/);if(e){let[,i,o]=e;if(!i||!o)throw new Error(`Invalid runtime specification: '${r}'`);let a=["node","bun","tsx","deno"];if(!a.includes(i))throw new Error(`Unsupported runtime '${i}'. Supported runtimes: ${a.join(", ")}`);if(!Ht(i))throw new Error(`Runtime '${i}' is not available on this system. Please install it first.`);let c=k.resolve(o);if(!F.existsSync(c))throw new Error(`Executable file not found at '${c}' for runtime '${i}'. Please check the file path and ensure the file exists.`);if(!Ft(c,i)){let l=k.extname(c);throw new Error(`File extension '${l}' is not compatible with runtime '${i}'. Expected extensions for ${i}: ${Wt(i).join(", ")}`)}return{runtime:i,executablePath:c,isExplicitRuntime:!0}}if(!r.includes("/")&&!r.includes("\\")){if(!r||r.trim()==="")throw new Error("Command name cannot be empty");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{executablePath:r,isExplicitRuntime:!1}}let s=k.resolve(r);if(!F.existsSync(s))throw new Error(`Executable file not found at '${s}'. Please check the file path and ensure the file exists. You can also:
|
|
14
|
+
\u2022 Set PAPERT_CODE_CLI_PATH environment variable
|
|
15
|
+
\u2022 Install papert globally: npm install -g papert
|
|
16
|
+
\u2022 For TypeScript files, ensure tsx is installed: npm install -g tsx
|
|
17
|
+
\u2022 Force specific runtime: bun:/path/to/cli.js or tsx:/path/to/index.ts`);if(!F.statSync(s).isFile())throw new Error(`Path '${s}' exists but is not a file. Please provide a path to an executable file.`);return{executablePath:s,isExplicitRuntime:!1}}function Wt(r){switch(r){case"node":case"bun":return[".js",".mjs",".cjs"];case"tsx":return[".ts",".tsx"];case"deno":return[".ts",".tsx",".js",".mjs"];default:return[]}}function Jt(r){let e=k.extname(r).toLowerCase();if([".js",".mjs",".cjs"].includes(e))return"node";if([".ts",".tsx"].includes(e)){if(ut("tsx"))return"tsx";throw new Error(`TypeScript file '${r}' requires 'tsx' runtime, but it's not available. Please install tsx: npm install -g tsx, or use explicit runtime: tsx:/path/to/file.ts`)}}function lt(r){let e=Fe(r),{runtime:t,executablePath:s,isExplicitRuntime:n}=e;if(n&&t)return{command:t==="node"?process.execPath:t,args:[s],type:t,originalInput:r||""};let i=Jt(s);return i?{command:i==="node"?process.execPath:i,args:[s],type:i,originalInput:r||""}:{command:s,args:[],type:"native",originalInput:r||""}}var w=class r extends Error{constructor(e="Operation aborted"){super(e),this.name="AbortError",Object.setPrototypeOf(this,r.prototype)}};function dt(r){return r instanceof w||typeof r=="object"&&r!==null&&"name"in r&&r.name==="AbortError"}var L=T.createLogger("ProcessTransport"),pt="PAPERT_CODE_SKILLS_PATHS";function Yt(r){let e=new RegExp(`[${We.delimiter},]`);return r.split(e).map(t=>t.trim()).filter(Boolean)}function Xt(r,e){let t=[];e&&t.push(...Yt(e)),r&&(Array.isArray(r)?t.push(...r):t.push(r));let s=t.map(n=>n.trim()).filter(Boolean);if(s.length!==0)return Array.from(new Set(s)).join(We.delimiter)}var Me=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,T.configure({debug:e.debug,stderr:e.stderr,logLevel:e.logLevel}),this.initialize()}initialize(){try{if(this.abortController.signal.aborted)throw new w("Transport start aborted");let e=this.buildCliArguments(),t=this.options.cwd??process.cwd(),s={...process.env,...this.options.env},n=Xt(this.options.skillsPath,s[pt]);n&&(s[pt]=n);let i=lt(this.options.pathToPapertExecutable),o=this.options.debug||this.options.stderr?"pipe":"ignore";L.debug(`Spawning CLI (${i.type}): ${i.command} ${[...i.args,...e].join(" ")}`),this.childProcess=(0,ht.spawn)(i.command,[...i.args,...e],{cwd:t,env:s,stdio:["pipe","pipe",o],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",c=>{L.debug(c.toString())});let a=()=>{this.childProcess&&!this.childProcess.killed&&this.childProcess.kill("SIGTERM")};this.processExitHandler=a,this.abortHandler=a,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.setupEventHandlers(),this.ready=!0,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 w("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 w("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"];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 w("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 w("Cannot write: operation aborted");if(!this.ready||!this.childStdin)throw new Error("Transport not ready for writing");if(this.closed)throw new Error("Cannot write to closed transport");if(this.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=ft.createInterface({input:this.childStdout,crlfDelay:1/0,terminal:!1});try{for await(let t of ot(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}};var Je=require("node:crypto");function Ae(r){return r&&typeof r=="object"&&r.type==="user"&&"message"in r}function Oe(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 Le(r){return r&&typeof r=="object"&&r.type==="system"&&"subtype"in r&&"uuid"in r&&"session_id"in r}function je(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 De(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 Ne(r){return r&&typeof r=="object"&&r.type==="control_response"&&"response"in r}function $e(r){return r&&typeof r=="object"&&r.type==="control_cancel_request"&&"request_id"in r}var Ue=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 er=3e4,tr=3e4,rr=3e4,sr=1e4,S=T.createLogger("Query"),fe=class{transport;options;sessionId;inputStream;sdkMessages;abortController;pendingControlRequests=new Map;sdkMcpTransports=new Map;initialized;closed=!1;messageRouterStarted=!1;firstResultReceivedPromise;firstResultReceivedResolve;isSingleTurn;constructor(e,t,s=!1){this.transport=e,this.options=t,this.sessionId=(0,Je.randomUUID)(),this.inputStream=new Ue,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 w("Query aborted by user")),this.close().catch(n=>{S.error("Error during abort cleanup:",n)})):this.abortController.signal.addEventListener("abort",()=>{this.inputStream.error(new w("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 initialize(){try{S.debug("Initializing Query");let e=Array.from(this.sdkMcpTransports.keys());await this.sendControlRequest("initialize",{hooks:null,sdkMcpServers:e.length>0?e:void 0,mcpServers:this.options.mcpServers,agents:this.options.agents}),S.info("Query initialized successfully")}catch(e){throw S.error("Initialization error:",e),e}}startMessageRouter(){this.messageRouterStarted||(this.messageRouterStarted=!0,(async()=>{try{for await(let e of this.transport.readMessages())if(await this.routeMessage(e),this.closed)break;this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done()}catch(e){this.inputStream.error(e instanceof Error?e:new Error(String(e)))}})())}async routeMessage(e){if(qe(e)){await this.handleControlRequest(e);return}if(Ne(e)){this.handleControlResponse(e);return}if($e(e)){this.handleControlCancelRequest(e);return}if(Le(e)){this.inputStream.enqueue(e);return}if(je(e)){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleTurn&&"endInput"in this.transport&&this.transport.endInput(),this.inputStream.enqueue(e);return}if(Oe(e)||Ae(e)||De(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=new Promise((a,c)=>{setTimeout(()=>c(new Error("Permission callback timeout")),er)}),o=await Promise.race([Promise.resolve(this.options.canUseTool(e,t,{signal:n,suggestions:s})),i]);return o.behavior==="allow"?{behavior:"allow",updatedInput:o.updatedInput??t}:{behavior:"deny",message:o.message??"Denied",...o.interrupt!==void 0?{interrupt:o.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){return new Promise((n,i)=>{let o=setTimeout(()=>{i(new Error("MCP request timeout"))},tr),a="id"in t?t.id:null,c=s.sendToQuery;s.sendToQuery=async l=>("id"in l&&l.id===a&&(clearTimeout(o),s.sendToQuery=c,n(l)),c(l)),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 w("Request cancelled")))}async sendControlRequest(e,t={}){let s=(0,Je.randomUUID)(),n={type:"control_request",request_id:s,request:{subtype:e,...t}},i=new Promise((o,a)=>{let c=new AbortController,l=setTimeout(()=>{this.pendingControlRequests.delete(s),a(new Error(`Control request timeout: ${e}`))},rr);this.pendingControlRequests.set(s,{resolve:o,reject:a,timeout:l,abortController:c})});return this.transport.write(he(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(he(n))}async close(){if(!this.closed){this.closed=!0;for(let e of this.pendingControlRequests.values())e.abortController.abort(),clearTimeout(e.timeout);this.pendingControlRequests.clear(),await this.transport.close(),this.inputStream.hasError===void 0&&(this.abortController.signal.aborted?this.inputStream.error(new w("Query aborted")):this.inputStream.done());for(let e of this.sdkMcpTransports.values())try{await e.close()}catch(t){S.error("Error closing MCP transport:",t)}this.sdkMcpTransports.clear(),S.info("Query 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(he(t))}!this.isSingleTurn&&this.sdkMcpTransports.size>0&&this.firstResultReceivedPromise&&await Promise.race([this.firstResultReceivedPromise,new Promise(t=>{setTimeout(()=>{t()},sr)})]),this.endInput()}catch(t){if(this.abortController.signal.aborted){S.info("Aborted during input streaming"),this.inputStream.error(new w("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(){if(this.closed)throw new Error("Query is closed");await this.sendControlRequest("interrupt")}async setPermissionMode(e){if(this.closed)throw new Error("Query is closed");await this.sendControlRequest("set_permission_mode",{mode:e})}async setModel(e){if(this.closed)throw new Error("Query is closed");await this.sendControlRequest("set_model",{model:e})}async supportedCommands(){if(this.closed)throw new Error("Query is closed");return this.sendControlRequest("supported_commands")}async mcpServerStatus(){if(this.closed)throw new Error("Query is closed");return this.sendControlRequest("mcp_server_status")}getSessionId(){return this.sessionId}isClosed(){return this.closed}};var f={};st(f,{BRAND:()=>Pr,DIRTY:()=>W,EMPTY_PATH:()=>ar,INVALID:()=>m,NEVER:()=>hs,OK:()=>R,ParseStatus:()=>C,Schema:()=>v,ZodAny:()=>V,ZodArray:()=>z,ZodBigInt:()=>G,ZodBoolean:()=>Y,ZodBranded:()=>Re,ZodCatch:()=>ue,ZodDate:()=>X,ZodDefault:()=>ce,ZodDiscriminatedUnion:()=>Be,ZodEffects:()=>A,ZodEnum:()=>oe,ZodError:()=>E,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Ve,ZodIntersection:()=>se,ZodIssueCode:()=>u,ZodLazy:()=>ne,ZodLiteral:()=>ie,ZodMap:()=>xe,ZodNaN:()=>we,ZodNativeEnum:()=>ae,ZodNever:()=>O,ZodNull:()=>te,ZodNullable:()=>q,ZodNumber:()=>J,ZodObject:()=>P,ZodOptional:()=>I,ZodParsedType:()=>p,ZodPipeline:()=>Te,ZodPromise:()=>Q,ZodReadonly:()=>le,ZodRecord:()=>Ke,ZodSchema:()=>v,ZodSet:()=>be,ZodString:()=>K,ZodSymbol:()=>_e,ZodTransformer:()=>A,ZodTuple:()=>D,ZodType:()=>v,ZodUndefined:()=>ee,ZodUnion:()=>re,ZodUnknown:()=>Z,ZodVoid:()=>ve,addIssueToContext:()=>d,any:()=>Nr,array:()=>zr,bigint:()=>Or,boolean:()=>Ct,coerce:()=>ps,custom:()=>wt,date:()=>Lr,datetimeRegex:()=>xt,defaultErrorMap:()=>$,discriminatedUnion:()=>Qr,effect:()=>ns,enum:()=>ts,function:()=>Yr,getErrorMap:()=>me,getParsedType:()=>j,instanceof:()=>Mr,intersection:()=>Hr,isAborted:()=>Ze,isAsync:()=>ge,isDirty:()=>ze,isValid:()=>B,late:()=>Ir,lazy:()=>Xr,literal:()=>es,makeIssue:()=>Ce,map:()=>Jr,nan:()=>Ar,nativeEnum:()=>rs,never:()=>Ur,null:()=>qr,nullable:()=>os,number:()=>St,object:()=>Br,objectUtil:()=>Ge,oboolean:()=>ds,onumber:()=>ls,optional:()=>is,ostring:()=>us,pipeline:()=>cs,preprocess:()=>as,promise:()=>ss,quotelessJson:()=>nr,record:()=>Wr,set:()=>Gr,setErrorMap:()=>or,strictObject:()=>Kr,string:()=>kt,symbol:()=>jr,transformer:()=>ns,tuple:()=>Fr,undefined:()=>Dr,union:()=>Vr,unknown:()=>$r,util:()=>x,void:()=>Zr});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 Ge;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ge||(Ge={}));var p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),j=r=>{switch(typeof r){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(r)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(r)?p.array:r===null?p.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?p.promise:typeof Map<"u"&&r instanceof Map?p.map:typeof Set<"u"&&r instanceof Set?p.set:typeof Date<"u"&&r instanceof Date?p.date:p.object;default:return p.unknown}};var u=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"]),nr=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),E=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,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};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()}};E.create=r=>new E(r);var ir=(r,e)=>{let t;switch(r.code){case u.invalid_type:r.received===p.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.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 u.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 u.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 u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},$=ir;var mt=$;function or(r){mt=r}function me(){return mt}var Ce=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="",c=s.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...n,path:i,message:a}},ar=[];function d(r,e){let t=me(),s=Ce({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===$?void 0:$].filter(n=>!!n)});r.common.issues.push(s)}var C=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"}),W=r=>({status:"dirty",value:r}),R=r=>({status:"valid",value:r}),Ze=r=>r.status==="aborted",ze=r=>r.status==="dirty",B=r=>r.status==="valid",ge=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 M=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}},gt=(r,e)=>{if(B(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 E(r.common.issues);return this._error=t,this._error}}};function _(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:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:n}}var v=class{get description(){return this._def.description}_getType(e){return j(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ge(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:j(e)},n=this._parseSync({data:e,path:s.path,parent:s});return gt(s,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return B(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=>B(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:j(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await(ge(n)?n:Promise.resolve(n));return gt(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:u.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!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 q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return Q.create(this,this._def)}or(e){return re.create([this,e],this._def)}and(e){return se.create(this,e,this._def)}transform(e){return new A({..._(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ce({..._(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new Re({typeName:g.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ue({..._(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 Te.create(this,e)}readonly(){return le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cr=/^c[^\s-]{8,}$/i,ur=/^[0-9a-z]+$/,lr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dr=/^[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,pr=/^[a-z0-9_-]{21}$/i,hr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fr=/^[-+]?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)?)??$/,mr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ye,yr=/^(?:(?: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])$/,_r=/^(?:(?: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])$/,vr=/^(([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]))$/,xr=/^(([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])$/,br=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_t="((\\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])))",kr=new RegExp(`^${_t}$`);function vt(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 Sr(r){return new RegExp(`^${vt(r)}$`)}function xt(r){let e=`${_t}T${vt(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 Cr(r,e){return!!((e==="v4"||!e)&&yr.test(r)||(e==="v6"||!e)&&vr.test(r))}function Rr(r,e){if(!hr.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 Tr(r,e){return!!((e==="v4"||!e)&&_r.test(r)||(e==="v6"||!e)&&xr.test(r))}var K=class r extends v{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:p.string,received:i.parsedType}),m}let s=new C,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:u.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),d(n,{code:u.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?d(n,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&d(n,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")mr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"email",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")Ye||(Ye=new RegExp(gr,"u")),Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"emoji",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")dr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"uuid",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")pr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"nanoid",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")cr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")ur.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid2",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")lr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"ulid",code:u.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),d(n,{validation:"url",code:u.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),d(n,{validation:"regex",code:u.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),d(n,{code:u.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),d(n,{code:u.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),d(n,{code:u.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?xt(i).test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:u.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?kr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:u.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Sr(i).test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:u.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?fr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"duration",code:u.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Cr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"ip",code:u.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Rr(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"jwt",code:u.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Tr(e.data,i.version)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cidr",code:u.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?br.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"base64",code:u.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?wr.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"base64url",code:u.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:u.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}};K.create=r=>new K({checks:[],typeName:g.ZodString,coerce:r?.coerce??!1,..._(r)});function Er(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 J=class r extends v{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)!==p.number){let i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:p.number,received:i.parsedType}),m}let s,n=new C;for(let i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.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),d(s,{code:u.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),d(s,{code:u.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Er(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.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)}};J.create=r=>new J({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,..._(r)});var G=class r extends v{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)!==p.bigint)return this._getInvalidInput(e);let s,n=new C;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.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),d(s,{code:u.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),d(s,{code:u.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 d(t,{code:u.invalid_type,expected:p.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}};G.create=r=>new G({checks:[],typeName:g.ZodBigInt,coerce:r?.coerce??!1,..._(r)});var Y=class extends v{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.boolean,received:s.parsedType}),m}return R(e.data)}};Y.create=r=>new Y({typeName:g.ZodBoolean,coerce:r?.coerce||!1,..._(r)});var X=class r extends v{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:p.date,received:i.parsedType}),m}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_date}),m}let s=new C,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:u.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),d(n,{code:u.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}};X.create=r=>new X({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,..._(r)});var _e=class extends v{_parse(e){if(this._getType(e)!==p.symbol){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.symbol,received:s.parsedType}),m}return R(e.data)}};_e.create=r=>new _e({typeName:g.ZodSymbol,..._(r)});var ee=class extends v{_parse(e){if(this._getType(e)!==p.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.undefined,received:s.parsedType}),m}return R(e.data)}};ee.create=r=>new ee({typeName:g.ZodUndefined,..._(r)});var te=class extends v{_parse(e){if(this._getType(e)!==p.null){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.null,received:s.parsedType}),m}return R(e.data)}};te.create=r=>new te({typeName:g.ZodNull,..._(r)});var V=class extends v{constructor(){super(...arguments),this._any=!0}_parse(e){return R(e.data)}};V.create=r=>new V({typeName:g.ZodAny,..._(r)});var Z=class extends v{constructor(){super(...arguments),this._unknown=!0}_parse(e){return R(e.data)}};Z.create=r=>new Z({typeName:g.ZodUnknown,..._(r)});var O=class extends v{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:u.invalid_type,expected:p.never,received:t.parsedType}),m}};O.create=r=>new O({typeName:g.ZodNever,..._(r)});var ve=class extends v{_parse(e){if(this._getType(e)!==p.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.void,received:s.parsedType}),m}return R(e.data)}};ve.create=r=>new ve({typeName:g.ZodVoid,..._(r)});var z=class r extends v{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==p.array)return d(t,{code:u.invalid_type,expected:p.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)&&(d(t,{code:o?u.too_big:u.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&&(d(t,{code:u.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&&(d(t,{code:u.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 M(t,o,t.path,a)))).then(o=>C.mergeArray(s,o));let i=[...t.data].map((o,a)=>n.type._parseSync(new M(t,o,t.path,a)));return C.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,..._(e)});function ye(r){if(r instanceof P){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=I.create(ye(s))}return new P({...r._def,shape:()=>e})}else return r instanceof z?new z({...r._def,type:ye(r.element)}):r instanceof I?I.create(ye(r.unwrap())):r instanceof q?q.create(ye(r.unwrap())):r instanceof D?D.create(r.items.map(e=>ye(e))):r}var P=class r extends v{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)!==p.object){let l=this._getOrReturnCtx(e);return d(l,{code:u.invalid_type,expected:p.object,received:l.parsedType}),m}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof O&&this._def.unknownKeys==="strip"))for(let l in n.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let y=i[l],b=n.data[l];c.push({key:{status:"valid",value:l},value:y._parse(new M(n,b,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof O){let l=this._def.unknownKeys;if(l==="passthrough")for(let y of a)c.push({key:{status:"valid",value:y},value:{status:"valid",value:n.data[y]}});else if(l==="strict")a.length>0&&(d(n,{code:u.unrecognized_keys,keys:a}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let y of a){let b=n.data[y];c.push({key:{status:"valid",value:y},value:l._parse(new M(n,b,n.path,y)),alwaysSet:y in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let y of c){let b=await y.key,N=await y.value;l.push({key:b,value:N,alwaysSet:y.alwaysSet})}return l}).then(l=>C.mergeObjectSync(s,l)):C.mergeObjectSync(s,c)}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 ye(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 bt(x.objectKeys(this.shape))}};P.create=(r,e)=>new P({shape:()=>r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,..._(e)});P.strictCreate=(r,e)=>new P({shape:()=>r,unknownKeys:"strict",catchall:O.create(),typeName:g.ZodObject,..._(e)});P.lazycreate=(r,e)=>new P({shape:r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,..._(e)});var re=class extends v{_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 E(a.ctx.common.issues));return d(t,{code:u.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 c of s){let l={...t,common:{...t.common,issues:[]},parent:null},y=c._parseSync({data:t.data,path:t.path,parent:l});if(y.status==="valid")return y;y.status==="dirty"&&!i&&(i={result:y,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new E(c));return d(t,{code:u.invalid_union,unionErrors:a}),m}}get options(){return this._def.options}};re.create=(r,e)=>new re({options:r,typeName:g.ZodUnion,..._(e)});var U=r=>r instanceof ne?U(r.schema):r instanceof A?U(r.innerType()):r instanceof ie?[r.value]:r instanceof oe?r.options:r instanceof ae?x.objectValues(r.enum):r instanceof ce?U(r._def.innerType):r instanceof ee?[void 0]:r instanceof te?[null]:r instanceof I?[void 0,...U(r.unwrap())]:r instanceof q?[null,...U(r.unwrap())]:r instanceof Re||r instanceof le?U(r.unwrap()):r instanceof ue?U(r._def.innerType):[],Be=class r extends v{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return d(t,{code:u.invalid_type,expected:p.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}):(d(t,{code:u.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,..._(s)})}};function Xe(r,e){let t=j(r),s=j(e);if(r===e)return{valid:!0,data:r};if(t===p.object&&s===p.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 c=Xe(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===p.array&&s===p.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],c=Xe(o,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return t===p.date&&s===p.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var se=class extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(Ze(i)||Ze(o))return m;let a=Xe(i.value,o.value);return a.valid?((ze(i)||ze(o))&&t.dirty(),{status:t.value,value:a.data}):(d(s,{code:u.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}))}};se.create=(r,e,t)=>new se({left:r,right:e,typeName:g.ZodIntersection,..._(t)});var D=class r extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==p.array)return d(s,{code:u.invalid_type,expected:p.array,received:s.parsedType}),m;if(s.data.length<this._def.items.length)return d(s,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...s.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new M(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>C.mergeArray(t,o)):C.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,..._(e)})};var Ke=class r extends v{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!==p.object)return d(s,{code:u.invalid_type,expected:p.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 M(s,a,s.path,a)),value:o._parse(new M(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?C.mergeObjectAsync(t,n):C.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof v?new r({keyType:e,valueType:t,typeName:g.ZodRecord,..._(s)}):new r({keyType:K.create(),valueType:e,typeName:g.ZodRecord,..._(t)})}},xe=class extends v{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!==p.map)return d(s,{code:u.invalid_type,expected:p.map,received:s.parsedType}),m;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,c],l)=>({key:n._parse(new M(s,a,s.path,[l,"key"])),value:i._parse(new M(s,c,s.path,[l,"value"]))}));if(s.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,y=await c.value;if(l.status==="aborted"||y.status==="aborted")return m;(l.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(l.value,y.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,y=c.value;if(l.status==="aborted"||y.status==="aborted")return m;(l.status==="dirty"||y.status==="dirty")&&t.dirty(),a.set(l.value,y.value)}return{status:t.value,value:a}}}};xe.create=(r,e,t)=>new xe({valueType:e,keyType:r,typeName:g.ZodMap,..._(t)});var be=class r extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==p.set)return d(s,{code:u.invalid_type,expected:p.set,received:s.parsedType}),m;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(d(s,{code:u.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&&(d(s,{code:u.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(c){let l=new Set;for(let y of c){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),l.add(y.value)}return{status:t.value,value:l}}let a=[...s.data.values()].map((c,l)=>i._parse(new M(s,c,s.path,l)));return s.common.async?Promise.all(a).then(c=>o(c)):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)}};be.create=(r,e)=>new be({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,..._(e)});var Ve=class r extends v{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.function)return d(t,{code:u.invalid_type,expected:p.function,received:t.parsedType}),m;function s(a,c){return Ce({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,me(),$].filter(l=>!!l),issueData:{code:u.invalid_arguments,argumentsError:c}})}function n(a,c){return Ce({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,me(),$].filter(l=>!!l),issueData:{code:u.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Q){let a=this;return R(async function(...c){let l=new E([]),y=await a._def.args.parseAsync(c,i).catch(ke=>{throw l.addIssue(s(c,ke)),l}),b=await Reflect.apply(o,this,y);return await a._def.returns._def.type.parseAsync(b,i).catch(ke=>{throw l.addIssue(n(b,ke)),l})})}else{let a=this;return R(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new E([s(c,l.error)]);let y=Reflect.apply(o,this,l.data),b=a._def.returns.safeParse(y,i);if(!b.success)throw new E([n(y,b.error)]);return b.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,..._(s)})}},ne=class extends v{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})}};ne.create=(r,e)=>new ne({getter:r,typeName:g.ZodLazy,..._(e)});var ie=class extends v{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};ie.create=(r,e)=>new ie({value:r,typeName:g.ZodLiteral,..._(e)});function bt(r,e){return new oe({values:r,typeName:g.ZodEnum,..._(e)})}var oe=class r extends v{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:x.joinValues(s),received:t.parsedType,code:u.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 d(t,{received:t.data,code:u.invalid_enum_value,options:s}),m}return R(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})}};oe.create=bt;var ae=class extends v{_parse(e){let t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==p.string&&s.parsedType!==p.number){let n=x.objectValues(t);return d(s,{expected:x.joinValues(n),received:s.parsedType,code:u.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 d(s,{received:s.data,code:u.invalid_enum_value,options:n}),m}return R(e.data)}get enum(){return this._def.values}};ae.create=(r,e)=>new ae({values:r,typeName:g.ZodNativeEnum,..._(e)});var Q=class extends v{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return d(t,{code:u.invalid_type,expected:p.promise,received:t.parsedType}),m;let s=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return R(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,..._(e)});var A=class extends v{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=>{d(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 c=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return c.status==="aborted"?m:c.status==="dirty"?W(c.value):t.value==="dirty"?W(c.value):c});{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"?W(a.value):t.value==="dirty"?W(a.value):a}}if(n.type==="refinement"){let o=a=>{let c=n.refinement(a,i);if(s.common.async)return Promise.resolve(c);if(c 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(!B(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=>B(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,..._(t)});A.createWithPreprocess=(r,e,t)=>new A({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,..._(t)});var I=class extends v{_parse(e){return this._getType(e)===p.undefined?R(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I.create=(r,e)=>new I({innerType:r,typeName:g.ZodOptional,..._(e)});var q=class extends v{_parse(e){return this._getType(e)===p.null?R(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q.create=(r,e)=>new q({innerType:r,typeName:g.ZodNullable,..._(e)});var ce=class extends v{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===p.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ce.create=(r,e)=>new ce({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var ue=class extends v{_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 ge(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new E(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ue.create=(r,e)=>new ue({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var we=class extends v{_parse(e){if(this._getType(e)!==p.nan){let s=this._getOrReturnCtx(e);return d(s,{code:u.invalid_type,expected:p.nan,received:s.parsedType}),m}return{status:"valid",value:e.data}}};we.create=r=>new we({typeName:g.ZodNaN,..._(r)});var Pr=Symbol("zod_brand"),Re=class extends v{_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}},Te=class r extends v{_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(),W(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 v{_parse(e){let t=this._def.innerType._parse(e),s=n=>(B(n)&&(n.value=Object.freeze(n.value)),n);return ge(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};le.create=(r,e)=>new le({innerType:r,typeName:g.ZodReadonly,..._(e)});function yt(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function wt(r,e={},t){return r?V.create().superRefine((s,n)=>{let i=r(s);if(i instanceof Promise)return i.then(o=>{if(!o){let a=yt(e,s),c=a.fatal??t??!0;n.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=yt(e,s),a=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:a})}}):V.create()}var Ir={object:P.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 Mr=(r,e={message:`Input not instance of ${r.name}`})=>wt(t=>t instanceof r,e),kt=K.create,St=J.create,Ar=we.create,Or=G.create,Ct=Y.create,Lr=X.create,jr=_e.create,Dr=ee.create,qr=te.create,Nr=V.create,$r=Z.create,Ur=O.create,Zr=ve.create,zr=z.create,Br=P.create,Kr=P.strictCreate,Vr=re.create,Qr=Be.create,Hr=se.create,Fr=D.create,Wr=Ke.create,Jr=xe.create,Gr=be.create,Yr=Ve.create,Xr=ne.create,es=ie.create,ts=oe.create,rs=ae.create,ss=Q.create,ns=A.create,is=I.create,os=q.create,as=A.createWithPreprocess,cs=Te.create,us=()=>kt().optional(),ls=()=>St().optional(),ds=()=>Ct().optional(),ps={string:(r=>K.create({...r,coerce:!0})),number:(r=>J.create({...r,coerce:!0})),boolean:(r=>Y.create({...r,coerce:!0})),bigint:(r=>G.create({...r,coerce:!0})),date:(r=>X.create({...r,coerce:!0}))};var hs=m;var fs=f.object({command:f.string().min(1,"Command must be a non-empty string"),args:f.array(f.string()).optional(),env:f.record(f.string(),f.string()).optional()}),gn=f.object({connect:f.custom(r=>typeof r=="function",{message:"connect must be a function"})}),ms=f.object({model:f.string().optional(),temp:f.number().optional(),top_p:f.number().optional()}),gs=f.object({max_time_minutes:f.number().optional(),max_turns:f.number().optional()}),yn=f.object({name:f.string().min(1,"Name must be a non-empty string"),description:f.string().min(1,"Description must be a non-empty string"),tools:f.array(f.string()).optional(),systemPrompt:f.string().min(1,"System prompt must be a non-empty string"),modelConfig:ms.partial().optional(),runConfig:gs.partial().optional(),color:f.string().optional(),isBuiltin:f.boolean().optional()}),Rt=f.object({cwd:f.string().optional(),model:f.string().optional(),pathToPapertExecutable:f.string().optional(),env:f.record(f.string(),f.string()).optional(),skillsPath:f.union([f.string().min(1),f.array(f.string().min(1))]).optional(),permissionMode:f.enum(["default","plan","auto-edit","yolo"]).optional(),canUseTool:f.custom(r=>typeof r=="function",{message:"canUseTool must be a function"}).optional(),mcpServers:f.record(f.string(),fs).optional(),abortController:f.instanceof(AbortController).optional(),debug:f.boolean().optional(),stderr:f.custom(r=>typeof r=="function",{message:"stderr must be a function"}).optional(),logLevel:f.enum(["debug","info","warn","error"]).optional(),maxSessionTurns:f.number().optional(),coreTools:f.array(f.string()).optional(),excludeTools:f.array(f.string()).optional(),allowedTools:f.array(f.string()).optional(),authType:f.enum(["openai","papert-oauth"]).optional(),agents:f.array(f.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:f.boolean().optional()}).strict();var Tt=T.createLogger("createQuery");function Qe({prompt:r,options:e={}}){let t=ys(e),s=typeof r=="string",n=e.pathToPapertExecutable??t.executablePath,i=e.abortController??new AbortController,o=new Me({pathToPapertExecutable:n,cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,env:e.env,skillsPath:e.skillsPath,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},c=new fe(o,a,s);if(s){let l=r,y={type:"user",session_id:c.getSessionId(),message:{role:"user",content:l},parent_tool_use_id:null};(async()=>{try{await c.initialized,o.write(he(y))}catch(b){Tt.error("Error sending single-turn prompt:",b)}})()}else c.streamInput(r).catch(l=>{Tt.error("Error streaming input:",l)});return c}function ys(r){let e=Rt.safeParse(r);if(!e.success){let s=e.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ");throw new Error(`Invalid QueryOptions: ${s}`)}let t;try{t=Fe(r.pathToPapertExecutable)}catch(s){let n=s instanceof Error?s.message:String(s);throw new Error(`Invalid pathToPapertExecutable: ${n}`)}return t}var Et=require("node:crypto");var Ee=class{options;sessions=new Map;constructor(e={}){this.options=e}createSession({sessionId:e=(0,Et.randomUUID)(),options:t={}}={}){let s=this.sessions.get(e);if(s)return s;let n=new Pe(e,this,t);return this.sessions.set(e,n),n}getSession(e){return this.sessions.get(e)}getDefaultOptions(){return this.options}unregisterSession(e){this.sessions.delete(e)}async close(){let e=Array.from(this.sessions.values());this.sessions.clear(),await Promise.allSettled(e.map(t=>t.close()))}},Pe=class{constructor(e,t,s={}){this.sessionId=e;this.client=t;this.options=s}activeQueries=new Set;closed=!1;getSessionId(){return this.sessionId}isClosed(){return this.closed}stream(e,t={}){if(this.closed)throw new Error("Session is closed");let s={...this.client.getDefaultOptions(),...this.options,...t},n=this.createPromptStream(e),i=Qe({prompt:n,options:s});return this.activeQueries.add(i),i}async send(e,t={}){let s=this.stream(e,t),n=[];try{for await(let i of s)n.push(i)}finally{await s.close(),this.activeQueries.delete(s)}return n}async close(){if(this.closed)return;this.closed=!0;let e=Array.from(this.activeQueries.values());this.activeQueries.clear(),await Promise.allSettled(e.map(t=>t.close())),this.client.unregisterSession(this.sessionId)}async*createPromptStream(e){yield{type:"user",session_id:this.sessionId,message:{role:"user",content:e},parent_tool_use_id:null}}};function Pt(r={}){return new Ee(r)}var It=require("node:child_process"),Mt=require("node:fs"),et=require("node:module"),de=Se(require("node:path"),1),Ot={};function _s(){try{let e=(0,et.createRequire)(Ot.url).resolve("@papert-code/sdk-typescript/package.json"),t=de.default.dirname(e),s=de.default.join(t,"dist","cli","cli.js");if((0,Mt.existsSync)(s))return s}catch{return}}function vs(r){if(r)return r;let e;try{let s=new URL(Ot.url);e=de.default.dirname(s.pathname)}catch{let s=new URL("file:///papert-sdk-agent-entrypoint.js");e=de.default.dirname(s.pathname)}let t=(0,et.createRequire)(e);try{let s=t.resolve("@papert-code/papert-code");return de.default.resolve(s)}catch{let s=_s();return s||de.default.resolve(e,"..","..","cli","dist","index.js")}}async function At(r={}){let e=vs(r.cliBinaryPath),{model:t,approvalMode:s,baseUrl:n,apiKey:i,cwd:o,extraArgs:a=[]}=r.cliArgs||{},c=[];t&&c.push("--model",t),s&&c.push("--approval-mode",s),n&&c.push("--openai-base-url",n);let l={};return i&&(l.OPENAI_API_KEY=i),{runPrompt:async(b,N)=>{let ke={...process.env,...l},Lt=[e,"--prompt",b,...c,...a||[],...N?.extraArgs||[]];return new Promise((jt,Dt)=>{let pe=(0,It.spawn)("node",Lt,{cwd:o||process.cwd(),env:ke,stdio:["ignore","pipe","pipe"]});N?.signal&&(N.signal.aborted?pe.kill("SIGTERM"):N.signal.addEventListener("abort",()=>{pe.kill("SIGTERM")}));let tt="",rt="";pe.stdout.on("data",H=>{tt+=H.toString()}),pe.stderr.on("data",H=>{rt+=H.toString()}),pe.on("error",H=>{Dt(H)}),pe.on("close",H=>{jt({stdout:tt,stderr:rt,exitCode:H})})})}}}var He=class{options;_exitError=null;_isReady=!1;session=null;pendingWrites=[];constructor(e){this.options=e,this._isReady=!0}get isReady(){return this._isReady}get exitError(){return this._exitError}async close(){if(this.session)try{await fetch(new URL(`/api/v1/sessions/${this.session.sessionId}/release`,this.options.baseUrl),{method:"POST",headers:{authorization:`Bearer ${this.session.token}`}})}catch{}finally{this.session=null}}async waitForExit(){}write(e){this.pendingWrites.push(e)}async*readMessages(){this.session||(this.session=await this.createSession());let e=this.pendingWrites.shift();if(!e)return;let t=await fetch(new URL("/",this.options.baseUrl),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.session.token}`,"x-papert-session-id":this.session.sessionId},body:e});if(!t.ok||!t.body)throw new Error(`Remote request failed: ${t.status} ${t.statusText}`);let s=t.body.getReader(),n=new TextDecoder,i="";for(;;){let{value:o,done:a}=await s.read();if(a)break;for(i+=n.decode(o,{stream:!0});;){let c=i.indexOf(`
|
|
18
|
+
|
|
19
|
+
`);if(c===-1)break;let l=i.slice(0,c);i=i.slice(c+2);let y=l.split(`
|
|
20
|
+
`).find(N=>N.startsWith("data: "));if(!y)continue;let b=y.slice(6);yield JSON.parse(b)}}}async createSession(){let e=await fetch(new URL("/api/v1/sessions",this.options.baseUrl),{method:"POST",headers:{authorization:`Bearer ${this.options.serverToken}`}});if(!e.ok)throw new Error(`Failed to create remote session: ${e.status} ${e.statusText}`);return await e.json()}};0&&(module.exports={AbortError,HttpSseTransport,PapertClient,PapertClientSession,Query,SdkLogger,createClient,createPapertAgent,isAbortError,isControlCancel,isControlRequest,isControlResponse,isSDKAssistantMessage,isSDKPartialAssistantMessage,isSDKResultMessage,isSDKSystemMessage,isSDKUserMessage,query});
|