@esri/solutions-components 5.1.0-next.54 → 5.1.0-next.55

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.
@@ -62,14 +62,14 @@ Please make sure you are calling this method within a traceable function and tha
62
62
  `)}var pj=class extends Error{constructor(e,t,n,r,s){super(bw(e,{name:t,index:n,operation:r,tree:s})),this.name=t,this.index=n,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=bw(e,{name:t,index:n,operation:r,tree:s})}},hj=Q({JsonPatchError:()=>ct,_areEquals:()=>tc,applyOperation:()=>ia,applyPatch:()=>Oi,applyReducer:()=>gj,deepClone:()=>fj,getValueByPointer:()=>Ml,validate:()=>Sx,validator:()=>Ll}),ct=pj,fj=er,ii={add:function(e,t,n){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=Ml(n,this.path);r&&(r=er(r));let s=ia(n,{op:"remove",path:this.from}).removed;return ia(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=Ml(n,this.from);return ia(n,{op:"add",path:this.path,value:er(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:tc(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},mj={add:function(e,t,n){return Cm(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:ii.move,copy:ii.copy,test:ii.test,_get:ii._get};function Ml(e,t){if(t=="")return e;var n={op:"_get",path:t};return ia(e,n),n.value}function ia(e,t,n=!1,r=!0,s=!0,a=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Ll(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Ml(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=tc(e,t.value),i.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,t,e);return i}}else{r||(e=er(e));let i=(t.path||"").split("/"),o=e,c=1,u=i.length,l,d,p;for(typeof n=="function"?p=n:p=Ll;;){if(d=i[c],d&&d.indexOf("~")!=-1&&(d=dj(d)),s&&(d=="__proto__"||d=="prototype"&&c>0&&i[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&l===void 0&&(o[d]===void 0?l=i.slice(0,c).join("/"):c==u-1&&(l=t.path),l!==void 0&&p(t,0,e,l)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(n&&!Cm(d))throw new ct("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,t,e);Cm(d)&&(d=~~d)}if(c>=u){if(n&&t.op==="add"&&d>o.length)throw new ct("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);let h=mj[t.op].call(t,o,d,e);if(h.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return h}}else if(c>=u){let h=ii[t.op].call(t,o,d,e);if(h.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return h}if(o=o[d],n&&c<u&&(!o||typeof o!="object"))throw new ct("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,t,e)}}}function Oi(e,t,n,r=!0,s=!0){if(n&&!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(e=er(e));let a=new Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=ia(e,t[i],n,!0,s,i),e=a[i].newDocument;return a.newDocument=e,a}function gj(e,t,n){let r=ia(e,t);if(r.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r.newDocument}function Ll(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))throw new ct("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(ii[e.op]){if(typeof e.path!="string")throw new ct("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new ct('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new ct("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Nm(e.value))throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var s=e.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new ct("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new ct("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var i=Sx([{op:"_get",path:e.from,value:void 0}],n);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new ct("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Sx(e,t,n){try{if(!Array.isArray(e))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Oi(er(t),er(e),n||!0);else{n=n||Ll;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(s){if(s instanceof ct)return s;throw s}}function tc(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),r=Array.isArray(t),s,a,i;if(n&&r){if(a=e.length,a!=t.length)return!1;for(s=a;s--!==0;)if(!tc(e[s],t[s]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(e);if(a=o.length,a!==Object.keys(t).length)return!1;for(s=a;s--!==0;)if(!t.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!tc(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Tx(e,t,n,r,s){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var a=$m(t),i=$m(e),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=e[u];if(Am(t,u)&&!(t[u]===void 0&&l!==void 0&&Array.isArray(t)===!1)){var d=t[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?Tx(l,d,n,r+"/"+Ua(u),s):l!==d&&(s&&n.push({op:"test",path:r+"/"+Ua(u),value:er(l)}),n.push({op:"replace",path:r+"/"+Ua(u),value:er(d)}))}else Array.isArray(e)===Array.isArray(t)?(s&&n.push({op:"test",path:r+"/"+Ua(u),value:er(l)}),n.push({op:"remove",path:r+"/"+Ua(u)}),o=!0):(s&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}))}if(!(!o&&a.length==i.length))for(var c=0;c<a.length;c++){var u=a[c];!Am(e,u)&&t[u]!==void 0&&n.push({op:"add",path:r+"/"+Ua(u),value:er(t[u])})}}}function Ap(e,t,n=!1){var r=[];return Tx(e,t,r,"",n),r}({...hj});var yj=Q({LogStreamCallbackHandler:()=>jm,RunLog:()=>Uy,RunLogPatch:()=>zr,isLogStreamHandler:()=>Ix}),zr=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=Oi({},t);return new Uy({ops:t,state:n[n.length-1].newDocument})}},Uy=class Pm extends zr{state;constructor(t){super(t),this.state=t.state}concat(t){let n=this.ops.concat(t.ops),r=Oi(this.state,t.ops);return new Pm({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=Oi({},t.ops);return new Pm({ops:t.ops,state:n[n.length-1].newDocument})}},Ix=e=>e.name==="log_stream_tracer";async function kw(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:n}=e;if(["retriever","llm","prompt"].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function xw(e,t){let{outputs:n}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function _j(e){return e!==void 0&&e.message!==void 0}var jm=class extends Xr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=gn.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(r=>this.includeTags?.includes(r))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(r=>!this.excludeTags?.includes(r))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let r=this.keyMapByRunId[e];r&&await this.writer.write(new zr({ops:[{op:"add",path:`/logs/${r}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new zr({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await kw(e,this._schemaFormat)),await this.writer.write(new zr({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await kw(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await xw(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new zr({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new zr({ops:[{op:"replace",path:"/final_output",value:await xw(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let s=e.inputs.messages!==void 0,a;s?_j(n?.chunk)?a=n?.chunk:a=new mn({id:`run-${e.id}`,content:t}):a=t;let i=new zr({ops:[{op:"add",path:`/logs/${r}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(i)}},vj=Q({ChatGenerationChunk:()=>Wr,GenerationChunk:()=>Si,RUN_KEY:()=>nc}),nc="__run",Si=class Ex{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ex({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Wr=class Ax extends Si{message;constructor(t){super(t),this.message=t.message}concat(t){return new Ax({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}},wj=Object.prototype.toString,bj=e=>wj.call(e)==="[object Error]",kj=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function xj(e){if(!(e&&bj(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:t,stack:n}=e;return t==="Load failed"?n===void 0||"__sentry_captured__"in e:t.startsWith("error sending request for url")?!0:kj.has(t)}function Oj(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ou(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var Sj=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Tj(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,s=Math.round(r*t.minTimeout*t.factor**(n-1));return s=Math.min(s,t.maxTimeout),s}function Ow(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Ij({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:s}){let a=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Sj)throw a.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(c),Ow(r,o)<=0)throw a;let u=await s.shouldConsumeRetry(c),l=Ow(r,o);if(l<=0||i<=0)throw a;if(a instanceof TypeError&&!xj(a)){if(u)throw a;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw a;if(!u)return s.signal?.throwIfAborted(),!1;let d=Tj(n,s),p=Math.min(d,l);return p>0&&await new Promise((h,f)=>{let m=()=>{clearTimeout(v),s.signal?.removeEventListener("abort",m),f(s.signal.reason)},v=setTimeout(()=>{s.signal?.removeEventListener("abort",m),h()},p);s.unref&&v.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function Rm(e,t={}){if(t={...t},Oj(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Ou("factor",t.factor,{min:0,allowInfinity:!1}),Ou("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Ou("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Ou("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,s=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let a=await e(n);return t.signal?.throwIfAborted(),a}catch(a){await Ij({error:a,attemptNumber:n,retriesConsumed:r,startTime:s,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ej=Q({AsyncCaller:()=>Jc}),Aj=[400,401,402,403,404,405,406,407,409],$j=e=>{if(typeof e!="object"||e===null)return;if("message"in e&&typeof e.message=="string"&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&typeof e.name=="string"&&e.name==="AbortError"||"code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t="response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0,n="status"in e&&typeof e.status=="number"?e.status:void 0,r=t??n;if(r&&Aj.includes(+r))throw e;if(("error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0)==="insufficient_quota"){let s=new Error("message"in e&&typeof e.message=="string"?e.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}},Jc=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??$j,this.queue=new("default"in qr?qr.default:qr)({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Rm(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>this.onFailedAttempt?.(n),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((s,a)=>{r=()=>{a(ec(e.signal))},e.signal?.addEventListener("abort",r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener("abort",r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},Cj=Q({isSerializableSchema:()=>ha,isStandardJsonSchema:()=>Dy,isStandardSchema:()=>$x});function $x(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function Dy(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function ha(e){return $x(e)&&Dy(e)}function no(e,t,n){function r(o,c){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),o._zod.traits.has(e))return;o._zod.traits.add(e),t(o,c);let u=i.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in o||(o[p]=u[p].bind(o))}}let s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:e});function i(o){var c;let u=n?.Parent?new a:this;r(u,o),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>n?.Parent&&o instanceof n.Parent?!0:o?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Fo=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Nj={};function $p(e){return Nj}function Pj(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function jj(e,t){return typeof t=="bigint"?t.toString():t}function Rj(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var Sw=Symbol("evaluating");function Mm(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Sw)return r===void 0&&(r=Sw,r=n()),r},set(s){Object.defineProperty(e,t,{value:s})},configurable:!0})}function Cx(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Nx(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}var Px="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Tw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mj(e){if(Tw(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Tw(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function tr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function Lj(e){return{}}function zj(e,t){if(!Mj(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=Nx(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Cx(this,"shape",s),s}});return tr(e,r)}function Uj(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Nx(t._zod.def,{get shape(){let a=t._zod.def.shape,i={...a};for(let o in a)i[o]=e?new e({type:"optional",innerType:a[o]}):a[o];return Cx(this,"shape",i),i},checks:[]});return tr(t,s)}function Su(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Tu(e){return typeof e=="string"?e:e?.message}function Cp(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let s=Tu(e.inst?._zod.def?.error?.(e))??Tu(t?.error?.(e))??Tu(n.customError?.(e))??Tu(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}var jx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jj,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Dj=no("$ZodError",jx),Np=no("$ZodError",jx,{Parent:Error});function Fj(e){let t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Bj(e){let t=[],n=[...e.issues].sort((r,s)=>(r.path??[]).length-(s.path??[]).length);for(let r of n)t.push(`\u2716 ${r.message}`),r.path?.length&&t.push(` \u2192 at ${Fj(r.path)}`);return t.join(`
63
63
  `)}var Zj=e=>(t,n,r,s)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Fo;if(i.issues.length){let o=new(s?.Err??e)(i.issues.map(c=>Cp(c,a,$p())));throw Px(o,s?.callee),o}return i.value},Fy=Zj(Np),qj=e=>async(t,n,r,s)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){let o=new(s?.Err??e)(i.issues.map(c=>Cp(c,a,$p())));throw Px(o,s?.callee),o}return i.value},Rx=qj(Np),Vj=e=>(t,n,r)=>{let s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Fo;return a.issues.length?{success:!1,error:new(e??Dj)(a.issues.map(i=>Cp(i,s,$p())))}:{success:!0,data:a.value}},Hj=Vj(Np),Wj=e=>async(t,n,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>Cp(i,s,$p())))}:{success:!0,data:a.value}},Jj=Wj(Np),Gj={major:4,minor:3,patch:6},By=no("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Gj;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let s of r)for(let a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(i,o,c)=>{let u=Su(i),l;for(let d of o){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,h=d._zod.check(i);if(h instanceof Promise&&c?.async===!1)throw new Fo;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,i.issues.length!==p&&(u||(u=Su(i,p)))});else{if(i.issues.length===p)continue;u||(u=Su(i,p))}}return l?l.then(()=>i):i},a=(i,o,c)=>{if(Su(i))return i.aborted=!0,i;let u=s(o,r,c);if(u instanceof Promise){if(c.async===!1)throw new Fo;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if(o.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return u instanceof Promise?u.then(l=>a(l,i,o)):a(u,i,o)}let c=e._zod.parse(i,o);if(c instanceof Promise){if(o.async===!1)throw new Fo;return c.then(u=>s(u,r,o))}return s(c,r,o)}}Mm(e,"~standard",()=>({validate:s=>{try{let a=Hj(e,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return Jj(e,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Kj=no("$ZodUnknown",(e,t)=>{By.init(e,t),e._zod.parse=n=>n}),Xj=no("$ZodNever",(e,t)=>{By.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Iw(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Mx=no("$ZodOptional",(e,t)=>{By.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Mm(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Mm(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Rj(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Iw(a,n.value)):Iw(s,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Ew,Yj=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qj(){return new Yj}(Ew=globalThis).__zod_globalRegistry??(Ew.__zod_globalRegistry=Qj());var hn=globalThis.__zod_globalRegistry;function eR(e){return new e({type:"unknown"})}function tR(e,t){return new e({type:"never",...Lj()})}function Lm(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??hn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function tt(e,t,n={path:[],schemaPath:[]}){var r;let s=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);let o=e._zod.toJSONSchema?.();if(o)i.schema=o;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let d=i.schema,p=t.processors[s.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);p(e,t,d,u)}let l=e._zod.parent;l&&(i.ref||(i.ref=l),tt(l,t,u),t.seen.get(l).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&Jt(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function zm(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of e.seen.entries()){let o=e.metadataRegistry.get(i[0])?.id;if(o){let c=r.get(o);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${o}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(o,i[0])}}let s=i=>{let o=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,d=e.external.uri??(h=>h);if(l)return{ref:d(l)};let p=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=p,{defId:p,ref:`${d("__shared")}#/${o}/${p}`}}if(i[1]===n)return{ref:"#"};let c=`#/${o}/`,u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:c+u}},a=i=>{if(i[1].schema.$ref)return;let o=i[1],{ref:c,defId:u}=s(i);o.def={...o.schema},u&&(o.defId=u);let l=o.schema;for(let d in l)delete l[d];l.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let o=i[1];if(o.cycle)throw new Error(`Cycle detected: #/${o.cycle?.join("/")}/<root>
64
64
 
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let o=i[1];if(t===i[0]){a(i);continue}if(e.external){let c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(o.cycle){a(i);continue}if(o.count>1&&e.reused==="ref"){a(i);continue}}}function Um(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=i=>{let o=e.seen.get(i);if(o.ref===null)return;let c=o.def??o.schema,u={...c},l=o.ref;if(o.ref=null,l){r(l);let p=e.seen.get(l),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,u),i._zod.parent===l)for(let f in c)f==="$ref"||f==="allOf"||f in u||delete c[f];if(h.$ref&&p.def)for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}let d=i._zod.parent;if(d&&d!==l){r(d);let p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}e.override({zodSchema:i,jsonSchema:c,path:o.path??[]})};for(let i of[...e.seen.entries()].reverse())r(i[0]);let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(i)}Object.assign(s,n.def??n.schema);let a=e.external?.defs??{};for(let i of e.seen.entries()){let o=i[1];o.def&&o.defId&&(a[o.defId]=o.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?s.$defs=a:s.definitions=a);try{let i=JSON.parse(JSON.stringify(s));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Aw(t,"input",e.processors),output:Aw(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function Jt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Jt(r.element,n);if(r.type==="set")return Jt(r.valueType,n);if(r.type==="lazy")return Jt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Jt(r.innerType,n);if(r.type==="intersection")return Jt(r.left,n)||Jt(r.right,n);if(r.type==="record"||r.type==="map")return Jt(r.keyType,n)||Jt(r.valueType,n);if(r.type==="pipe")return Jt(r.in,n)||Jt(r.out,n);if(r.type==="object"){for(let s in r.shape)if(Jt(r.shape[s],n))return!0;return!1}if(r.type==="union"){for(let s of r.options)if(Jt(s,n))return!0;return!1}if(r.type==="tuple"){for(let s of r.items)if(Jt(s,n))return!0;return!!(r.rest&&Jt(r.rest,n))}return!1}var Aw=(e,t,n={})=>r=>{let{libraryOptions:s,target:a}=r??{},i=Lm({...s??{},target:a,io:t,processors:n});return tt(e,i),zm(i,e),Um(i,e)},nR={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rR=(e,t,n,r)=>{let s=n;s.type="string";let{minimum:a,maximum:i,format:o,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof a=="number"&&(s.minLength=a),typeof i=="number"&&(s.maxLength=i),o&&(s.format=nR[o]??o,s.format===""&&delete s.format,o==="time"&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?s.pattern=l[0].source:l.length>1&&(s.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},sR=(e,t,n,r)=>{let s=n,{minimum:a,maximum:i,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof o=="string"&&o.includes("int")?s.type="integer":s.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(s.minimum=l,s.exclusiveMinimum=!0):s.exclusiveMinimum=l),typeof a=="number"&&(s.minimum=a,typeof l=="number"&&t.target!=="draft-04"&&(l>=a?delete s.minimum:delete s.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(s.maximum=u,s.exclusiveMaximum=!0):s.exclusiveMaximum=u),typeof i=="number"&&(s.maximum=i,typeof u=="number"&&t.target!=="draft-04"&&(u<=i?delete s.maximum:delete s.exclusiveMaximum)),typeof c=="number"&&(s.multipleOf=c)},aR=(e,t,n,r)=>{n.type="boolean"},iR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},oR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},cR=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},uR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},lR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},dR=(e,t,n,r)=>{n.not={}},pR=(e,t,n,r)=>{},hR=(e,t,n,r)=>{},fR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},mR=(e,t,n,r)=>{let s=e._zod.def,a=Pj(s.entries);a.every(i=>typeof i=="number")&&(n.type="number"),a.every(i=>typeof i=="string")&&(n.type="string"),n.enum=a},gR=(e,t,n,r)=>{let s=e._zod.def,a=[];for(let i of s.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(i))}else a.push(i);if(a.length!==0)if(a.length===1){let i=a[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else a.every(i=>typeof i=="number")&&(n.type="number"),a.every(i=>typeof i=="string")&&(n.type="string"),a.every(i=>typeof i=="boolean")&&(n.type="boolean"),a.every(i=>i===null)&&(n.type="null"),n.enum=a},yR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},_R=(e,t,n,r)=>{let s=n,a=e._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=a.source},vR=(e,t,n,r)=>{let s=n,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:o,mime:c}=e._zod.bag;i!==void 0&&(a.minLength=i),o!==void 0&&(a.maxLength=o),c?c.length===1?(a.contentMediaType=c[0],Object.assign(s,a)):(Object.assign(s,a),s.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(s,a)},wR=(e,t,n,r)=>{n.type="boolean"},bR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},kR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},xR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},OR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},SR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},TR=(e,t,n,r)=>{let s=n,a=e._zod.def,{minimum:i,maximum:o}=e._zod.bag;typeof i=="number"&&(s.minItems=i),typeof o=="number"&&(s.maxItems=o),s.type="array",s.items=tt(a.element,t,{...r,path:[...r.path,"items"]})},IR=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="object",s.properties={};let i=a.shape;for(let u in i)s.properties[u]=tt(i[u],t,{...r,path:[...r.path,"properties",u]});let o=new Set(Object.keys(i)),c=new Set([...o].filter(u=>{let l=a.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(s.required=Array.from(c)),a.catchall?._zod.def.type==="never"?s.additionalProperties=!1:a.catchall?a.catchall&&(s.additionalProperties=tt(a.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},ER=(e,t,n,r)=>{let s=e._zod.def,a=s.inclusive===!1,i=s.options.map((o,c)=>tt(o,t,{...r,path:[...r.path,a?"oneOf":"anyOf",c]}));a?n.oneOf=i:n.anyOf=i},AR=(e,t,n,r)=>{let s=e._zod.def,a=tt(s.left,t,{...r,path:[...r.path,"allOf",0]}),i=tt(s.right,t,{...r,path:[...r.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(a)?a.allOf:[a],...o(i)?i.allOf:[i]];n.allOf=c},$R=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",o=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,h)=>tt(p,t,{...r,path:[...r.path,i,h]})),u=a.rest?tt(a.rest,t,{...r,path:[...r.path,o,...t.target==="openapi-3.0"?[a.items.length]:[]]}):null;t.target==="draft-2020-12"?(s.prefixItems=c,u&&(s.items=u)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),s.minItems=c.length,u||(s.maxItems=c.length)):(s.items=c,u&&(s.additionalItems=u));let{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(s.minItems=l),typeof d=="number"&&(s.maxItems=d)},CR=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="object";let i=a.keyType,o=i._zod.bag?.patterns;if(a.mode==="loose"&&o&&o.size>0){let u=tt(a.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(let l of o)s.patternProperties[l.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(s.propertyNames=tt(a.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=tt(a.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let c=i._zod.values;if(c){let u=[...c].filter(l=>typeof l=="string"||typeof l=="number");u.length>0&&(s.required=u)}},NR=(e,t,n,r)=>{let s=e._zod.def,a=tt(s.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},PR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},jR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},RR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},MR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},LR=(e,t,n,r)=>{let s=e._zod.def,a=t.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;tt(a,t,r);let i=t.seen.get(e);i.ref=a},zR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,n.readOnly=!0},UR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},DR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},FR=(e,t,n,r)=>{let s=e._zod.innerType;tt(s,t,r);let a=t.seen.get(e);a.ref=s},$w={string:rR,number:sR,boolean:aR,bigint:iR,symbol:oR,null:cR,undefined:uR,void:lR,never:dR,any:pR,unknown:hR,date:fR,enum:mR,literal:gR,nan:yR,template_literal:_R,file:vR,success:wR,custom:bR,function:kR,transform:xR,map:OR,set:SR,array:TR,object:IR,union:ER,intersection:AR,tuple:$R,record:CR,nullable:NR,nonoptional:PR,default:jR,prefault:RR,catch:MR,pipe:LR,readonly:zR,promise:UR,optional:DR,lazy:FR};function Cw(e,t){if("_idmap"in e){let r=e,s=Lm({...t,processors:$w}),a={};for(let c of r._idmap.entries()){let[u,l]=c;tt(l,s)}let i={},o={registry:r,uri:t?.uri,defs:a};s.external=o;for(let c of r._idmap.entries()){let[u,l]=c;zm(s,l),i[u]=Um(s,l)}if(Object.keys(a).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:a}}return{schemas:i}}let n=Lm({...t,processors:$w});return tt(e,n),zm(n,e),Um(n,e)}function nt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function mt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function BR(e){return nt(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),mt(e)}function En(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(nt(e)||mt(e))}function Lx(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function zx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function ZR(e){return!!(Lx(e)||zx(e))}async function Ux(e,t){if(nt(e))try{return{success:!0,data:await Rx(e,t)}}catch(n){return{success:!1,error:n}}if(mt(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Pp(e,t){if(nt(e))return await Rx(e,t);if(mt(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function qR(e,t){if(nt(e))try{return{success:!0,data:Fy(e,t)}}catch(n){return{success:!1,error:n}}if(mt(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function al(e,t){if(nt(e))return Fy(e,t);if(mt(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Ti(e){if(nt(e))return hn.get(e)?.description;if(mt(e)||"description"in e&&typeof e.description=="string")return e.description}function VR(e){if(!En(e))return!1;if(mt(e)){let t=e._def;if(t.typeName==="ZodObject"){let n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(nt(e)){let t=e._zod.def;if(t.type==="object"){let n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Zy(e){return En(e)?mt(e)?e._def.typeName==="ZodString":nt(e)?e._zod.def.type==="string":!1:!1}function qy(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function xr(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function jp(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Dx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function Fx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function Pn(e){return!!(qy(e)||xr(e))}function rc(e){if(mt(e))return e.shape;if(nt(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bx(e,t){if(mt(e))return e.extend(t);if(nt(e))return zj(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vy(e){if(mt(e))return e.partial();if(nt(e))return Uj(Mx,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zl(e,t=!1){if(mt(e))return e.strict();if(xr(e)){let n=e._zod.def.shape;if(t)for(let[a,i]of Object.entries(e._zod.def.shape)){if(xr(i))n[a]=zl(i,t);else if(jp(i)){let c=i._zod.def.element;xr(c)&&(c=zl(c,t)),n[a]=tr(i,{...i._zod.def,element:c})}else n[a]=i;let o=hn.get(i);o&&hn.add(n[a],o)}let r=tr(e,{...e._zod.def,shape:n,catchall:tR(Xj)}),s=hn.get(e);return s&&hn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Dm(e,t=!1){if(qy(e))return e.passthrough();if(xr(e)){let n=e._zod.def.shape;if(t)for(let[a,i]of Object.entries(e._zod.def.shape)){if(xr(i))n[a]=Dm(i,t);else if(jp(i)){let c=i._zod.def.element;xr(c)&&(c=Dm(c,t)),n[a]=tr(i,{...i._zod.def,element:c})}else n[a]=i;let o=hn.get(i);o&&hn.add(n[a],o)}let r=tr(e,{...e._zod.def,shape:n,catchall:eR(Kj)}),s=hn.get(e);return s&&hn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Zx(e){if(mt(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(nt(e))try{let t=Fy(e,void 0);return()=>t}catch{return}}function HR(e){return mt(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function WR(e){return nt(e)&&e._zod.def.type==="pipe"}function qs(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(mt(e))return HR(e)?qs(e._def.schema,t,n):e;if(nt(e)){let s=e;if(WR(e)&&(s=qs(e._zod.def.in,t,n)),t){if(xr(s)){let i={};for(let[o,c]of Object.entries(s._zod.def.shape))i[o]=qs(c,t,n);s=tr(s,{...s._zod.def,shape:i})}else if(jp(s)){let i=qs(s._zod.def.element,t,n);s=tr(s,{...s._zod.def,element:i})}else if(Dx(s)){let i=qs(s._zod.def.innerType,t,n);s=tr(s,{...s._zod.def,innerType:i})}else if(Fx(s)){let i=qs(s._zod.def.innerType,t,n);s=tr(s,{...s._zod.def,innerType:i})}}let a=hn.get(e);return a&&hn.add(s,a),n.set(e,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function qx(e,t=!1){return qs(e,t,new WeakMap)}function JR(e,t){if(mt(e)){let n=rc(e),r={};for(let[s,a]of Object.entries(n))t(s,a)?r[s]=a.optional():r[s]=a;return e.extend(r)}if(nt(e)){let n=rc(e),r={...e._zod.def.shape};for(let[i,o]of Object.entries(n))t(i,o)&&(r[i]=new Mx({type:"optional",innerType:o}));let s=tr(e,{...e._zod.def,shape:r}),a=hn.get(e);return a&&hn.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vx(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var GR=Symbol("Let zodToJsonSchema decide on which parser to use"),KR={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},XR=e=>({...KR,...e}),YR=e=>{let t=XR(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},Hx=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function yn(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Hx(t,e.currentPath):t.join("/")}}function Wx(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Ve(e,t,n,r,s){e[t]=n,Wx(e,t,r,s)}var Fe;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},e.getValidEnumValues=s=>{let a=e.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(a){return s[a]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},e.find=(s,a)=>{for(let i of s)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=r,e.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Fe||(Fe={}));var Nw;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Nw||(Nw={}));var re=Fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ss=e=>{switch(typeof e){case"undefined":return re.undefined;case"string":return re.string;case"number":return Number.isNaN(e)?re.nan:re.number;case"boolean":return re.boolean;case"function":return re.function;case"bigint":return re.bigint;case"symbol":return re.symbol;case"object":return Array.isArray(e)?re.array:e===null?re.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?re.promise:typeof Map<"u"&&e instanceof Map?re.map:typeof Set<"u"&&e instanceof Set?re.set:typeof Date<"u"&&e instanceof Date?re.date:re.object;default:return re.unknown}},D=Fe.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"]),fa=class Jx extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(t){if(!(t instanceof Jx))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Fe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n=Object.create(null),r=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];n[a]=n[a]||[],n[a].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fa.create=e=>new fa(e);var Fm=(e,t)=>{let n;switch(e.code){case D.invalid_type:e.received===re.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Fe.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:n=`Unrecognized key(s) in object: ${Fe.joinValues(e.keys,", ")}`;break;case D.invalid_union:n="Invalid input";break;case D.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Fe.joinValues(e.options)}`;break;case D.invalid_enum_value:n=`Invalid enum value. Expected ${Fe.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:n="Invalid function arguments";break;case D.invalid_return_type:n="Invalid function return type";break;case D.invalid_date:n="Invalid date";break;case D.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Fe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case D.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case D.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case D.custom:n="Invalid input";break;case D.invalid_intersection_types:n="Intersection results could not be merged";break;case D.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:n="Number must be finite";break;default:n=t.defaultError,Fe.assertNever(e)}return{message:n}},QR=Fm;function e2(){return QR}var t2=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}};function H(e,t){let n=e2(),r=t2({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Fm?void 0:Fm].filter(s=>!!s)});e.common.issues.push(r)}var or=class Gx{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return we;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let a=await s.key,i=await s.value;r.push({key:a,value:i})}return Gx.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return we;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:t.value,value:r}}},we=Object.freeze({status:"aborted"}),Bm=e=>({status:"dirty",value:e}),Un=e=>({status:"valid",value:e}),Pw=e=>e.status==="aborted",jw=e=>e.status==="dirty",Ii=e=>e.status==="valid",Ul=e=>typeof Promise<"u"&&e instanceof Promise,ae;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ae||(ae={}));var xs=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},Rw=(e,t)=>{if(Ii(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fa(e.common.issues);return this._error=n,this._error}}};function $e(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,i)=>{let{message:o}=e;return a.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:o??n??i.defaultError}},description:s}}var Le=class{get description(){return this._def.description}_getType(e){return ss(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new or,ctx:{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ul(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Rw(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Ii(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>Ii(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(Ul(r)?r:Promise.resolve(r));return Rw(n,s)}refine(e,t){let n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let a=e(r),i=()=>s.addIssue({code:D.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(o=>o?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new Ai({schema:this,typeName:F.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 ms.create(this,this._def)}nullable(){return $i.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ei.create(this)}promise(){return Bl.create(this,this._def)}or(e){return Dl.create([this,e],this._def)}and(e){return Fl.create(this,e,this._def)}transform(e){return new Ai({...$e(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Km({...$e(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new O2({typeName:F.ZodBranded,type:this,...$e(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Xm({...$e(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return S2.create(this,e)}readonly(){return Ym.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},n2=/^c[^\s-]{8,}$/i,r2=/^[0-9a-z]+$/,s2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a2=/^[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,i2=/^[a-z0-9_-]{21}$/i,o2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,c2=/^[-+]?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)?)??$/,u2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,l2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vf,d2=/^(?:(?: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])$/,p2=/^(?:(?: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])$/,h2=/^(([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]))$/,f2=/^(([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])$/,m2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kx="((\\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])))",y2=new RegExp(`^${Kx}$`);function Xx(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function _2(e){return new RegExp(`^${Xx(e)}$`)}function v2(e){let t=`${Kx}T${Xx(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function w2(e,t){return!!((t==="v4"||!t)&&d2.test(e)||(t==="v6"||!t)&&h2.test(e))}function b2(e,t){if(!o2.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function k2(e,t){return!!((t==="v4"||!t)&&p2.test(e)||(t==="v6"||!t)&&f2.test(e))}var Zm=class vo extends Le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==re.string){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.string,received:s.parsedType}),we}let n=new or,r;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(r=this._getOrReturnCtx(t,r),a?H(r,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&H(r,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")u2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"email",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")vf||(vf=new RegExp(l2,"u")),vf.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"emoji",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")a2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"uuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")i2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"nanoid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")n2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")r2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cuid2",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")s2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"ulid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),H(r,{validation:"url",code:D.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"regex",code:D.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?v2(s).test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?y2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?_2(s).test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?c2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"duration",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?w2(t.data,s.version)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"ip",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?b2(t.data,s.alg)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"jwt",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k2(t.data,s.version)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cidr",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?m2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"base64",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?g2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"base64url",code:D.invalid_string,message:s.message}),n.dirty()):Fe.assertNever(s);return{status:n.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:D.invalid_string,...ae.errToObj(r)})}_addCheck(t){return new vo({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ae.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ae.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ae.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ae.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ae.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ae.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ae.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ae.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ae.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ae.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ae.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ae.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ae.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ae.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ae.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ae.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ae.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...ae.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ae.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ae.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ae.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ae.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ae.errToObj(n)})}nonempty(t){return this.min(1,ae.errToObj(t))}trim(){return new vo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new vo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new vo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Zm.create=e=>new Zm({checks:[],typeName:F.ZodString,coerce:e?.coerce??!1,...$e(e)});function x2(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}var Mw=class qm extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==re.number){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.number,received:s.parsedType}),we}let n,r=new or;for(let s of this._def.checks)s.kind==="int"?Fe.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?x2(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_finite,message:s.message}),r.dirty()):Fe.assertNever(s);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ae.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ae.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ae.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ae.toString(n))}setLimit(t,n,r,s){return new qm({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ae.toString(s)}]})}_addCheck(t){return new qm({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ae.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ae.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ae.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ae.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ae.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ae.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ae.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ae.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ae.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Fe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Mw.create=e=>new Mw({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...$e(e)});var Lw=class Vm extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==re.bigint)return this._getInvalidInput(t);let n,r=new or;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Fe.assertNever(s);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:re.bigint,received:n.parsedType}),we}gte(t,n){return this.setLimit("min",t,!0,ae.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ae.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ae.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ae.toString(n))}setLimit(t,n,r,s){return new Vm({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ae.toString(s)}]})}_addCheck(t){return new Vm({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ae.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ae.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ae.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ae.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ae.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Lw.create=e=>new Lw({checks:[],typeName:F.ZodBigInt,coerce:e?.coerce??!1,...$e(e)});var zw=class extends Le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==re.boolean){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.boolean,received:t.parsedType}),we}return Un(e.data)}};zw.create=e=>new zw({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...$e(e)});var Uw=class Yx extends Le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==re.date){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.date,received:s.parsedType}),we}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_date}),we}let n=new or,r;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Fe.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Yx({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ae.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ae.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Uw.create=e=>new Uw({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...$e(e)});var Dw=class extends Le{_parse(e){if(this._getType(e)!==re.symbol){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.symbol,received:t.parsedType}),we}return Un(e.data)}};Dw.create=e=>new Dw({typeName:F.ZodSymbol,...$e(e)});var Fw=class extends Le{_parse(e){if(this._getType(e)!==re.undefined){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.undefined,received:t.parsedType}),we}return Un(e.data)}};Fw.create=e=>new Fw({typeName:F.ZodUndefined,...$e(e)});var Bw=class extends Le{_parse(e){if(this._getType(e)!==re.null){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.null,received:t.parsedType}),we}return Un(e.data)}};Bw.create=e=>new Bw({typeName:F.ZodNull,...$e(e)});var Hm=class extends Le{constructor(){super(...arguments),this._any=!0}_parse(e){return Un(e.data)}};Hm.create=e=>new Hm({typeName:F.ZodAny,...$e(e)});var Zw=class extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Un(e.data)}};Zw.create=e=>new Zw({typeName:F.ZodUnknown,...$e(e)});var Os=class extends Le{_parse(e){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.never,received:t.parsedType}),we}};Os.create=e=>new Os({typeName:F.ZodNever,...$e(e)});var qw=class extends Le{_parse(e){if(this._getType(e)!==re.undefined){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.void,received:t.parsedType}),we}return Un(e.data)}};qw.create=e=>new qw({typeName:F.ZodVoid,...$e(e)});var Ei=class il extends Le{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==re.array)return H(n,{code:D.invalid_type,expected:re.array,received:n.parsedType}),we;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(H(n,{code:i?D.too_big:D.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(H(n,{code:D.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(H(n,{code:D.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new xs(n,i,n.path,o)))).then(i=>or.mergeArray(r,i));let a=[...n.data].map((i,o)=>s.type._parseSync(new xs(n,i,n.path,o)));return or.mergeArray(r,a)}get element(){return this._def.type}min(t,n){return new il({...this._def,minLength:{value:t,message:ae.toString(n)}})}max(t,n){return new il({...this._def,maxLength:{value:t,message:ae.toString(n)}})}length(t,n){return new il({...this._def,exactLength:{value:t,message:ae.toString(n)}})}nonempty(t){return this.min(1,t)}};Ei.create=(e,t)=>new Ei({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...$e(t)});function Ja(e){if(e instanceof Jr){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ms.create(Ja(r))}return new Jr({...e._def,shape:()=>t})}else return e instanceof Ei?new Ei({...e._def,type:Ja(e.element)}):e instanceof ms?ms.create(Ja(e.unwrap())):e instanceof $i?$i.create(Ja(e.unwrap())):e instanceof sc?sc.create(e.items.map(t=>Ja(t))):e}var Jr=class Wn extends Le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Fe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==re.object){let c=this._getOrReturnCtx(t);return H(c,{code:D.invalid_type,expected:re.object,received:c.parsedType}),we}let{status:n,ctx:r}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Os&&this._def.unknownKeys==="strip"))for(let c in r.data)a.includes(c)||i.push(c);let o=[];for(let c of a){let u=s[c],l=r.data[c];o.push({key:{status:"valid",value:c},value:u._parse(new xs(r,l,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Os){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)o.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")i.length>0&&(H(r,{code:D.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=r.data[u];o.push({key:{status:"valid",value:u},value:c._parse(new xs(r,l,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of o){let l=await u.key,d=await u.value;c.push({key:l,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>or.mergeObjectSync(n,c)):or.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(t){return ae.errToObj,new Wn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ae.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new Wn({...this._def,unknownKeys:"strip"})}passthrough(){return new Wn({...this._def,unknownKeys:"passthrough"})}extend(t){return new Wn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Wn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Wn({...this._def,catchall:t})}pick(t){let n={};for(let r of Fe.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Wn({...this._def,shape:()=>n})}omit(t){let n={};for(let r of Fe.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Wn({...this._def,shape:()=>n})}deepPartial(){return Ja(this)}partial(t){let n={};for(let r of Fe.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new Wn({...this._def,shape:()=>n})}required(t){let n={};for(let r of Fe.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ms;)s=s._def.innerType;n[r]=s}return new Wn({...this._def,shape:()=>n})}keyof(){return eO(Fe.objectKeys(this.shape))}};Jr.create=(e,t)=>new Jr({shape:()=>e,unknownKeys:"strip",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});Jr.strictCreate=(e,t)=>new Jr({shape:()=>e,unknownKeys:"strict",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});Jr.lazycreate=(e,t)=>new Jr({shape:e,unknownKeys:"strip",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});var Dl=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new fa(i.ctx.common.issues));return H(t,{code:D.invalid_union,unionErrors:a}),we}if(t.common.async)return Promise.all(n.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let s,a=[];for(let o of n){let c={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(o=>new fa(o));return H(t,{code:D.invalid_union,unionErrors:i}),we}}get options(){return this._def.options}};Dl.create=(e,t)=>new Dl({options:e,typeName:F.ZodUnion,...$e(t)});function Wm(e,t){let n=ss(e),r=ss(t);if(e===t)return{valid:!0,data:e};if(n===re.object&&r===re.object){let s=Fe.objectKeys(t),a=Fe.objectKeys(e).filter(o=>s.indexOf(o)!==-1),i={...e,...t};for(let o of a){let c=Wm(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===re.array&&r===re.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let a=0;a<e.length;a++){let i=e[a],o=t[a],c=Wm(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===re.date&&r===re.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Fl=class extends Le{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(s,a)=>{if(Pw(s)||Pw(a))return we;let i=Wm(s.value,a.value);return i.valid?((jw(s)||jw(a))&&t.dirty(),{status:t.value,value:i.data}):(H(n,{code:D.invalid_intersection_types}),we)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>r(s,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Fl.create=(e,t,n)=>new Fl({left:e,right:t,typeName:F.ZodIntersection,...$e(n)});var sc=class Qx extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.array)return H(r,{code:D.invalid_type,expected:re.array,received:r.parsedType}),we;if(r.data.length<this._def.items.length)return H(r,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),we;!this._def.rest&&r.data.length>this._def.items.length&&(H(r,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,i)=>{let o=this._def.items[i]||this._def.rest;return o?o._parse(new xs(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>or.mergeArray(n,a)):or.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Qx({...this._def,rest:t})}};sc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sc({items:e,typeName:F.ZodTuple,rest:null,...$e(t)})};var Vw=class extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==re.map)return H(n,{code:D.invalid_type,expected:re.map,received:n.parsedType}),we;let r=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,o],c)=>({key:r._parse(new xs(n,i,n.path,[c,"key"])),value:s._parse(new xs(n,o,n.path,[c,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let o of a){let c=await o.key,u=await o.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),i.set(c.value,u.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let o of a){let c=o.key,u=o.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),i.set(c.value,u.value)}return{status:t.value,value:i}}}};Vw.create=(e,t,n)=>new Vw({valueType:t,keyType:e,typeName:F.ZodMap,...$e(n)});var Hw=class Jm extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.set)return H(r,{code:D.invalid_type,expected:re.set,received:r.parsedType}),we;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(H(r,{code:D.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(H(r,{code:D.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return we;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let o=[...r.data.values()].map((c,u)=>a._parse(new xs(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,n){return new Jm({...this._def,minSize:{value:t,message:ae.toString(n)}})}max(t,n){return new Jm({...this._def,maxSize:{value:t,message:ae.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Hw.create=(e,t)=>new Hw({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...$e(t)});var Ww=class extends Le{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})}};Ww.create=(e,t)=>new Ww({getter:e,typeName:F.ZodLazy,...$e(t)});var Jw=class extends Le{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return H(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jw.create=(e,t)=>new Jw({value:e,typeName:F.ZodLiteral,...$e(t)});function eO(e,t){return new Hy({values:e,typeName:F.ZodEnum,...$e(t)})}var Hy=class Gm extends Le{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return H(n,{expected:Fe.joinValues(r),received:n.parsedType,code:D.invalid_type}),we}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return H(n,{received:n.data,code:D.invalid_enum_value,options:r}),we}return Un(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Gm.create(t,{...this._def,...n})}exclude(t,n=this._def){return Gm.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Hy.create=eO;var Gw=class extends Le{_parse(e){let t=Fe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==re.string&&n.parsedType!==re.number){let r=Fe.objectValues(t);return H(n,{expected:Fe.joinValues(r),received:n.parsedType,code:D.invalid_type}),we}if(this._cache||(this._cache=new Set(Fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=Fe.objectValues(t);return H(n,{received:n.data,code:D.invalid_enum_value,options:r}),we}return Un(e.data)}get enum(){return this._def.values}};Gw.create=(e,t)=>new Gw({values:e,typeName:F.ZodNativeEnum,...$e(t)});var Bl=class extends Le{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==re.promise&&t.common.async===!1)return H(t,{code:D.invalid_type,expected:re.promise,received:t.parsedType}),we;let n=t.parsedType===re.promise?t.data:Promise.resolve(t.data);return Un(n.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Bl.create=(e,t)=>new Bl({type:e,typeName:F.ZodPromise,...$e(t)});var Ai=class extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:a=>{H(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){let a=r.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(t.value==="aborted")return we;let o=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return o.status==="aborted"?we:o.status==="dirty"||t.value==="dirty"?Bm(o.value):o});{if(t.value==="aborted")return we;let i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?we:i.status==="dirty"||t.value==="dirty"?Bm(i.value):i}}if(r.type==="refinement"){let a=i=>{let o=r.refinement(i,s);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?we:(i.status==="dirty"&&t.dirty(),a(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?we:(i.status==="dirty"&&t.dirty(),a(i.value).then(()=>({status:t.value,value:i.value}))))}if(r.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ii(a))return we;let i=r.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ii(a)?Promise.resolve(r.transform(a.value,s)).then(i=>({status:t.value,value:i})):we);Fe.assertNever(r)}};Ai.create=(e,t,n)=>new Ai({schema:e,typeName:F.ZodEffects,effect:t,...$e(n)});Ai.createWithPreprocess=(e,t,n)=>new Ai({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...$e(n)});var ms=class extends Le{_parse(e){return this._getType(e)===re.undefined?Un(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ms.create=(e,t)=>new ms({innerType:e,typeName:F.ZodOptional,...$e(t)});var $i=class extends Le{_parse(e){return this._getType(e)===re.null?Un(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$i.create=(e,t)=>new $i({innerType:e,typeName:F.ZodNullable,...$e(t)});var Km=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===re.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Km.create=(e,t)=>new Km({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$e(t)});var Xm=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ul(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new fa(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new fa(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Xm.create=(e,t)=>new Xm({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$e(t)});var Kw=class extends Le{_parse(e){if(this._getType(e)!==re.nan){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.nan,received:t.parsedType}),we}return{status:"valid",value:e.data}}};Kw.create=e=>new Kw({typeName:F.ZodNaN,...$e(e)});var O2=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},S2=class tO extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?we:s.status==="dirty"?(n.dirty(),Bm(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?we:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new tO({in:t,out:n,typeName:F.ZodPipeline})}},Ym=class extends Le{_parse(e){let t=this._def.innerType._parse(e),n=r=>(Ii(r)&&(r.value=Object.freeze(r.value)),r);return Ul(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}};Ym.create=(e,t)=>new Ym({innerType:e,typeName:F.ZodReadonly,...$e(t)});var F;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(F||(F={}));var Rp=Zm.create,Xw=Hm.create;Os.create;Ei.create;var Mp=Jr.create;Dl.create;Fl.create;sc.create;Hy.create;Bl.create;ms.create;$i.create;function T2(e,t){let n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==F.ZodAny&&(n.items=Ze(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ve(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ve(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ve(n,"minItems",e.exactLength.value,e.exactLength.message,t),Ve(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function I2(e,t){let n={type:"integer",format:"int64"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?Ve(n,"minimum",r.value,r.message,t):Ve(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ve(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?Ve(n,"maximum",r.value,r.message,t):Ve(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ve(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ve(n,"multipleOf",r.value,r.message,t);break}return n}function E2(){return{type:"boolean"}}function nO(e,t){return Ze(e.type._def,t)}var A2=(e,t)=>Ze(e.innerType._def,t);function rO(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>rO(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $2(e,t)}}var $2=(e,t)=>{let n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(let r of e.checks)switch(r.kind){case"min":Ve(n,"minimum",r.value,r.message,t);break;case"max":Ve(n,"maximum",r.value,r.message,t);break}return n};function C2(e,t){return{...Ze(e.innerType._def,t),default:e.defaultValue()}}function N2(e,t){return t.effectStrategy==="input"?Ze(e.schema._def,t):yn(t)}function P2(e){return{type:"string",enum:Array.from(e.values)}}var j2=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function R2(e,t){let n=[Ze(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ze(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(a=>{if(j2(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function M2(e,t){let n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}var wf,Zn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(wf===void 0&&(wf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wf),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function sO(e,t){let n={type:"string"};if(e.checks)for(let r of e.checks)switch(r.kind){case"min":Ve(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Ve(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":qn(n,"email",r.message,t);break;case"format:idn-email":qn(n,"idn-email",r.message,t);break;case"pattern:zod":Wt(n,Zn.email,r.message,t);break}break;case"url":qn(n,"uri",r.message,t);break;case"uuid":qn(n,"uuid",r.message,t);break;case"regex":Wt(n,r.regex,r.message,t);break;case"cuid":Wt(n,Zn.cuid,r.message,t);break;case"cuid2":Wt(n,Zn.cuid2,r.message,t);break;case"startsWith":Wt(n,RegExp(`^${bf(r.value,t)}`),r.message,t);break;case"endsWith":Wt(n,RegExp(`${bf(r.value,t)}$`),r.message,t);break;case"datetime":qn(n,"date-time",r.message,t);break;case"date":qn(n,"date",r.message,t);break;case"time":qn(n,"time",r.message,t);break;case"duration":qn(n,"duration",r.message,t);break;case"length":Ve(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),Ve(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":Wt(n,RegExp(bf(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&qn(n,"ipv4",r.message,t),r.version!=="v4"&&qn(n,"ipv6",r.message,t);break;case"base64url":Wt(n,Zn.base64url,r.message,t);break;case"jwt":Wt(n,Zn.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&Wt(n,Zn.ipv4Cidr,r.message,t),r.version!=="v4"&&Wt(n,Zn.ipv6Cidr,r.message,t);break;case"emoji":Wt(n,Zn.emoji(),r.message,t);break;case"ulid":Wt(n,Zn.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":qn(n,"binary",r.message,t);break;case"contentEncoding:base64":Ve(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":Wt(n,Zn.base64,r.message,t);break}break;case"nanoid":Wt(n,Zn.nanoid,r.message,t);break}return n}function bf(e,t){return t.patternStrategy==="escape"?z2(e):e}var L2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z2(e){let t="";for(let n=0;n<e.length;n++)L2.has(e[n])||(t+="\\"),t+=e[n];return t}function qn(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ve(e,"format",t,n,r)}function Wt(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Yw(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ve(e,"pattern",Yw(t,r),n,r)}function Yw(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source,s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let o=i[1];if(t===i[0]){a(i);continue}if(e.external){let c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){a(i);continue}}if(e.metadataRegistry.get(i[0])?.id){a(i);continue}if(o.cycle){a(i);continue}if(o.count>1&&e.reused==="ref"){a(i);continue}}}function Um(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=i=>{let o=e.seen.get(i);if(o.ref===null)return;let c=o.def??o.schema,u={...c},l=o.ref;if(o.ref=null,l){r(l);let p=e.seen.get(l),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,u),i._zod.parent===l)for(let f in c)f==="$ref"||f==="allOf"||f in u||delete c[f];if(h.$ref&&p.def)for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}let d=i._zod.parent;if(d&&d!==l){r(d);let p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}e.override({zodSchema:i,jsonSchema:c,path:o.path??[]})};for(let i of[...e.seen.entries()].reverse())r(i[0]);let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(i)}Object.assign(s,n.def??n.schema);let a=e.external?.defs??{};for(let i of e.seen.entries()){let o=i[1];o.def&&o.defId&&(a[o.defId]=o.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?s.$defs=a:s.definitions=a);try{let i=JSON.parse(JSON.stringify(s));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Aw(t,"input",e.processors),output:Aw(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function Jt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Jt(r.element,n);if(r.type==="set")return Jt(r.valueType,n);if(r.type==="lazy")return Jt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Jt(r.innerType,n);if(r.type==="intersection")return Jt(r.left,n)||Jt(r.right,n);if(r.type==="record"||r.type==="map")return Jt(r.keyType,n)||Jt(r.valueType,n);if(r.type==="pipe")return Jt(r.in,n)||Jt(r.out,n);if(r.type==="object"){for(let s in r.shape)if(Jt(r.shape[s],n))return!0;return!1}if(r.type==="union"){for(let s of r.options)if(Jt(s,n))return!0;return!1}if(r.type==="tuple"){for(let s of r.items)if(Jt(s,n))return!0;return!!(r.rest&&Jt(r.rest,n))}return!1}var Aw=(e,t,n={})=>r=>{let{libraryOptions:s,target:a}=r??{},i=Lm({...s??{},target:a,io:t,processors:n});return tt(e,i),zm(i,e),Um(i,e)},nR={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rR=(e,t,n,r)=>{let s=n;s.type="string";let{minimum:a,maximum:i,format:o,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof a=="number"&&(s.minLength=a),typeof i=="number"&&(s.maxLength=i),o&&(s.format=nR[o]??o,s.format===""&&delete s.format,o==="time"&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?s.pattern=l[0].source:l.length>1&&(s.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},sR=(e,t,n,r)=>{let s=n,{minimum:a,maximum:i,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof o=="string"&&o.includes("int")?s.type="integer":s.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(s.minimum=l,s.exclusiveMinimum=!0):s.exclusiveMinimum=l),typeof a=="number"&&(s.minimum=a,typeof l=="number"&&t.target!=="draft-04"&&(l>=a?delete s.minimum:delete s.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(s.maximum=u,s.exclusiveMaximum=!0):s.exclusiveMaximum=u),typeof i=="number"&&(s.maximum=i,typeof u=="number"&&t.target!=="draft-04"&&(u<=i?delete s.maximum:delete s.exclusiveMaximum)),typeof c=="number"&&(s.multipleOf=c)},aR=(e,t,n,r)=>{n.type="boolean"},iR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},oR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},cR=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},uR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},lR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},dR=(e,t,n,r)=>{n.not={}},pR=(e,t,n,r)=>{},hR=(e,t,n,r)=>{},fR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},mR=(e,t,n,r)=>{let s=e._zod.def,a=Pj(s.entries);a.every(i=>typeof i=="number")&&(n.type="number"),a.every(i=>typeof i=="string")&&(n.type="string"),n.enum=a},gR=(e,t,n,r)=>{let s=e._zod.def,a=[];for(let i of s.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(i))}else a.push(i);if(a.length!==0)if(a.length===1){let i=a[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else a.every(i=>typeof i=="number")&&(n.type="number"),a.every(i=>typeof i=="string")&&(n.type="string"),a.every(i=>typeof i=="boolean")&&(n.type="boolean"),a.every(i=>i===null)&&(n.type="null"),n.enum=a},yR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},_R=(e,t,n,r)=>{let s=n,a=e._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=a.source},vR=(e,t,n,r)=>{let s=n,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:o,mime:c}=e._zod.bag;i!==void 0&&(a.minLength=i),o!==void 0&&(a.maxLength=o),c?c.length===1?(a.contentMediaType=c[0],Object.assign(s,a)):(Object.assign(s,a),s.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(s,a)},wR=(e,t,n,r)=>{n.type="boolean"},bR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},kR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},xR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},OR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},SR=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},TR=(e,t,n,r)=>{let s=n,a=e._zod.def,{minimum:i,maximum:o}=e._zod.bag;typeof i=="number"&&(s.minItems=i),typeof o=="number"&&(s.maxItems=o),s.type="array",s.items=tt(a.element,t,{...r,path:[...r.path,"items"]})},IR=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="object",s.properties={};let i=a.shape;for(let u in i)s.properties[u]=tt(i[u],t,{...r,path:[...r.path,"properties",u]});let o=new Set(Object.keys(i)),c=new Set([...o].filter(u=>{let l=a.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(s.required=Array.from(c)),a.catchall?._zod.def.type==="never"?s.additionalProperties=!1:a.catchall?a.catchall&&(s.additionalProperties=tt(a.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},ER=(e,t,n,r)=>{let s=e._zod.def,a=s.inclusive===!1,i=s.options.map((o,c)=>tt(o,t,{...r,path:[...r.path,a?"oneOf":"anyOf",c]}));a?n.oneOf=i:n.anyOf=i},AR=(e,t,n,r)=>{let s=e._zod.def,a=tt(s.left,t,{...r,path:[...r.path,"allOf",0]}),i=tt(s.right,t,{...r,path:[...r.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(a)?a.allOf:[a],...o(i)?i.allOf:[i]];n.allOf=c},$R=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",o=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,h)=>tt(p,t,{...r,path:[...r.path,i,h]})),u=a.rest?tt(a.rest,t,{...r,path:[...r.path,o,...t.target==="openapi-3.0"?[a.items.length]:[]]}):null;t.target==="draft-2020-12"?(s.prefixItems=c,u&&(s.items=u)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),s.minItems=c.length,u||(s.maxItems=c.length)):(s.items=c,u&&(s.additionalItems=u));let{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(s.minItems=l),typeof d=="number"&&(s.maxItems=d)},CR=(e,t,n,r)=>{let s=n,a=e._zod.def;s.type="object";let i=a.keyType,o=i._zod.bag?.patterns;if(a.mode==="loose"&&o&&o.size>0){let u=tt(a.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(let l of o)s.patternProperties[l.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(s.propertyNames=tt(a.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=tt(a.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let c=i._zod.values;if(c){let u=[...c].filter(l=>typeof l=="string"||typeof l=="number");u.length>0&&(s.required=u)}},NR=(e,t,n,r)=>{let s=e._zod.def,a=tt(s.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},PR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},jR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},RR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},MR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},LR=(e,t,n,r)=>{let s=e._zod.def,a=t.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;tt(a,t,r);let i=t.seen.get(e);i.ref=a},zR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType,n.readOnly=!0},UR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},DR=(e,t,n,r)=>{let s=e._zod.def;tt(s.innerType,t,r);let a=t.seen.get(e);a.ref=s.innerType},FR=(e,t,n,r)=>{let s=e._zod.innerType;tt(s,t,r);let a=t.seen.get(e);a.ref=s},$w={string:rR,number:sR,boolean:aR,bigint:iR,symbol:oR,null:cR,undefined:uR,void:lR,never:dR,any:pR,unknown:hR,date:fR,enum:mR,literal:gR,nan:yR,template_literal:_R,file:vR,success:wR,custom:bR,function:kR,transform:xR,map:OR,set:SR,array:TR,object:IR,union:ER,intersection:AR,tuple:$R,record:CR,nullable:NR,nonoptional:PR,default:jR,prefault:RR,catch:MR,pipe:LR,readonly:zR,promise:UR,optional:DR,lazy:FR};function Cw(e,t){if("_idmap"in e){let r=e,s=Lm({...t,processors:$w}),a={};for(let c of r._idmap.entries()){let[u,l]=c;tt(l,s)}let i={},o={registry:r,uri:t?.uri,defs:a};s.external=o;for(let c of r._idmap.entries()){let[u,l]=c;zm(s,l),i[u]=Um(s,l)}if(Object.keys(a).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:a}}return{schemas:i}}let n=Lm({...t,processors:$w});return tt(e,n),zm(n,e),Um(n,e)}function nt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function gt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function BR(e){return nt(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),gt(e)}function En(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(nt(e)||gt(e))}function Lx(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function zx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function ZR(e){return!!(Lx(e)||zx(e))}async function Ux(e,t){if(nt(e))try{return{success:!0,data:await Rx(e,t)}}catch(n){return{success:!1,error:n}}if(gt(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Pp(e,t){if(nt(e))return await Rx(e,t);if(gt(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function qR(e,t){if(nt(e))try{return{success:!0,data:Fy(e,t)}}catch(n){return{success:!1,error:n}}if(gt(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function al(e,t){if(nt(e))return Fy(e,t);if(gt(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Ti(e){if(nt(e))return hn.get(e)?.description;if(gt(e)||"description"in e&&typeof e.description=="string")return e.description}function VR(e){if(!En(e))return!1;if(gt(e)){let t=e._def;if(t.typeName==="ZodObject"){let n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(nt(e)){let t=e._zod.def;if(t.type==="object"){let n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Zy(e){return En(e)?gt(e)?e._def.typeName==="ZodString":nt(e)?e._zod.def.type==="string":!1:!1}function qy(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function xr(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function jp(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Dx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function Fx(e){return nt(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function Pn(e){return!!(qy(e)||xr(e))}function rc(e){if(gt(e))return e.shape;if(nt(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bx(e,t){if(gt(e))return e.extend(t);if(nt(e))return zj(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vy(e){if(gt(e))return e.partial();if(nt(e))return Uj(Mx,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zl(e,t=!1){if(gt(e))return e.strict();if(xr(e)){let n=e._zod.def.shape;if(t)for(let[a,i]of Object.entries(e._zod.def.shape)){if(xr(i))n[a]=zl(i,t);else if(jp(i)){let c=i._zod.def.element;xr(c)&&(c=zl(c,t)),n[a]=tr(i,{...i._zod.def,element:c})}else n[a]=i;let o=hn.get(i);o&&hn.add(n[a],o)}let r=tr(e,{...e._zod.def,shape:n,catchall:tR(Xj)}),s=hn.get(e);return s&&hn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Dm(e,t=!1){if(qy(e))return e.passthrough();if(xr(e)){let n=e._zod.def.shape;if(t)for(let[a,i]of Object.entries(e._zod.def.shape)){if(xr(i))n[a]=Dm(i,t);else if(jp(i)){let c=i._zod.def.element;xr(c)&&(c=Dm(c,t)),n[a]=tr(i,{...i._zod.def,element:c})}else n[a]=i;let o=hn.get(i);o&&hn.add(n[a],o)}let r=tr(e,{...e._zod.def,shape:n,catchall:eR(Kj)}),s=hn.get(e);return s&&hn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Zx(e){if(gt(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(nt(e))try{let t=Fy(e,void 0);return()=>t}catch{return}}function HR(e){return gt(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function WR(e){return nt(e)&&e._zod.def.type==="pipe"}function qs(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(gt(e))return HR(e)?qs(e._def.schema,t,n):e;if(nt(e)){let s=e;if(WR(e)&&(s=qs(e._zod.def.in,t,n)),t){if(xr(s)){let i={};for(let[o,c]of Object.entries(s._zod.def.shape))i[o]=qs(c,t,n);s=tr(s,{...s._zod.def,shape:i})}else if(jp(s)){let i=qs(s._zod.def.element,t,n);s=tr(s,{...s._zod.def,element:i})}else if(Dx(s)){let i=qs(s._zod.def.innerType,t,n);s=tr(s,{...s._zod.def,innerType:i})}else if(Fx(s)){let i=qs(s._zod.def.innerType,t,n);s=tr(s,{...s._zod.def,innerType:i})}}let a=hn.get(e);return a&&hn.add(s,a),n.set(e,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function qx(e,t=!1){return qs(e,t,new WeakMap)}function JR(e,t){if(gt(e)){let n=rc(e),r={};for(let[s,a]of Object.entries(n))t(s,a)?r[s]=a.optional():r[s]=a;return e.extend(r)}if(nt(e)){let n=rc(e),r={...e._zod.def.shape};for(let[i,o]of Object.entries(n))t(i,o)&&(r[i]=new Mx({type:"optional",innerType:o}));let s=tr(e,{...e._zod.def,shape:r}),a=hn.get(e);return a&&hn.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vx(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var GR=Symbol("Let zodToJsonSchema decide on which parser to use"),KR={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},XR=e=>({...KR,...e}),YR=e=>{let t=XR(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},Hx=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function yn(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Hx(t,e.currentPath):t.join("/")}}function Wx(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Ve(e,t,n,r,s){e[t]=n,Wx(e,t,r,s)}var Fe;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},e.getValidEnumValues=s=>{let a=e.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(a){return s[a]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},e.find=(s,a)=>{for(let i of s)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=r,e.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Fe||(Fe={}));var Nw;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Nw||(Nw={}));var re=Fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ss=e=>{switch(typeof e){case"undefined":return re.undefined;case"string":return re.string;case"number":return Number.isNaN(e)?re.nan:re.number;case"boolean":return re.boolean;case"function":return re.function;case"bigint":return re.bigint;case"symbol":return re.symbol;case"object":return Array.isArray(e)?re.array:e===null?re.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?re.promise:typeof Map<"u"&&e instanceof Map?re.map:typeof Set<"u"&&e instanceof Set?re.set:typeof Date<"u"&&e instanceof Date?re.date:re.object;default:return re.unknown}},D=Fe.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"]),fa=class Jx extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(t){if(!(t instanceof Jx))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Fe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n=Object.create(null),r=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];n[a]=n[a]||[],n[a].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fa.create=e=>new fa(e);var Fm=(e,t)=>{let n;switch(e.code){case D.invalid_type:e.received===re.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Fe.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:n=`Unrecognized key(s) in object: ${Fe.joinValues(e.keys,", ")}`;break;case D.invalid_union:n="Invalid input";break;case D.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Fe.joinValues(e.options)}`;break;case D.invalid_enum_value:n=`Invalid enum value. Expected ${Fe.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:n="Invalid function arguments";break;case D.invalid_return_type:n="Invalid function return type";break;case D.invalid_date:n="Invalid date";break;case D.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Fe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case D.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case D.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case D.custom:n="Invalid input";break;case D.invalid_intersection_types:n="Intersection results could not be merged";break;case D.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:n="Number must be finite";break;default:n=t.defaultError,Fe.assertNever(e)}return{message:n}},QR=Fm;function e2(){return QR}var t2=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}};function H(e,t){let n=e2(),r=t2({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Fm?void 0:Fm].filter(s=>!!s)});e.common.issues.push(r)}var or=class Gx{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return we;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let a=await s.key,i=await s.value;r.push({key:a,value:i})}return Gx.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return we;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:t.value,value:r}}},we=Object.freeze({status:"aborted"}),Bm=e=>({status:"dirty",value:e}),Un=e=>({status:"valid",value:e}),Pw=e=>e.status==="aborted",jw=e=>e.status==="dirty",Ii=e=>e.status==="valid",Ul=e=>typeof Promise<"u"&&e instanceof Promise,ae;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ae||(ae={}));var xs=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},Rw=(e,t)=>{if(Ii(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fa(e.common.issues);return this._error=n,this._error}}};function $e(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,i)=>{let{message:o}=e;return a.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:o??n??i.defaultError}},description:s}}var Le=class{get description(){return this._def.description}_getType(e){return ss(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new or,ctx:{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ul(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Rw(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Ii(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>Ii(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(Ul(r)?r:Promise.resolve(r));return Rw(n,s)}refine(e,t){let n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let a=e(r),i=()=>s.addIssue({code:D.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(o=>o?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new Ai({schema:this,typeName:F.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 ms.create(this,this._def)}nullable(){return $i.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ei.create(this)}promise(){return Bl.create(this,this._def)}or(e){return Dl.create([this,e],this._def)}and(e){return Fl.create(this,e,this._def)}transform(e){return new Ai({...$e(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Km({...$e(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new O2({typeName:F.ZodBranded,type:this,...$e(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Xm({...$e(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return S2.create(this,e)}readonly(){return Ym.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},n2=/^c[^\s-]{8,}$/i,r2=/^[0-9a-z]+$/,s2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a2=/^[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,i2=/^[a-z0-9_-]{21}$/i,o2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,c2=/^[-+]?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)?)??$/,u2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,l2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vf,d2=/^(?:(?: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])$/,p2=/^(?:(?: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])$/,h2=/^(([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]))$/,f2=/^(([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])$/,m2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kx="((\\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])))",y2=new RegExp(`^${Kx}$`);function Xx(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function _2(e){return new RegExp(`^${Xx(e)}$`)}function v2(e){let t=`${Kx}T${Xx(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function w2(e,t){return!!((t==="v4"||!t)&&d2.test(e)||(t==="v6"||!t)&&h2.test(e))}function b2(e,t){if(!o2.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function k2(e,t){return!!((t==="v4"||!t)&&p2.test(e)||(t==="v6"||!t)&&f2.test(e))}var Zm=class vo extends Le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==re.string){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.string,received:s.parsedType}),we}let n=new or,r;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(r=this._getOrReturnCtx(t,r),a?H(r,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&H(r,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")u2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"email",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")vf||(vf=new RegExp(l2,"u")),vf.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"emoji",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")a2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"uuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")i2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"nanoid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")n2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")r2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cuid2",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")s2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"ulid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),H(r,{validation:"url",code:D.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"regex",code:D.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?v2(s).test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?y2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?_2(s).test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{code:D.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?c2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"duration",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?w2(t.data,s.version)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"ip",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?b2(t.data,s.alg)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"jwt",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k2(t.data,s.version)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"cidr",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?m2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"base64",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?g2.test(t.data)||(r=this._getOrReturnCtx(t,r),H(r,{validation:"base64url",code:D.invalid_string,message:s.message}),n.dirty()):Fe.assertNever(s);return{status:n.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:D.invalid_string,...ae.errToObj(r)})}_addCheck(t){return new vo({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ae.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ae.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ae.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ae.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ae.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ae.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ae.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ae.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ae.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ae.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ae.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ae.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ae.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ae.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ae.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ae.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ae.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...ae.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ae.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ae.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ae.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ae.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ae.errToObj(n)})}nonempty(t){return this.min(1,ae.errToObj(t))}trim(){return new vo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new vo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new vo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Zm.create=e=>new Zm({checks:[],typeName:F.ZodString,coerce:e?.coerce??!1,...$e(e)});function x2(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}var Mw=class qm extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==re.number){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.number,received:s.parsedType}),we}let n,r=new or;for(let s of this._def.checks)s.kind==="int"?Fe.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?x2(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_finite,message:s.message}),r.dirty()):Fe.assertNever(s);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ae.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ae.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ae.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ae.toString(n))}setLimit(t,n,r,s){return new qm({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ae.toString(s)}]})}_addCheck(t){return new qm({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ae.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ae.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ae.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ae.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ae.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ae.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ae.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ae.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ae.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Fe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Mw.create=e=>new Mw({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...$e(e)});var Lw=class Vm extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==re.bigint)return this._getInvalidInput(t);let n,r=new or;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Fe.assertNever(s);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:re.bigint,received:n.parsedType}),we}gte(t,n){return this.setLimit("min",t,!0,ae.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ae.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ae.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ae.toString(n))}setLimit(t,n,r,s){return new Vm({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ae.toString(s)}]})}_addCheck(t){return new Vm({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ae.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ae.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ae.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ae.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ae.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Lw.create=e=>new Lw({checks:[],typeName:F.ZodBigInt,coerce:e?.coerce??!1,...$e(e)});var zw=class extends Le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==re.boolean){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.boolean,received:t.parsedType}),we}return Un(e.data)}};zw.create=e=>new zw({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...$e(e)});var Uw=class Yx extends Le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==re.date){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:re.date,received:s.parsedType}),we}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_date}),we}let n=new or,r;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(r=this._getOrReturnCtx(t,r),H(r,{code:D.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Fe.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Yx({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ae.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ae.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Uw.create=e=>new Uw({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...$e(e)});var Dw=class extends Le{_parse(e){if(this._getType(e)!==re.symbol){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.symbol,received:t.parsedType}),we}return Un(e.data)}};Dw.create=e=>new Dw({typeName:F.ZodSymbol,...$e(e)});var Fw=class extends Le{_parse(e){if(this._getType(e)!==re.undefined){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.undefined,received:t.parsedType}),we}return Un(e.data)}};Fw.create=e=>new Fw({typeName:F.ZodUndefined,...$e(e)});var Bw=class extends Le{_parse(e){if(this._getType(e)!==re.null){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.null,received:t.parsedType}),we}return Un(e.data)}};Bw.create=e=>new Bw({typeName:F.ZodNull,...$e(e)});var Hm=class extends Le{constructor(){super(...arguments),this._any=!0}_parse(e){return Un(e.data)}};Hm.create=e=>new Hm({typeName:F.ZodAny,...$e(e)});var Zw=class extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Un(e.data)}};Zw.create=e=>new Zw({typeName:F.ZodUnknown,...$e(e)});var Os=class extends Le{_parse(e){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.never,received:t.parsedType}),we}};Os.create=e=>new Os({typeName:F.ZodNever,...$e(e)});var qw=class extends Le{_parse(e){if(this._getType(e)!==re.undefined){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.void,received:t.parsedType}),we}return Un(e.data)}};qw.create=e=>new qw({typeName:F.ZodVoid,...$e(e)});var Ei=class il extends Le{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==re.array)return H(n,{code:D.invalid_type,expected:re.array,received:n.parsedType}),we;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(H(n,{code:i?D.too_big:D.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(H(n,{code:D.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(H(n,{code:D.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new xs(n,i,n.path,o)))).then(i=>or.mergeArray(r,i));let a=[...n.data].map((i,o)=>s.type._parseSync(new xs(n,i,n.path,o)));return or.mergeArray(r,a)}get element(){return this._def.type}min(t,n){return new il({...this._def,minLength:{value:t,message:ae.toString(n)}})}max(t,n){return new il({...this._def,maxLength:{value:t,message:ae.toString(n)}})}length(t,n){return new il({...this._def,exactLength:{value:t,message:ae.toString(n)}})}nonempty(t){return this.min(1,t)}};Ei.create=(e,t)=>new Ei({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...$e(t)});function Ja(e){if(e instanceof Jr){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ms.create(Ja(r))}return new Jr({...e._def,shape:()=>t})}else return e instanceof Ei?new Ei({...e._def,type:Ja(e.element)}):e instanceof ms?ms.create(Ja(e.unwrap())):e instanceof $i?$i.create(Ja(e.unwrap())):e instanceof sc?sc.create(e.items.map(t=>Ja(t))):e}var Jr=class Wn extends Le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Fe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==re.object){let c=this._getOrReturnCtx(t);return H(c,{code:D.invalid_type,expected:re.object,received:c.parsedType}),we}let{status:n,ctx:r}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Os&&this._def.unknownKeys==="strip"))for(let c in r.data)a.includes(c)||i.push(c);let o=[];for(let c of a){let u=s[c],l=r.data[c];o.push({key:{status:"valid",value:c},value:u._parse(new xs(r,l,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Os){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)o.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")i.length>0&&(H(r,{code:D.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=r.data[u];o.push({key:{status:"valid",value:u},value:c._parse(new xs(r,l,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of o){let l=await u.key,d=await u.value;c.push({key:l,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>or.mergeObjectSync(n,c)):or.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(t){return ae.errToObj,new Wn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ae.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new Wn({...this._def,unknownKeys:"strip"})}passthrough(){return new Wn({...this._def,unknownKeys:"passthrough"})}extend(t){return new Wn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Wn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Wn({...this._def,catchall:t})}pick(t){let n={};for(let r of Fe.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Wn({...this._def,shape:()=>n})}omit(t){let n={};for(let r of Fe.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Wn({...this._def,shape:()=>n})}deepPartial(){return Ja(this)}partial(t){let n={};for(let r of Fe.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new Wn({...this._def,shape:()=>n})}required(t){let n={};for(let r of Fe.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ms;)s=s._def.innerType;n[r]=s}return new Wn({...this._def,shape:()=>n})}keyof(){return eO(Fe.objectKeys(this.shape))}};Jr.create=(e,t)=>new Jr({shape:()=>e,unknownKeys:"strip",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});Jr.strictCreate=(e,t)=>new Jr({shape:()=>e,unknownKeys:"strict",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});Jr.lazycreate=(e,t)=>new Jr({shape:e,unknownKeys:"strip",catchall:Os.create(),typeName:F.ZodObject,...$e(t)});var Dl=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new fa(i.ctx.common.issues));return H(t,{code:D.invalid_union,unionErrors:a}),we}if(t.common.async)return Promise.all(n.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let s,a=[];for(let o of n){let c={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(o=>new fa(o));return H(t,{code:D.invalid_union,unionErrors:i}),we}}get options(){return this._def.options}};Dl.create=(e,t)=>new Dl({options:e,typeName:F.ZodUnion,...$e(t)});function Wm(e,t){let n=ss(e),r=ss(t);if(e===t)return{valid:!0,data:e};if(n===re.object&&r===re.object){let s=Fe.objectKeys(t),a=Fe.objectKeys(e).filter(o=>s.indexOf(o)!==-1),i={...e,...t};for(let o of a){let c=Wm(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===re.array&&r===re.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let a=0;a<e.length;a++){let i=e[a],o=t[a],c=Wm(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===re.date&&r===re.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Fl=class extends Le{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(s,a)=>{if(Pw(s)||Pw(a))return we;let i=Wm(s.value,a.value);return i.valid?((jw(s)||jw(a))&&t.dirty(),{status:t.value,value:i.data}):(H(n,{code:D.invalid_intersection_types}),we)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>r(s,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Fl.create=(e,t,n)=>new Fl({left:e,right:t,typeName:F.ZodIntersection,...$e(n)});var sc=class Qx extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.array)return H(r,{code:D.invalid_type,expected:re.array,received:r.parsedType}),we;if(r.data.length<this._def.items.length)return H(r,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),we;!this._def.rest&&r.data.length>this._def.items.length&&(H(r,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,i)=>{let o=this._def.items[i]||this._def.rest;return o?o._parse(new xs(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>or.mergeArray(n,a)):or.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Qx({...this._def,rest:t})}};sc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sc({items:e,typeName:F.ZodTuple,rest:null,...$e(t)})};var Vw=class extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==re.map)return H(n,{code:D.invalid_type,expected:re.map,received:n.parsedType}),we;let r=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,o],c)=>({key:r._parse(new xs(n,i,n.path,[c,"key"])),value:s._parse(new xs(n,o,n.path,[c,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let o of a){let c=await o.key,u=await o.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),i.set(c.value,u.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let o of a){let c=o.key,u=o.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),i.set(c.value,u.value)}return{status:t.value,value:i}}}};Vw.create=(e,t,n)=>new Vw({valueType:t,keyType:e,typeName:F.ZodMap,...$e(n)});var Hw=class Jm extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.set)return H(r,{code:D.invalid_type,expected:re.set,received:r.parsedType}),we;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(H(r,{code:D.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(H(r,{code:D.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return we;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let o=[...r.data.values()].map((c,u)=>a._parse(new xs(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,n){return new Jm({...this._def,minSize:{value:t,message:ae.toString(n)}})}max(t,n){return new Jm({...this._def,maxSize:{value:t,message:ae.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Hw.create=(e,t)=>new Hw({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...$e(t)});var Ww=class extends Le{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})}};Ww.create=(e,t)=>new Ww({getter:e,typeName:F.ZodLazy,...$e(t)});var Jw=class extends Le{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return H(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jw.create=(e,t)=>new Jw({value:e,typeName:F.ZodLiteral,...$e(t)});function eO(e,t){return new Hy({values:e,typeName:F.ZodEnum,...$e(t)})}var Hy=class Gm extends Le{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return H(n,{expected:Fe.joinValues(r),received:n.parsedType,code:D.invalid_type}),we}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return H(n,{received:n.data,code:D.invalid_enum_value,options:r}),we}return Un(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Gm.create(t,{...this._def,...n})}exclude(t,n=this._def){return Gm.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Hy.create=eO;var Gw=class extends Le{_parse(e){let t=Fe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==re.string&&n.parsedType!==re.number){let r=Fe.objectValues(t);return H(n,{expected:Fe.joinValues(r),received:n.parsedType,code:D.invalid_type}),we}if(this._cache||(this._cache=new Set(Fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=Fe.objectValues(t);return H(n,{received:n.data,code:D.invalid_enum_value,options:r}),we}return Un(e.data)}get enum(){return this._def.values}};Gw.create=(e,t)=>new Gw({values:e,typeName:F.ZodNativeEnum,...$e(t)});var Bl=class extends Le{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==re.promise&&t.common.async===!1)return H(t,{code:D.invalid_type,expected:re.promise,received:t.parsedType}),we;let n=t.parsedType===re.promise?t.data:Promise.resolve(t.data);return Un(n.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Bl.create=(e,t)=>new Bl({type:e,typeName:F.ZodPromise,...$e(t)});var Ai=class extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:a=>{H(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){let a=r.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(t.value==="aborted")return we;let o=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return o.status==="aborted"?we:o.status==="dirty"||t.value==="dirty"?Bm(o.value):o});{if(t.value==="aborted")return we;let i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?we:i.status==="dirty"||t.value==="dirty"?Bm(i.value):i}}if(r.type==="refinement"){let a=i=>{let o=r.refinement(i,s);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?we:(i.status==="dirty"&&t.dirty(),a(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?we:(i.status==="dirty"&&t.dirty(),a(i.value).then(()=>({status:t.value,value:i.value}))))}if(r.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ii(a))return we;let i=r.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ii(a)?Promise.resolve(r.transform(a.value,s)).then(i=>({status:t.value,value:i})):we);Fe.assertNever(r)}};Ai.create=(e,t,n)=>new Ai({schema:e,typeName:F.ZodEffects,effect:t,...$e(n)});Ai.createWithPreprocess=(e,t,n)=>new Ai({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...$e(n)});var ms=class extends Le{_parse(e){return this._getType(e)===re.undefined?Un(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ms.create=(e,t)=>new ms({innerType:e,typeName:F.ZodOptional,...$e(t)});var $i=class extends Le{_parse(e){return this._getType(e)===re.null?Un(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$i.create=(e,t)=>new $i({innerType:e,typeName:F.ZodNullable,...$e(t)});var Km=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===re.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Km.create=(e,t)=>new Km({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$e(t)});var Xm=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ul(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new fa(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new fa(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Xm.create=(e,t)=>new Xm({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$e(t)});var Kw=class extends Le{_parse(e){if(this._getType(e)!==re.nan){let t=this._getOrReturnCtx(e);return H(t,{code:D.invalid_type,expected:re.nan,received:t.parsedType}),we}return{status:"valid",value:e.data}}};Kw.create=e=>new Kw({typeName:F.ZodNaN,...$e(e)});var O2=class extends Le{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},S2=class tO extends Le{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?we:s.status==="dirty"?(n.dirty(),Bm(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?we:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new tO({in:t,out:n,typeName:F.ZodPipeline})}},Ym=class extends Le{_parse(e){let t=this._def.innerType._parse(e),n=r=>(Ii(r)&&(r.value=Object.freeze(r.value)),r);return Ul(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}};Ym.create=(e,t)=>new Ym({innerType:e,typeName:F.ZodReadonly,...$e(t)});var F;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(F||(F={}));var Rp=Zm.create,Xw=Hm.create;Os.create;Ei.create;var Mp=Jr.create;Dl.create;Fl.create;sc.create;Hy.create;Bl.create;ms.create;$i.create;function T2(e,t){let n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==F.ZodAny&&(n.items=Ze(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ve(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ve(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ve(n,"minItems",e.exactLength.value,e.exactLength.message,t),Ve(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function I2(e,t){let n={type:"integer",format:"int64"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?Ve(n,"minimum",r.value,r.message,t):Ve(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ve(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?Ve(n,"maximum",r.value,r.message,t):Ve(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ve(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ve(n,"multipleOf",r.value,r.message,t);break}return n}function E2(){return{type:"boolean"}}function nO(e,t){return Ze(e.type._def,t)}var A2=(e,t)=>Ze(e.innerType._def,t);function rO(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>rO(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $2(e,t)}}var $2=(e,t)=>{let n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(let r of e.checks)switch(r.kind){case"min":Ve(n,"minimum",r.value,r.message,t);break;case"max":Ve(n,"maximum",r.value,r.message,t);break}return n};function C2(e,t){return{...Ze(e.innerType._def,t),default:e.defaultValue()}}function N2(e,t){return t.effectStrategy==="input"?Ze(e.schema._def,t):yn(t)}function P2(e){return{type:"string",enum:Array.from(e.values)}}var j2=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function R2(e,t){let n=[Ze(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ze(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(a=>{if(j2(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function M2(e,t){let n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}var wf,Zn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(wf===void 0&&(wf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wf),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function sO(e,t){let n={type:"string"};if(e.checks)for(let r of e.checks)switch(r.kind){case"min":Ve(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Ve(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":qn(n,"email",r.message,t);break;case"format:idn-email":qn(n,"idn-email",r.message,t);break;case"pattern:zod":Wt(n,Zn.email,r.message,t);break}break;case"url":qn(n,"uri",r.message,t);break;case"uuid":qn(n,"uuid",r.message,t);break;case"regex":Wt(n,r.regex,r.message,t);break;case"cuid":Wt(n,Zn.cuid,r.message,t);break;case"cuid2":Wt(n,Zn.cuid2,r.message,t);break;case"startsWith":Wt(n,RegExp(`^${bf(r.value,t)}`),r.message,t);break;case"endsWith":Wt(n,RegExp(`${bf(r.value,t)}$`),r.message,t);break;case"datetime":qn(n,"date-time",r.message,t);break;case"date":qn(n,"date",r.message,t);break;case"time":qn(n,"time",r.message,t);break;case"duration":qn(n,"duration",r.message,t);break;case"length":Ve(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),Ve(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":Wt(n,RegExp(bf(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&qn(n,"ipv4",r.message,t),r.version!=="v4"&&qn(n,"ipv6",r.message,t);break;case"base64url":Wt(n,Zn.base64url,r.message,t);break;case"jwt":Wt(n,Zn.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&Wt(n,Zn.ipv4Cidr,r.message,t),r.version!=="v4"&&Wt(n,Zn.ipv6Cidr,r.message,t);break;case"emoji":Wt(n,Zn.emoji(),r.message,t);break;case"ulid":Wt(n,Zn.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":qn(n,"binary",r.message,t);break;case"contentEncoding:base64":Ve(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":Wt(n,Zn.base64,r.message,t);break}break;case"nanoid":Wt(n,Zn.nanoid,r.message,t);break}return n}function bf(e,t){return t.patternStrategy==="escape"?z2(e):e}var L2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z2(e){let t="";for(let n=0;n<e.length;n++)L2.has(e[n])||(t+="\\"),t+=e[n];return t}function qn(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ve(e,"format",t,n,r)}function Wt(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Yw(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ve(e,"pattern",Yw(t,r),n,r)}function Yw(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source,s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
66
66
  ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
67
67
  ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
68
68
  `:`[${r[c]}\r
69
69
  ]`;continue}s+=r[c],r[c]==="\\"?a=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function aO(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??yn(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===F.ZodString&&e.keyType._def.checks?.length){let{type:r,...s}=sO(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===F.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===F.ZodBranded&&e.keyType._def.type._def.typeName===F.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...s}=nO(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function U2(e,t){return t.mapStrategy==="record"?aO(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Ze(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||yn(t),Ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||yn(t)],minItems:2,maxItems:2}}}function D2(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),r=Array.from(new Set(n.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function F2(e){return e.target==="openAi"?void 0:{not:yn({...e,currentPath:[...e.currentPath,"not"]})}}function B2(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Zl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Z2(e,t){if(t.target==="openApi3")return Qw(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Zl&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,a)=>{let i=Zl[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;default:return s}},[]);if(r.length===n.length){let s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Qw(e,t)}var Qw=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Ze(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function q2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Zl[e.innerType._def.typeName],nullable:!0}:{type:[Zl[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let r=Ze(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Ze(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function V2(e,t){let n={type:"number"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"int":n.type="integer",Wx(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?Ve(n,"minimum",r.value,r.message,t):Ve(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ve(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?Ve(n,"maximum",r.value,r.message,t):Ve(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ve(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ve(n,"multipleOf",r.value,r.message,t);break}return n}function H2(e,t){let n=t.target==="openAi",r={type:"object",properties:{}},s=[],a=e.shape();for(let o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let u=J2(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Ze(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,u||s.push(o))}s.length&&(r.required=s);let i=W2(e,t);return i!==void 0&&(r.additionalProperties=i),r}function W2(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ze(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function J2(e){try{return e.isOptional()}catch{return!0}}var G2=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ze(e.innerType._def,t);let n=Ze(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:yn(t)},n]}:yn(t)},K2=(e,t)=>{if(t.pipeStrategy==="input")return Ze(e.in._def,t);if(t.pipeStrategy==="output")return Ze(e.out._def,t);let n=Ze(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,Ze(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}};function X2(e,t){return Ze(e.type._def,t)}function Y2(e,t){let n={type:"array",uniqueItems:!0,items:Ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ve(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ve(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Q2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Ze(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Ze(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Ze(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function eM(e){return{not:yn(e)}}function tM(e){return yn(e)}var nM=(e,t)=>Ze(e.innerType._def,t),rM=(e,t,n)=>{switch(t){case F.ZodString:return sO(e,n);case F.ZodNumber:return V2(e,n);case F.ZodObject:return H2(e,n);case F.ZodBigInt:return I2(e,n);case F.ZodBoolean:return E2();case F.ZodDate:return rO(e,n);case F.ZodUndefined:return eM(n);case F.ZodNull:return B2(n);case F.ZodArray:return T2(e,n);case F.ZodUnion:case F.ZodDiscriminatedUnion:return Z2(e,n);case F.ZodIntersection:return R2(e,n);case F.ZodTuple:return Q2(e,n);case F.ZodRecord:return aO(e,n);case F.ZodLiteral:return M2(e,n);case F.ZodEnum:return P2(e);case F.ZodNativeEnum:return D2(e);case F.ZodNullable:return q2(e,n);case F.ZodOptional:return G2(e,n);case F.ZodMap:return U2(e,n);case F.ZodSet:return Y2(e,n);case F.ZodLazy:return()=>e.getter()._def;case F.ZodPromise:return X2(e,n);case F.ZodNaN:case F.ZodNever:return F2(n);case F.ZodEffects:return N2(e,n);case F.ZodAny:return yn(n);case F.ZodUnknown:return tM(n);case F.ZodDefault:return C2(e,n);case F.ZodBranded:return nO(e,n);case F.ZodReadonly:return nM(e,n);case F.ZodCatch:return A2(e,n);case F.ZodPipeline:return K2(e,n);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(r=>{})()}};function Ze(e,t,n=!1){let r=t.seen.get(e);if(t.override){let o=t.override?.(e,t,r,n);if(o!==GR)return o}if(r&&!n){let o=sM(r,t);if(o!==void 0)return o}let s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);let a=rM(e,e.typeName,t),i=typeof a=="function"?Ze(a(),t):a;if(i&&aM(e,t,i),t.postProcess){let o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}var sM=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Hx(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),yn(t)):t.$refStrategy==="seen"?yn(t):void 0}},aM=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),iM=(e,t)=>{let n=YR(t),r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,u])=>({...o,[c]:Ze(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??yn(n)}),{}):void 0,s=typeof t=="string"?t:t?.name,a=Ze(e._def,n,!1)??yn(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let i=s===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function oa(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=e.length;if(r!==t.length)return!1;for(let s=0;s<r;s++)if(!oa(e[s],t[s]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let a of r)if(!oa(e[a],t[a]))return!1;return!0}return e===t}function Gn(e){return encodeURI(oM(e))}function oM(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var cM={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},uM={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},lM={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},dM=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function cs(e,t=Object.create(null),n=dM,r=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let a=e.$id||e.id;if(a){let i=new URL(a,n.href);i.hash.length>1?t[i.href]=e:(i.hash="",r===""?n=i:cs(e,t,n))}}else if(e!==!0&&e!==!1)return t;let s=n.href+(r?"#"+r:"");if(t[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s}),e.$ref&&e.__absolute_ref__===void 0){let a=new URL(e.$ref,n.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let a=new URL(e.$recursiveRef,n.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){let a=new URL("#"+e.$anchor,n.href);t[a.href]=e}for(let a in e){if(lM[a])continue;let i=`${r}/${Gn(a)}`,o=e[a];if(Array.isArray(o)){if(cM[a]){let c=o.length;for(let u=0;u<c;u++)cs(o[u],t,n,`${i}/${u}`)}}else if(uM[a])for(let c in o)cs(o[c],t,n,`${i}/${Gn(c)}`);else cs(o,t,n,i)}return t}var pM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,hM=[0,31,28,31,30,31,30,31,31,30,31,30,31],fM=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,mM=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,gM=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,yM=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,_M=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,vM=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wM=/^(?:\/(?:[^~/]|~0|~1)*)*$/,bM=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,kM=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,xM=e=>{if(e[0]==='"')return!1;let[t,n,...r]=e.split("@");return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},OM=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,SM=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,TM=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function pr(e){return e.test.bind(e)}var eb={date:iO,time:oO.bind(void 0,!1),"date-time":AM,duration:TM,uri:NM,"uri-reference":pr(gM),"uri-template":pr(yM),url:pr(_M),email:xM,hostname:pr(mM),ipv4:pr(OM),ipv6:pr(SM),regex:jM,uuid:pr(vM),"json-pointer":pr(wM),"json-pointer-uri-fragment":pr(bM),"relative-json-pointer":pr(kM)};function IM(e){return e%4===0&&(e%100!==0||e%400===0)}function iO(e){let t=e.match(pM);if(!t)return!1;let n=+t[1],r=+t[2],s=+t[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&IM(n)?29:hM[r])}function oO(e,t){let n=t.match(fM);if(!n)return!1;let r=+n[1],s=+n[2],a=+n[3],i=!!n[5];return(r<=23&&s<=59&&a<=59||r==23&&s==59&&a==60)&&(!e||i)}var EM=/t|\s/i;function AM(e){let t=e.split(EM);return t.length==2&&iO(t[0])&&oO(!0,t[1])}var $M=/\/|:/,CM=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function NM(e){return $M.test(e)&&CM.test(e)}var PM=/[^\\]\\Z/;function jM(e){if(PM.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function RM(e){let t=0,n=e.length,r=0,s;for(;r<n;)t++,s=e.charCodeAt(r++),s>=55296&&s<=56319&&r<n&&(s=e.charCodeAt(r),(s&64512)==56320&&r++);return t}function st(e,t,n="2019-09",r=cs(t),s=!0,a=null,i="#",o="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:d,$recursiveRef:p,$recursiveAnchor:h,type:f,const:m,enum:v,required:g,not:y,anyOf:k,allOf:x,oneOf:S,if:E,then:I,else:w,format:P,properties:A,patternProperties:Z,additionalProperties:ze,unevaluatedProperties:rt,minProperties:B,maxProperties:L,propertyNames:z,dependentRequired:ee,dependentSchemas:oe,dependencies:ne,prefixItems:ue,items:Oe,additionalItems:Te,unevaluatedItems:Ue,contains:De,minContains:kt,maxContains:b,minItems:_,maxItems:C,uniqueItems:O,minimum:Ne,maximum:Je,exclusiveMinimum:yt,exclusiveMaximum:pt,multipleOf:Lt,minLength:Cn,maxLength:ht,pattern:dr,__absolute_ref__:La,__absolute_recursive_ref__:uu}=t,V=[];if(h===!0&&a===null&&(a=t),p==="#"){let he=a===null?r[uu]:a,ce=`${o}/$recursiveRef`,Ae=st(e,a===null?t:a,n,r,s,he,i,ce,c);Ae.valid||V.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:ce,error:"A subschema had errors."},...Ae.errors)}if(d!==void 0){let he=r[La||d];if(he===void 0){let X=`Unresolved $ref "${d}".`;throw La&&La!==d&&(X+=` Absolute URI "${La}".`),X+=`
70
70
  Known schemas:
71
71
  - ${Object.keys(r).join(`
72
- - `)}`,new Error(X)}let ce=`${o}/$ref`,Ae=st(e,he,n,r,s,a,i,ce,c);if(Ae.valid||V.push({instanceLocation:i,keyword:"$ref",keywordLocation:ce,error:"A subschema had errors."},...Ae.errors),n==="4"||n==="7")return{valid:V.length===0,errors:V}}if(Array.isArray(f)){let he=f.length,ce=!1;for(let Ae=0;Ae<he;Ae++)if(l===f[Ae]||f[Ae]==="integer"&&l==="number"&&e%1===0&&e===e){ce=!0;break}ce||V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(l!=="number"||e%1||e!==e)&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`}):f!==void 0&&l!==f&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`});if(m!==void 0&&(l==="object"||l==="array"?oa(e,m)||V.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):e!==m&&V.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),v!==void 0&&(l==="object"||l==="array"?v.some(he=>oa(e,he))||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(he=>e===he)||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),y!==void 0){let he=`${o}/not`;st(e,y,n,r,s,a,i,he).valid&&V.push({instanceLocation:i,keyword:"not",keywordLocation:he,error:'Instance matched "not" schema.'})}let Fs=[];if(k!==void 0){let he=`${o}/anyOf`,ce=V.length,Ae=!1;for(let X=0;X<k.length;X++){let W=k[X],_e=Object.create(c),ye=st(e,W,n,r,s,h===!0?a:null,i,`${he}/${X}`,_e);V.push(...ye.errors),Ae=Ae||ye.valid,ye.valid&&Fs.push(_e)}Ae?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:he,error:"Instance does not match any subschemas."})}if(x!==void 0){let he=`${o}/allOf`,ce=V.length,Ae=!0;for(let X=0;X<x.length;X++){let W=x[X],_e=Object.create(c),ye=st(e,W,n,r,s,h===!0?a:null,i,`${he}/${X}`,_e);V.push(...ye.errors),Ae=Ae&&ye.valid,ye.valid&&Fs.push(_e)}Ae?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"allOf",keywordLocation:he,error:"Instance does not match every subschema."})}if(S!==void 0){let he=`${o}/oneOf`,ce=V.length,Ae=S.filter((X,W)=>{let _e=Object.create(c),ye=st(e,X,n,r,s,h===!0?a:null,i,`${he}/${W}`,_e);return V.push(...ye.errors),ye.valid&&Fs.push(_e),ye.valid}).length;Ae===1?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:he,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Fs),E!==void 0){let he=`${o}/if`;if(st(e,E,n,r,s,a,i,he,c).valid){if(I!==void 0){let ce=st(e,I,n,r,s,a,i,`${o}/then`,c);ce.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:he,error:'Instance does not match "then" schema.'},...ce.errors)}}else if(w!==void 0){let ce=st(e,w,n,r,s,a,i,`${o}/else`,c);ce.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:he,error:'Instance does not match "else" schema.'},...ce.errors)}}if(l==="object"){if(g!==void 0)for(let X of g)X in e||V.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${X}".`});let he=Object.keys(e);if(B!==void 0&&he.length<B&&V.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${B} properties.`}),L!==void 0&&he.length>L&&V.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${L} properties.`}),z!==void 0){let X=`${o}/propertyNames`;for(let W in e){let _e=`${i}/${Gn(W)}`,ye=st(W,z,n,r,s,a,_e,X);ye.valid||V.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:X,error:`Property name "${W}" does not match schema.`},...ye.errors)}}if(ee!==void 0){let X=`${o}/dependantRequired`;for(let W in ee)if(W in e){let _e=ee[W];for(let ye of _e)ye in e||V.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:X,error:`Instance has "${W}" but does not have "${ye}".`})}}if(oe!==void 0)for(let X in oe){let W=`${o}/dependentSchemas`;if(X in e){let _e=st(e,oe[X],n,r,s,a,i,`${W}/${Gn(X)}`,c);_e.valid||V.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:W,error:`Instance has "${X}" but does not match dependant schema.`},..._e.errors)}}if(ne!==void 0){let X=`${o}/dependencies`;for(let W in ne)if(W in e){let _e=ne[W];if(Array.isArray(_e))for(let ye of _e)ye in e||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:X,error:`Instance has "${W}" but does not have "${ye}".`});else{let ye=st(e,_e,n,r,s,a,i,`${X}/${Gn(W)}`);ye.valid||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:X,error:`Instance has "${W}" but does not match dependant schema.`},...ye.errors)}}}let ce=Object.create(null),Ae=!1;if(A!==void 0){let X=`${o}/properties`;for(let W in A){if(!(W in e))continue;let _e=`${i}/${Gn(W)}`,ye=st(e[W],A[W],n,r,s,a,_e,`${X}/${Gn(W)}`);if(ye.valid)c[W]=ce[W]=!0;else if(Ae=s,V.push({instanceLocation:i,keyword:"properties",keywordLocation:X,error:`Property "${W}" does not match schema.`},...ye.errors),Ae)break}}if(!Ae&&Z!==void 0){let X=`${o}/patternProperties`;for(let W in Z){let _e=new RegExp(W,"u"),ye=Z[W];for(let on in e){if(!_e.test(on))continue;let zE=`${i}/${Gn(on)}`,n0=st(e[on],ye,n,r,s,a,zE,`${X}/${Gn(W)}`);n0.valid?c[on]=ce[on]=!0:(Ae=s,V.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:X,error:`Property "${on}" matches pattern "${W}" but does not match associated schema.`},...n0.errors))}}}if(!Ae&&ze!==void 0){let X=`${o}/additionalProperties`;for(let W in e){if(ce[W])continue;let _e=`${i}/${Gn(W)}`,ye=st(e[W],ze,n,r,s,a,_e,X);ye.valid?c[W]=!0:(Ae=s,V.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:X,error:`Property "${W}" does not match additional properties schema.`},...ye.errors))}}else if(!Ae&&rt!==void 0){let X=`${o}/unevaluatedProperties`;for(let W in e)if(!c[W]){let _e=`${i}/${Gn(W)}`,ye=st(e[W],rt,n,r,s,a,_e,X);ye.valid?c[W]=!0:V.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:X,error:`Property "${W}" does not match unevaluated properties schema.`},...ye.errors)}}}else if(l==="array"){C!==void 0&&e.length>C&&V.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${C}).`}),_!==void 0&&e.length<_&&V.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${_}).`});let he=e.length,ce=0,Ae=!1;if(ue!==void 0){let X=`${o}/prefixItems`,W=Math.min(ue.length,he);for(;ce<W;ce++){let _e=st(e[ce],ue[ce],n,r,s,a,`${i}/${ce}`,`${X}/${ce}`);if(c[ce]=!0,!_e.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:X,error:"Items did not match schema."},..._e.errors),Ae))break}}if(Oe!==void 0){let X=`${o}/items`;if(Array.isArray(Oe)){let W=Math.min(Oe.length,he);for(;ce<W;ce++){let _e=st(e[ce],Oe[ce],n,r,s,a,`${i}/${ce}`,`${X}/${ce}`);if(c[ce]=!0,!_e.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"items",keywordLocation:X,error:"Items did not match schema."},..._e.errors),Ae))break}}else for(;ce<he;ce++){let W=st(e[ce],Oe,n,r,s,a,`${i}/${ce}`,X);if(c[ce]=!0,!W.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"items",keywordLocation:X,error:"Items did not match schema."},...W.errors),Ae))break}if(!Ae&&Te!==void 0){let W=`${o}/additionalItems`;for(;ce<he;ce++){let _e=st(e[ce],Te,n,r,s,a,`${i}/${ce}`,W);c[ce]=!0,_e.valid||(Ae=s,V.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:W,error:"Items did not match additional items schema."},..._e.errors))}}}if(De!==void 0)if(he===0&&kt===void 0)V.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(kt!==void 0&&he<kt)V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${he}) than minContains (${kt}).`});else{let X=`${o}/contains`,W=V.length,_e=0;for(let ye=0;ye<he;ye++){let on=st(e[ye],De,n,r,s,a,`${i}/${ye}`,X);on.valid?(c[ye]=!0,_e++):V.push(...on.errors)}_e>=(kt||0)&&(V.length=W),kt===void 0&&b===void 0&&_e===0?V.splice(W,0,{instanceLocation:i,keyword:"contains",keywordLocation:X,error:"Array does not contain item matching schema."}):kt!==void 0&&_e<kt?V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${kt} items matching schema. Only ${_e} items were found.`}):b!==void 0&&_e>b&&V.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${b} items matching schema. ${_e} items were found.`})}if(!Ae&&Ue!==void 0){let X=`${o}/unevaluatedItems`;for(ce;ce<he;ce++){if(c[ce])continue;let W=st(e[ce],Ue,n,r,s,a,`${i}/${ce}`,X);c[ce]=!0,W.valid||V.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:X,error:"Items did not match unevaluated items schema."},...W.errors)}}if(O)for(let X=0;X<he;X++){let W=e[X],_e=typeof W=="object"&&W!==null;for(let ye=0;ye<he;ye++){if(X===ye)continue;let on=e[ye];(W===on||_e&&typeof on=="object"&&on!==null&&oa(W,on))&&(V.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${X} and ${ye}.`}),X=Number.MAX_SAFE_INTEGER,ye=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(Ne!==void 0&&(yt===!0&&e<=Ne||e<Ne)&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${yt?"or equal to ":""} ${Ne}.`}),Je!==void 0&&(pt===!0&&e>=Je||e>Je)&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${pt?"or equal to ":""} ${Je}.`})):(Ne!==void 0&&e<Ne&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${Ne}.`}),Je!==void 0&&e>Je&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Je}.`}),yt!==void 0&&e<=yt&&V.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${yt}.`}),pt!==void 0&&e>=pt&&V.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${pt}.`})),Lt!==void 0){let he=e%Lt;Math.abs(0-he)>=11920929e-14&&Math.abs(Lt-he)>=11920929e-14&&V.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${Lt}.`})}}else if(l==="string"){let he=Cn===void 0&&ht===void 0?0:RM(e);Cn!==void 0&&he<Cn&&V.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${he} < ${Cn}).`}),ht!==void 0&&he>ht&&V.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${he} > ${ht}).`}),dr!==void 0&&!new RegExp(dr,"u").test(e)&&V.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),P!==void 0&&eb[P]&&!eb[P](e)&&V.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${P}".`})}return{valid:V.length===0,errors:V}}var Qm=class{schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=cs(t)}validate(t){return st(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),cs(t,this.lookup)}},MM=Q({Validator:()=>Qm,deepCompareStrict:()=>oa,toJsonSchema:()=>It,validatesOnlyStrings:()=>Bo});function It(e,t){if(Dy(e)&&!nt(e))return e["~standard"].jsonSchema.input({target:"draft-07"});if(nt(e)){let n=qx(e,!0);return xr(n)?Cw(zl(n,!0),t):Cw(e,t)}return mt(e)?iM(e):e}function Bo(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Bo(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>Bo(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,n=cs(e);return n[t]?Bo(n[t]):!1}return!1}function Wy(e){return e?e.lc_runnable:!1}var LM=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||r.some(s=>this.includeTags?.includes(s))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&r.every(s=>!this.excludeTags?.includes(s))),n}},zM=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function kf(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var UM=["*","_","`"];function DM(e){let t="";for(let[n,r]of Object.entries(e))t+=` classDef ${n} ${r};
72
+ - `)}`,new Error(X)}let ce=`${o}/$ref`,Ae=st(e,he,n,r,s,a,i,ce,c);if(Ae.valid||V.push({instanceLocation:i,keyword:"$ref",keywordLocation:ce,error:"A subschema had errors."},...Ae.errors),n==="4"||n==="7")return{valid:V.length===0,errors:V}}if(Array.isArray(f)){let he=f.length,ce=!1;for(let Ae=0;Ae<he;Ae++)if(l===f[Ae]||f[Ae]==="integer"&&l==="number"&&e%1===0&&e===e){ce=!0;break}ce||V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(l!=="number"||e%1||e!==e)&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`}):f!==void 0&&l!==f&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`});if(m!==void 0&&(l==="object"||l==="array"?oa(e,m)||V.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):e!==m&&V.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),v!==void 0&&(l==="object"||l==="array"?v.some(he=>oa(e,he))||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(he=>e===he)||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),y!==void 0){let he=`${o}/not`;st(e,y,n,r,s,a,i,he).valid&&V.push({instanceLocation:i,keyword:"not",keywordLocation:he,error:'Instance matched "not" schema.'})}let Fs=[];if(k!==void 0){let he=`${o}/anyOf`,ce=V.length,Ae=!1;for(let X=0;X<k.length;X++){let W=k[X],_e=Object.create(c),ye=st(e,W,n,r,s,h===!0?a:null,i,`${he}/${X}`,_e);V.push(...ye.errors),Ae=Ae||ye.valid,ye.valid&&Fs.push(_e)}Ae?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:he,error:"Instance does not match any subschemas."})}if(x!==void 0){let he=`${o}/allOf`,ce=V.length,Ae=!0;for(let X=0;X<x.length;X++){let W=x[X],_e=Object.create(c),ye=st(e,W,n,r,s,h===!0?a:null,i,`${he}/${X}`,_e);V.push(...ye.errors),Ae=Ae&&ye.valid,ye.valid&&Fs.push(_e)}Ae?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"allOf",keywordLocation:he,error:"Instance does not match every subschema."})}if(S!==void 0){let he=`${o}/oneOf`,ce=V.length,Ae=S.filter((X,W)=>{let _e=Object.create(c),ye=st(e,X,n,r,s,h===!0?a:null,i,`${he}/${W}`,_e);return V.push(...ye.errors),ye.valid&&Fs.push(_e),ye.valid}).length;Ae===1?V.length=ce:V.splice(ce,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:he,error:`Instance does not match exactly one subschema (${Ae} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Fs),E!==void 0){let he=`${o}/if`;if(st(e,E,n,r,s,a,i,he,c).valid){if(I!==void 0){let ce=st(e,I,n,r,s,a,i,`${o}/then`,c);ce.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:he,error:'Instance does not match "then" schema.'},...ce.errors)}}else if(w!==void 0){let ce=st(e,w,n,r,s,a,i,`${o}/else`,c);ce.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:he,error:'Instance does not match "else" schema.'},...ce.errors)}}if(l==="object"){if(g!==void 0)for(let X of g)X in e||V.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${X}".`});let he=Object.keys(e);if(B!==void 0&&he.length<B&&V.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${B} properties.`}),L!==void 0&&he.length>L&&V.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${L} properties.`}),z!==void 0){let X=`${o}/propertyNames`;for(let W in e){let _e=`${i}/${Gn(W)}`,ye=st(W,z,n,r,s,a,_e,X);ye.valid||V.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:X,error:`Property name "${W}" does not match schema.`},...ye.errors)}}if(ee!==void 0){let X=`${o}/dependantRequired`;for(let W in ee)if(W in e){let _e=ee[W];for(let ye of _e)ye in e||V.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:X,error:`Instance has "${W}" but does not have "${ye}".`})}}if(oe!==void 0)for(let X in oe){let W=`${o}/dependentSchemas`;if(X in e){let _e=st(e,oe[X],n,r,s,a,i,`${W}/${Gn(X)}`,c);_e.valid||V.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:W,error:`Instance has "${X}" but does not match dependant schema.`},..._e.errors)}}if(ne!==void 0){let X=`${o}/dependencies`;for(let W in ne)if(W in e){let _e=ne[W];if(Array.isArray(_e))for(let ye of _e)ye in e||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:X,error:`Instance has "${W}" but does not have "${ye}".`});else{let ye=st(e,_e,n,r,s,a,i,`${X}/${Gn(W)}`);ye.valid||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:X,error:`Instance has "${W}" but does not match dependant schema.`},...ye.errors)}}}let ce=Object.create(null),Ae=!1;if(A!==void 0){let X=`${o}/properties`;for(let W in A){if(!(W in e))continue;let _e=`${i}/${Gn(W)}`,ye=st(e[W],A[W],n,r,s,a,_e,`${X}/${Gn(W)}`);if(ye.valid)c[W]=ce[W]=!0;else if(Ae=s,V.push({instanceLocation:i,keyword:"properties",keywordLocation:X,error:`Property "${W}" does not match schema.`},...ye.errors),Ae)break}}if(!Ae&&Z!==void 0){let X=`${o}/patternProperties`;for(let W in Z){let _e=new RegExp(W,"u"),ye=Z[W];for(let on in e){if(!_e.test(on))continue;let zE=`${i}/${Gn(on)}`,n0=st(e[on],ye,n,r,s,a,zE,`${X}/${Gn(W)}`);n0.valid?c[on]=ce[on]=!0:(Ae=s,V.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:X,error:`Property "${on}" matches pattern "${W}" but does not match associated schema.`},...n0.errors))}}}if(!Ae&&ze!==void 0){let X=`${o}/additionalProperties`;for(let W in e){if(ce[W])continue;let _e=`${i}/${Gn(W)}`,ye=st(e[W],ze,n,r,s,a,_e,X);ye.valid?c[W]=!0:(Ae=s,V.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:X,error:`Property "${W}" does not match additional properties schema.`},...ye.errors))}}else if(!Ae&&rt!==void 0){let X=`${o}/unevaluatedProperties`;for(let W in e)if(!c[W]){let _e=`${i}/${Gn(W)}`,ye=st(e[W],rt,n,r,s,a,_e,X);ye.valid?c[W]=!0:V.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:X,error:`Property "${W}" does not match unevaluated properties schema.`},...ye.errors)}}}else if(l==="array"){C!==void 0&&e.length>C&&V.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${C}).`}),_!==void 0&&e.length<_&&V.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${_}).`});let he=e.length,ce=0,Ae=!1;if(ue!==void 0){let X=`${o}/prefixItems`,W=Math.min(ue.length,he);for(;ce<W;ce++){let _e=st(e[ce],ue[ce],n,r,s,a,`${i}/${ce}`,`${X}/${ce}`);if(c[ce]=!0,!_e.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:X,error:"Items did not match schema."},..._e.errors),Ae))break}}if(Oe!==void 0){let X=`${o}/items`;if(Array.isArray(Oe)){let W=Math.min(Oe.length,he);for(;ce<W;ce++){let _e=st(e[ce],Oe[ce],n,r,s,a,`${i}/${ce}`,`${X}/${ce}`);if(c[ce]=!0,!_e.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"items",keywordLocation:X,error:"Items did not match schema."},..._e.errors),Ae))break}}else for(;ce<he;ce++){let W=st(e[ce],Oe,n,r,s,a,`${i}/${ce}`,X);if(c[ce]=!0,!W.valid&&(Ae=s,V.push({instanceLocation:i,keyword:"items",keywordLocation:X,error:"Items did not match schema."},...W.errors),Ae))break}if(!Ae&&Te!==void 0){let W=`${o}/additionalItems`;for(;ce<he;ce++){let _e=st(e[ce],Te,n,r,s,a,`${i}/${ce}`,W);c[ce]=!0,_e.valid||(Ae=s,V.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:W,error:"Items did not match additional items schema."},..._e.errors))}}}if(De!==void 0)if(he===0&&kt===void 0)V.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(kt!==void 0&&he<kt)V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${he}) than minContains (${kt}).`});else{let X=`${o}/contains`,W=V.length,_e=0;for(let ye=0;ye<he;ye++){let on=st(e[ye],De,n,r,s,a,`${i}/${ye}`,X);on.valid?(c[ye]=!0,_e++):V.push(...on.errors)}_e>=(kt||0)&&(V.length=W),kt===void 0&&b===void 0&&_e===0?V.splice(W,0,{instanceLocation:i,keyword:"contains",keywordLocation:X,error:"Array does not contain item matching schema."}):kt!==void 0&&_e<kt?V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${kt} items matching schema. Only ${_e} items were found.`}):b!==void 0&&_e>b&&V.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${b} items matching schema. ${_e} items were found.`})}if(!Ae&&Ue!==void 0){let X=`${o}/unevaluatedItems`;for(ce;ce<he;ce++){if(c[ce])continue;let W=st(e[ce],Ue,n,r,s,a,`${i}/${ce}`,X);c[ce]=!0,W.valid||V.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:X,error:"Items did not match unevaluated items schema."},...W.errors)}}if(O)for(let X=0;X<he;X++){let W=e[X],_e=typeof W=="object"&&W!==null;for(let ye=0;ye<he;ye++){if(X===ye)continue;let on=e[ye];(W===on||_e&&typeof on=="object"&&on!==null&&oa(W,on))&&(V.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${X} and ${ye}.`}),X=Number.MAX_SAFE_INTEGER,ye=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(Ne!==void 0&&(yt===!0&&e<=Ne||e<Ne)&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${yt?"or equal to ":""} ${Ne}.`}),Je!==void 0&&(pt===!0&&e>=Je||e>Je)&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${pt?"or equal to ":""} ${Je}.`})):(Ne!==void 0&&e<Ne&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${Ne}.`}),Je!==void 0&&e>Je&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Je}.`}),yt!==void 0&&e<=yt&&V.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${yt}.`}),pt!==void 0&&e>=pt&&V.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${pt}.`})),Lt!==void 0){let he=e%Lt;Math.abs(0-he)>=11920929e-14&&Math.abs(Lt-he)>=11920929e-14&&V.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${Lt}.`})}}else if(l==="string"){let he=Cn===void 0&&ht===void 0?0:RM(e);Cn!==void 0&&he<Cn&&V.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${he} < ${Cn}).`}),ht!==void 0&&he>ht&&V.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${he} > ${ht}).`}),dr!==void 0&&!new RegExp(dr,"u").test(e)&&V.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),P!==void 0&&eb[P]&&!eb[P](e)&&V.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${P}".`})}return{valid:V.length===0,errors:V}}var Qm=class{schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=cs(t)}validate(t){return st(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),cs(t,this.lookup)}},MM=Q({Validator:()=>Qm,deepCompareStrict:()=>oa,toJsonSchema:()=>It,validatesOnlyStrings:()=>Bo});function It(e,t){if(Dy(e)&&!nt(e))return e["~standard"].jsonSchema.input({target:"draft-07"});if(nt(e)){let n=qx(e,!0);return xr(n)?Cw(zl(n,!0),t):Cw(e,t)}return gt(e)?iM(e):e}function Bo(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Bo(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>Bo(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,n=cs(e);return n[t]?Bo(n[t]):!1}return!1}function Wy(e){return e?e.lc_runnable:!1}var LM=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||r.some(s=>this.includeTags?.includes(s))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&r.every(s=>!this.excludeTags?.includes(s))),n}},zM=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function kf(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var UM=["*","_","`"];function DM(e){let t="";for(let[n,r]of Object.entries(e))t+=` classDef ${n} ${r};
73
73
  `;return t}function FM(e,t,n){let{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{},u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
74
74
  graph TD;
75
75
  `:`graph TD;
@@ -158,7 +158,7 @@ Here are the output tags:
158
158
  {tags}
159
159
  \`\`\``,i4=class extends Kc{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?Ap(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return ig(e[0].text)}async parse(e){return ig(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?ag.replace("{tags}",this.tags?.join(", ")??""):ag}},o4=e=>e.split(`
160
160
  `).map(t=>t.replace(/^\s+/,"")).join(`
161
- `).trim(),LO=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(LO),t):(t[e.name]=e.text??void 0,t)};function ig(e){let t=o4(e),n=a4.parser(!0),r={},s=[];n.onopentag=o=>{let c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){let o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){let c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){let c=s[s.length-1];c.attributes[o.name]=o.value}};let a=/```(xml)?(.*)```/s.exec(t),i=a?a[2]:t;return n.write(i).close(),r&&r.name==="?xml"&&(r=r.children[0]),LO(r)}var c4=Q({AsymmetricStructuredOutputParser:()=>r4,BaseCumulativeTransformOutputParser:()=>Kc,BaseLLMOutputParser:()=>Up,BaseOutputParser:()=>so,BaseTransformOutputParser:()=>Gc,BytesOutputParser:()=>XL,CommaSeparatedListOutputParser:()=>YL,CustomListOutputParser:()=>QL,JsonMarkdownStructuredOutputParser:()=>MO,JsonOutputParser:()=>i_,ListOutputParser:()=>Xc,MarkdownListOutputParser:()=>t4,NumberedListOutputParser:()=>e4,OutputParserException:()=>sr,StandardSchemaOutputParser:()=>RO,StringOutputParser:()=>n4,StructuredOutputParser:()=>o_,XMLOutputParser:()=>i4,XML_FORMAT_INSTRUCTIONS:()=>ag,parseJsonMarkdown:()=>Al,parsePartialJson:()=>wi,parseXMLMarkdown:()=>ig}),u4=Q({extendInteropZodObject:()=>Bx,getInteropZodDefaultGetter:()=>Zx,getInteropZodObjectShape:()=>rc,getSchemaDescription:()=>Ti,interopParse:()=>al,interopParseAsync:()=>Pp,interopSafeParse:()=>qR,interopSafeParseAsync:()=>Ux,interopZodObjectMakeFieldsOptional:()=>JR,interopZodObjectPartial:()=>Vy,interopZodObjectPassthrough:()=>Dm,interopZodObjectStrict:()=>zl,interopZodTransformInputSchema:()=>qx,isInteropZodError:()=>Vx,isInteropZodLiteral:()=>ZR,isInteropZodObject:()=>Pn,isInteropZodSchema:()=>En,isShapelessZodSchema:()=>VR,isSimpleStringZodSchema:()=>Zy,isZodArrayV4:()=>jp,isZodLiteralV3:()=>Lx,isZodLiteralV4:()=>zx,isZodNullableV4:()=>Fx,isZodObjectV3:()=>qy,isZodObjectV4:()=>xr,isZodOptionalV4:()=>Dx,isZodSchema:()=>BR,isZodSchemaV3:()=>mt,isZodSchemaV4:()=>nt});function Dp(e,t){if(e.function===void 0)return;let n;if(t?.partial)try{n=wi(e.function.arguments??"{}")}catch{return}else try{n=JSON.parse(e.function.arguments)}catch(s){throw new sr([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
161
+ `).trim(),LO=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(LO),t):(t[e.name]=e.text??void 0,t)};function ig(e){let t=o4(e),n=a4.parser(!0),r={},s=[];n.onopentag=o=>{let c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){let o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){let c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){let c=s[s.length-1];c.attributes[o.name]=o.value}};let a=/```(xml)?(.*)```/s.exec(t),i=a?a[2]:t;return n.write(i).close(),r&&r.name==="?xml"&&(r=r.children[0]),LO(r)}var c4=Q({AsymmetricStructuredOutputParser:()=>r4,BaseCumulativeTransformOutputParser:()=>Kc,BaseLLMOutputParser:()=>Up,BaseOutputParser:()=>so,BaseTransformOutputParser:()=>Gc,BytesOutputParser:()=>XL,CommaSeparatedListOutputParser:()=>YL,CustomListOutputParser:()=>QL,JsonMarkdownStructuredOutputParser:()=>MO,JsonOutputParser:()=>i_,ListOutputParser:()=>Xc,MarkdownListOutputParser:()=>t4,NumberedListOutputParser:()=>e4,OutputParserException:()=>sr,StandardSchemaOutputParser:()=>RO,StringOutputParser:()=>n4,StructuredOutputParser:()=>o_,XMLOutputParser:()=>i4,XML_FORMAT_INSTRUCTIONS:()=>ag,parseJsonMarkdown:()=>Al,parsePartialJson:()=>wi,parseXMLMarkdown:()=>ig}),u4=Q({extendInteropZodObject:()=>Bx,getInteropZodDefaultGetter:()=>Zx,getInteropZodObjectShape:()=>rc,getSchemaDescription:()=>Ti,interopParse:()=>al,interopParseAsync:()=>Pp,interopSafeParse:()=>qR,interopSafeParseAsync:()=>Ux,interopZodObjectMakeFieldsOptional:()=>JR,interopZodObjectPartial:()=>Vy,interopZodObjectPassthrough:()=>Dm,interopZodObjectStrict:()=>zl,interopZodTransformInputSchema:()=>qx,isInteropZodError:()=>Vx,isInteropZodLiteral:()=>ZR,isInteropZodObject:()=>Pn,isInteropZodSchema:()=>En,isShapelessZodSchema:()=>VR,isSimpleStringZodSchema:()=>Zy,isZodArrayV4:()=>jp,isZodLiteralV3:()=>Lx,isZodLiteralV4:()=>zx,isZodNullableV4:()=>Fx,isZodObjectV3:()=>qy,isZodObjectV4:()=>xr,isZodOptionalV4:()=>Dx,isZodSchema:()=>BR,isZodSchemaV3:()=>gt,isZodSchemaV4:()=>nt});function Dp(e,t){if(e.function===void 0)return;let n;if(t?.partial)try{n=wi(e.function.arguments??"{}")}catch{return}else try{n=JSON.parse(e.function.arguments)}catch(s){throw new sr([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
162
162
  `))}let r={name:e.function.name,args:n,type:"tool_call"};return t?.returnId&&(r.id=e.id),r}function zO(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function Zo(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var UO=class extends Kc{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let n=e[0].message,r;if(kp(n)&&n.tool_calls?.length?r=n.tool_calls.map(a=>{let{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(a=>Dp(a,{returnId:this.returnId,partial:t}))),!r)return[];let s=[];for(let a of r)if(a!==void 0){let i={type:a.name,args:a.args,id:a.id};s.push(i)}return s}},DO=class extends UO{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}async _validateResult(e){if(this.serializableSchema!==void 0){let n=await this.serializableSchema["~standard"].validate(e);if(n.issues)throw new sr(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.issues)}`,JSON.stringify(e,null,2));return n.value}if(this.zodSchema===void 0)return e;let t=await Ux(this.zodSchema,e);if(t.success)return t.data;throw new sr(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let t=(await super.parsePartialResult(e)).filter(r=>r.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(r=>r.args)),this.returnSingle?n[0]:n}async parseResult(e){let t=(await super.parsePartialResult(e,!1)).filter(r=>r.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(r=>r.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(r=>this._validateResult(r)))}},l4=Q({assembleStructuredOutputPipeline:()=>c_,createContentParser:()=>og,createFunctionCallingParser:()=>FO});function og(e){return En(e)?o_.fromZodSchema(e):ha(e)?RO.fromSerializableSchema(e):new i_}function FO(e,t,n){let r=n??DO;return En(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):ha(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function c_(e,t,n,r){if(!n){let c=e.pipe(t);return r?c.withConfig({runName:r}):c}let s=ic.assign({parsed:(c,u)=>t.invoke(c.raw,u)}),a=ic.assign({parsed:()=>null}),i=s.withFallbacks({fallbacks:[a]}),o=Ts.from([{raw:e},i]);return r?o.withConfig({runName:r}):o}var d4=e=>e();function Of(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}function mi(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t!=="tools"&&n!==null&&n!==void 0))}var p4=Q({BaseChatModel:()=>Pa,SimpleChatModel:()=>h4});function Sf(e){let t=[];for(let n of e){let r=n;if(Array.isArray(n.content))for(let s=0;s<n.content.length;s++){let a=n.content[s];(my(a)||gy(a))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),wk(a),...n.content.slice(s+1)]}))}t.push(r)}return t}var Pa=class Vs extends a_{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=d4(()=>{let n=t.outputVersion??rr("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){let[n,r]=super._separateRunnableConfigFromCallOptions(t);return r.signal=n.signal,[n,r]}async invoke(t,n){let r=Vs._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,n,r){throw new Error("Not implemented.")}async*_streamIterator(t,n){if(this._streamResponseChunks===Vs.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{let r=Vs._convertInputToPromptValue(t).toChatMessages(),[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i={...s.metadata,...this.getLsParams(a)},o=this?.invocationParams(a),c=mi(o),u=en.configure(s.callbacks,this.callbacks,s.tags,this.tags,i,{...c,...this.metadata},{verbose:this.verbose}),l={options:a,invocation_params:o,batch_size:1},d=a.outputVersion??this.outputVersion,p=await u?.handleChatModelStart(this.toJSON(),[Sf(r)],s.runId,void 0,l,void 0,void 0,s.runName),h,f;try{for await(let m of this._streamResponseChunks(r,a,p?.[0])){if(a.signal?.throwIfAborted(),m.message.id==null){let v=p?.at(0)?.runId;v!=null&&m.message._updateId(`run-${v}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata},d==="v1"?yield Of(m.message):yield m.message,h?h=h.concat(m):h=m,cm(m.message)&&m.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}a.signal?.throwIfAborted()}catch(m){throw await Promise.all((p??[]).map(v=>v?.handleLLMError(m))),m}await Promise.all((p??[]).map(m=>m?.handleLLMEnd({generations:[[h]],llmOutput:f})))}}getLsParams(t){let n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:n}}async _generateUncached(t,n,r,s){let a=t.map(d=>d.map(kr)),i;if(s!==void 0&&s.length===a.length)i=s;else{let d={...r.metadata,...this.getLsParams(n)},p=this?.invocationParams(n),h=mi(p),f=en.configure(r.callbacks,this.callbacks,r.tags,this.tags,d,{...h,...this.metadata},{verbose:this.verbose}),m={options:n,invocation_params:p,batch_size:1};i=await f?.handleChatModelStart(this.toJSON(),a.map(Sf),r.runId,void 0,m,void 0,void 0,r.runName)}let o=n.outputVersion??this.outputVersion,c=[],u=[];if(i?.[0].handlers.find(Ey)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==Vs.prototype._streamResponseChunks)try{let d=await this._streamResponseChunks(a[0],n,i?.[0]),p,h;for await(let f of d){if(n.signal?.aborted){let m=p?.message;throw new im("Model invocation was aborted.",m)}if(f.message.id==null){let m=i?.at(0)?.runId;m!=null&&f.message._updateId(`run-${m}`)}p===void 0?p=f:p=ks(p,f),cm(f.message)&&f.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}if(n.signal?.aborted){let f=p?.message;throw new im("Model invocation was aborted.",f)}if(p===void 0)throw new Error("Received empty response from chat model call.");c.push([p]),await i?.[0].handleLLMEnd({generations:c,llmOutput:h})}catch(d){throw await i?.[0].handleLLMError(d),d}else{let d=await Promise.allSettled(a.map(async(p,h)=>{let f=await this._generate(p,{...n,promptIndex:h},i?.[h]);if(o==="v1")for(let m of f.generations)m.message=Of(m.message);return f}));await Promise.all(d.map(async(p,h)=>{if(p.status==="fulfilled"){let f=p.value;for(let m of f.generations){if(m.message.id==null){let v=i?.at(0)?.runId;v!=null&&m.message._updateId(`run-${v}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata}}return f.generations.length===1&&(f.generations[0].message.response_metadata={...f.llmOutput,...f.generations[0].message.response_metadata}),c[h]=f.generations,u[h]=f.llmOutput,i?.[h]?.handleLLMEnd({generations:[f.generations],llmOutput:f.llmOutput})}else return await i?.[h]?.handleLLMError(p.reason),Promise.reject(p.reason)}))}let l={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(l,nc,{value:i?{runIds:i?.map(d=>d.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:t,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a}){let i=t.map(y=>y.map(kr)),o={...a.metadata,...this.getLsParams(s)},c=this?.invocationParams(s),u=mi(c),l=en.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,{...u,...this.metadata},{verbose:this.verbose}),d={options:s,invocation_params:c,batch_size:1},p=await l?.handleChatModelStart(this.toJSON(),i.map(Sf),a.runId,void 0,d,void 0,void 0,a.runName),h=[],f=(await Promise.allSettled(i.map(async(y,k)=>{let x=Vs._convertInputToPromptValue(y).toString(),S=await n.lookup(x,r);return S==null&&h.push(k),S}))).map((y,k)=>({result:y,runManager:p?.[k]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),m=s.outputVersion??this.outputVersion,v=[];await Promise.all(f.map(async({result:y,runManager:k},x)=>{if(y.status==="fulfilled"){let S=y.value;return v[x]=S.map(E=>("message"in E&&jt(E.message)&&kp(E.message)&&(E.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m==="v1"&&(E.message=Of(E.message))),E.generationInfo={...E.generationInfo,tokenUsage:{}},E)),S.length&&await k?.handleLLMNewToken(S[0].text),k?.handleLLMEnd({generations:[S]},void 0,void 0,void 0,{cached:!0})}else return await k?.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(y.reason)}));let g={generations:v,missingPromptIndices:h,startedRunManagers:p};return Object.defineProperty(g,nc,{value:p?{runIds:p?.map(y=>y.runId)}:void 0,configurable:!0}),g}async generate(t,n,r){let s;Array.isArray(n)?s={stop:n}:s=n;let a=t.map(f=>f.map(kr)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(a,o,i);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:p}=await this._generateCached({messages:a,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i}),h={};if(d.length>0){let f=await this._generateUncached(d.map(m=>a[m]),o,i,p!==void 0?d.map(m=>p?.[m]):void 0);await Promise.all(f.generations.map(async(m,v)=>{let g=d[v];l[g]=m;let y=Vs._convertInputToPromptValue(a[g]).toString();return c.update(y,u,m)})),h=f.llmOutput??{}}return{generations:l,llmOutput:h}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,n,r){let s=t.map(a=>a.toChatMessages());return this.generate(s,n,r)}withStructuredOutput(t,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');let r=t,s=n?.name,a=Ti(r)??"A function available to call.",i=n?.method,o=n?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=s??"extract";!En(r)&&!ha(r)&&"name"in r&&(c=r.name);let u=En(r)||ha(r)?It(r):r,l=[{type:"function",function:{name:c,description:a,parameters:u}}];return c_(this.bindTools(l),lr.from(d=>{if(!mn.isInstance(d))throw new Error("Input is not an AIMessageChunk.");if(!d.tool_calls||d.tool_calls.length===0)throw new Error("No tool calls found in the response.");let p=d.tool_calls.find(h=>h.name===c);if(!p)throw new Error(`No tool call found with name ${c}.`);return p.args}),o,o?"StructuredOutputRunnable":"StructuredOutput")}},h4=class extends Pa{async _generate(e,t,n){let r=new Ke(await this._call(e,t,n));if(typeof r.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:r.content,message:r}]}}},f4=Q({BaseLLM:()=>BO,LLM:()=>u_}),BO=class bo extends a_{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,n){let r=bo._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,n,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){let[n,r]=super._separateRunnableConfigFromCallOptions(t);return r.signal=n.signal,[n,r]}async*_streamIterator(t,n){if(this._streamResponseChunks===bo.prototype._streamResponseChunks)yield this.invoke(t,n);else{let r=bo._convertInputToPromptValue(t),[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=this?.invocationParams(a),o=mi(i),c=en.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,{...o,...this.metadata},{verbose:this.verbose}),u={options:a,invocation_params:i,batch_size:1},l=await c?.handleLLMStart(this.toJSON(),[r.toString()],s.runId,void 0,u,void 0,void 0,s.runName),d=new Si({text:""});try{for await(let p of this._streamResponseChunks(r.toString(),a,l?.[0]))d?d=d.concat(p):d=p,typeof p.text=="string"&&(yield p.text)}catch(p){throw await Promise.all((l??[]).map(h=>h?.handleLLMError(p))),p}await Promise.all((l??[]).map(p=>p?.handleLLMEnd({generations:[[d]]})))}}async generatePrompt(t,n,r){let s=t.map(a=>a.toString());return this.generate(s,n,r)}invocationParams(t){return{}}_flattenLLMResult(t){let n=[];for(let r=0;r<t.generations.length;r+=1){let s=t.generations[r];if(r===0)n.push({generations:[s],llmOutput:t.llmOutput});else{let a=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[s],llmOutput:a})}}return n}async _generateUncached(t,n,r,s){let a;if(s!==void 0&&s.length===t.length)a=s;else{let u=this?.invocationParams(n),l=mi(u),d=en.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,{...l,...this.metadata},{verbose:this.verbose}),p={options:n,invocation_params:u,batch_size:t.length};a=await d?.handleLLMStart(this.toJSON(),t,r.runId,void 0,p,void 0,void 0,r?.runName)}let i=!!a?.[0].handlers.find(Ey),o;if(i&&t.length===1&&this._streamResponseChunks!==bo.prototype._streamResponseChunks)try{let u=await this._streamResponseChunks(t[0],n,a?.[0]),l;for await(let d of u)l===void 0?l=d:l=ks(l,d);if(l===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[l]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(u){throw await a?.[0].handleLLMError(u),u}else{try{o=await this._generate(t,n,a?.[0])}catch(l){throw await Promise.all((a??[]).map(d=>d?.handleLLMError(l))),l}let u=this._flattenLLMResult(o);await Promise.all((a??[]).map((l,d)=>l?.handleLLMEnd(u[d])))}let c=a?.map(u=>u.runId)||void 0;return Object.defineProperty(o,nc,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:t,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a,runId:i}){let o=this?.invocationParams(s),c=mi(o),u=en.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,{...c,...this.metadata},{verbose:this.verbose}),l={options:s,invocation_params:o,batch_size:t.length},d=await u?.handleLLMStart(this.toJSON(),t,i,void 0,l,void 0,void 0,a?.runName),p=[],h=(await Promise.allSettled(t.map(async(v,g)=>{let y=await n.lookup(v,r);return y==null&&p.push(g),y}))).map((v,g)=>({result:v,runManager:d?.[g]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),f=[];await Promise.all(h.map(async({result:v,runManager:g},y)=>{if(v.status==="fulfilled"){let k=v.value;return f[y]=k.map(x=>(x.generationInfo={...x.generationInfo,tokenUsage:{}},x)),k.length&&await g?.handleLLMNewToken(k[0].text),g?.handleLLMEnd({generations:[k]},void 0,void 0,void 0,{cached:!0})}else return await g?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));let m={generations:f,missingPromptIndices:p,startedRunManagers:d};return Object.defineProperty(m,nc,{value:d?{runIds:d?.map(v=>v.runId)}:void 0,configurable:!0}),m}async generate(t,n,r){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let s;Array.isArray(n)?s={stop:n}:s=n;let[a,i]=this._separateRunnableConfigFromCallOptionsCompat(s);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(t,i,a);let{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:u,missingPromptIndices:l,startedRunManagers:d}=await this._generateCached({prompts:t,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a,runId:a.runId}),p={};if(l.length>0){let h=await this._generateUncached(l.map(f=>t[f]),i,a,d!==void 0?l.map(f=>d?.[f]):void 0);await Promise.all(h.generations.map(async(f,m)=>{let v=l[m];return u[v]=f,o.update(t[v],c,f)})),p=h.llmOutput??{}}return{generations:u,llmOutput:p}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},u_=class extends BO{async _generate(e,t,n){return{generations:await Promise.all(e.map((r,s)=>this._call(r,{...t,promptIndex:s},n).then(a=>[{text:a}])))}}},m4=Q({}),g4=Q({BaseMemory:()=>y4,getInputValue:()=>_4,getOutputValue:()=>v4,getPromptInputKey:()=>w4}),y4=class{},ZO=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},_4=(e,t)=>{let n=ZO(e,t);if(!n){let r=Object.keys(e);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},v4=(e,t)=>{let n=ZO(e,t);if(!n&&n!==""){let r=Object.keys(e);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function w4(e,t){let n=Object.keys(e).filter(r=>!t.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var qO=class extends Up{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},VO=class extends Kc{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new qO(e)}_diff(e,t){if(t)return Ap(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?wi(r.arguments):{...r,arguments:wi(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},b4=class extends Up{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new VO;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},k4=Q({JsonKeyOutputFunctionsParser:()=>b4,JsonOutputFunctionsParser:()=>VO,OutputFunctionsParser:()=>qO}),x4=Q({JsonOutputKeyToolsParser:()=>DO,JsonOutputToolsParser:()=>UO,convertLangChainToolCallToOpenAI:()=>zO,makeInvalidToolCall:()=>Zo,parseToolCall:()=>Dp}),Yc=class extends je{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[r,s]of Object.entries(t))typeof s=="string"?n[r]=s:n[r]=await s();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),e,{...t,tags:r,metadata:n,runType:"prompt"})}},oc=class extends Yc{async formatPromptValue(e){return new e_(await this.format(e))}},O4=Object.prototype.toString,ao=Array.isArray||function(e){return O4.call(e)==="[object Array]"};function l_(e){return typeof e=="function"}function S4(e){return ao(e)?"array":typeof e}function Tf(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function db(e,t){return e!=null&&typeof e=="object"&&t in e}function T4(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var I4=RegExp.prototype.test;function E4(e,t){return I4.call(e,t)}var A4=/\S/;function $4(e){return!E4(A4,e)}var C4={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function N4(e){return String(e).replace(/[&<>"'`=\/]/g,function(t){return C4[t]})}var P4=/\s*/,j4=/\s+/,pb=/\s*=/,R4=/\s*\}/,M4=/#|\^|\/|>|\{|&|=|!/;function L4(e,t){if(!e)return[];var n=!1,r=[],s=[],a=[],i=!1,o=!1,c="",u=0;function l(){if(i&&!o)for(;a.length;)delete s[a.pop()];else a=[];i=!1,o=!1}var d,p,h;function f(w){if(typeof w=="string"&&(w=w.split(j4,2)),!ao(w)||w.length!==2)throw new Error("Invalid tags: "+w);d=new RegExp(Tf(w[0])+"\\s*"),p=new RegExp("\\s*"+Tf(w[1])),h=new RegExp("\\s*"+Tf("}"+w[1]))}f(t||_n.tags);for(var m=new Qc(e),v,g,y,k,x,S;!m.eos();){if(v=m.pos,y=m.scanUntil(d),y)for(var E=0,I=y.length;E<I;++E)k=y.charAt(E),$4(k)?(a.push(s.length),c+=k):(o=!0,n=!0,c+=" "),s.push(["text",k,v,v+1]),v+=1,k===`
163
163
  `&&(l(),c="",u=0,n=!1);if(!m.scan(d))break;if(i=!0,g=m.scan(M4)||"name",m.scan(P4),g==="="?(y=m.scanUntil(pb),m.scan(pb),m.scanUntil(p)):g==="{"?(y=m.scanUntil(h),m.scan(R4),m.scanUntil(p),g="&"):y=m.scanUntil(p),!m.scan(p))throw new Error("Unclosed tag at "+m.pos);if(g==">"?x=[g,y,v,m.pos,c,u,n]:x=[g,y,v,m.pos],u++,s.push(x),g==="#"||g==="^")r.push(x);else if(g==="/"){if(S=r.pop(),!S)throw new Error('Unopened section "'+y+'" at '+v);if(S[1]!==y)throw new Error('Unclosed section "'+S[1]+'" at '+v)}else g==="name"||g==="{"||g==="&"?o=!0:g==="="&&f(y)}if(l(),S=r.pop(),S)throw new Error('Unclosed section "'+S[1]+'" at '+m.pos);return U4(z4(s))}function z4(e){for(var t=[],n,r,s=0,a=e.length;s<a;++s)n=e[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function U4(e){for(var t=[],n=t,r=[],s,a,i=0,o=e.length;i<o;++i)switch(s=e[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":a=r.pop(),a[5]=s[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(s)}return t}function Qc(e){this.string=e,this.tail=e,this.pos=0}Qc.prototype.eos=function(){return this.tail===""};Qc.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Qc.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function Ci(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ci.prototype.push=function(e){return new Ci(e,this)};Ci.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var r=this,s,a,i,o=!1;r;){if(e.indexOf(".")>0)for(s=r.view,a=e.split("."),i=0;s!=null&&i<a.length;)i===a.length-1&&(o=db(s,a[i])||T4(s,a[i])),s=s[a[i++]];else s=r.view[e],o=db(r.view,e);if(o){n=s;break}r=r.parent}t[e]=n}return l_(n)&&(n=n.call(this.view)),n};function sn(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}sn.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};sn.prototype.parse=function(e,t){var n=this.templateCache,r=e+":"+(t||_n.tags).join(":"),s=typeof n<"u",a=s?n.get(r):void 0;return a==null&&(a=L4(e,t),s&&n.set(r,a)),a};sn.prototype.render=function(e,t,n,r){var s=this.getConfigTags(r),a=this.parse(e,s),i=t instanceof Ci?t:new Ci(t,void 0);return this.renderTokens(a,i,n,e,r)};sn.prototype.renderTokens=function(e,t,n,r,s){for(var a="",i,o,c,u=0,l=e.length;u<l;++u)c=void 0,i=e[u],o=i[0],o==="#"?c=this.renderSection(i,t,n,r,s):o==="^"?c=this.renderInverted(i,t,n,r,s):o===">"?c=this.renderPartial(i,t,n,s):o==="&"?c=this.unescapedValue(i,t):o==="name"?c=this.escapedValue(i,t,s):o==="text"&&(c=this.rawValue(i)),c!==void 0&&(a+=c);return a};sn.prototype.renderSection=function(e,t,n,r,s){var a=this,i="",o=t.lookup(e[1]);function c(d){return a.render(d,t,n,s)}if(o){if(ao(o))for(var u=0,l=o.length;u<l;++u)i+=this.renderTokens(e[4],t.push(o[u]),n,r,s);else if(typeof o=="object"||typeof o=="string"||typeof o=="number")i+=this.renderTokens(e[4],t.push(o),n,r,s);else if(l_(o)){if(typeof r!="string")throw new Error("Cannot use higher-order sections without the original template");o=o.call(t.view,r.slice(e[3],e[5]),c),o!=null&&(i+=o)}else i+=this.renderTokens(e[4],t,n,r,s);return i}};sn.prototype.renderInverted=function(e,t,n,r,s){var a=t.lookup(e[1]);if(!a||ao(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,s)};sn.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,""),s=e.split(`
164
164
  `),a=0;a<s.length;a++)s[a].length&&(a>0||!n)&&(s[a]=r+s[a]);return s.join(`
@@ -253,7 +253,7 @@ ${r}`)}return e}function Tz(e){let t=e.split(`
253
253
  `)}var Iz=Q({EventStreamContentType:()=>Ez,convertEventStreamToIterableReadableDataStream:()=>$z,getBytes:()=>SS,getLines:()=>TS,getMessages:()=>IS}),Ez="text/event-stream";async function SS(e,t){if(e instanceof ReadableStream){let n=e.getReader();for(;;){let r=await n.read();if(r.done){t(new Uint8Array,!0);break}t(r.value)}}else try{for await(let n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
254
254
  `))}}var oi=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(oi||{});function TS(e){let t,n,r,s=!1;return function(a,i){if(i){e(a,0,!0);return}t===void 0?(t=a,n=0,r=-1):t=Az(t,a);let o=t.length,c=0;for(;n<o;){s&&(t[n]===oi.NewLine&&(c=++n),s=!1);let u=-1;for(;n<o&&u===-1;++n)switch(t[n]){case oi.Colon:r===-1&&(r=n-c);break;case oi.CarriageReturn:s=!0;case oi.NewLine:u=n;break}if(u===-1)break;e(t.subarray(c,u),r),c=n,r=-1}c===o?t=void 0:c!==0&&(t=t.subarray(c),n-=c)}}function IS(e,t,n){let r=If(),s=new TextDecoder;return function(a,i,o){if(o){Cz(r)||(e?.(r),r=If());return}if(a.length===0)e?.(r),r=If();else if(i>0){let c=s.decode(a.subarray(0,i)),u=i+(a[i+1]===oi.Space?2:1),l=s.decode(a.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
255
255
  `+l:l;break;case"event":r.event=l;break;case"id":t?.(r.id=l);break;case"retry":{let d=parseInt(l,10);Number.isNaN(d)||n?.(r.retry=d);break}}}}}function Az(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function If(){return{data:"",event:"",id:"",retry:void 0}}function $z(e,t){let n=new ReadableStream({async start(r){let s=IS(a=>{if(a.event==="error")throw new Error(a.data??"Unspecified event streaming error.");a.event==="metadata"?t?.(a):a.data&&r.enqueue(a.data)});await SS(e,TS((a,i,o)=>{s(a,i,o),o&&r.close()}))}});return gn.fromReadableStream(n)}function Cz(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var Nz=Q({}),Pz=Q({convertToOpenAIFunction:()=>ES,convertToOpenAITool:()=>AS,isLangChainTool:()=>tu,isRunnableToolLike:()=>b_,isStructuredTool:()=>w_,isStructuredToolParams:()=>k_});function ES(e,t){let n=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:It(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function AS(e,t){let n=typeof t=="number"?void 0:t,r;return tu(e)?r={type:"function",function:ES(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function $S(e,t){let n=0,r=0,s=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],s+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(s))}function jz(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function Rz(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function Mz(e,t){return Math.sqrt(Rz(e,t))}var Lz=Q({cosineSimilarity:()=>hg,euclideanDistance:()=>Dz,innerProduct:()=>Uz,matrixFunc:()=>Vp,maximalMarginalRelevance:()=>Fz,normalize:()=>zz});function Vp(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(r=>t.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function zz(e,t=!1){let n=Bz(e);return e.map(r=>r.map(s=>t?1-s/n:s/n))}function hg(e,t){return Vp(e,t,$S)}function Uz(e,t){return Vp(e,t,jz)}function Dz(e,t){return Vp(e,t,Mz)}function Fz(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let s=hg(Array.isArray(e[0])?e:[e],t)[0],a=CS(s).maxIndex,i=[t[a]],o=[a];for(;o.length<Math.min(r,t.length);){let c=-1/0,u=-1,l=hg(t,i);s.forEach((d,p)=>{if(o.includes(p))return;let h=Math.max(...l[p]),f=n*d-(1-n)*h;f>c&&(c=f,u=p)}),i.push(t[u]),o.push(u)}return o}function CS(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function Bz(e){return e.reduce((t,n)=>Math.max(t,CS(n).maxValue),0)}var Zz=Q({isCloudMetadata:()=>fg,isLocalhost:()=>mg,isPrivateIp:()=>MS,isSafeUrl:()=>Xz,isSameOrigin:()=>Yz,validateSafeUrl:()=>LS}),qz=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],Vz=["169.254.169.254","169.254.170.2","100.100.100.200"],Hz=["metadata.google.internal","metadata","instance-data"],Wz=["localhost","localhost.localdomain"],Jz=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function NS(e){return Jz.test(e)}function Hp(e){return RS(e)!==null}function PS(e){return NS(e)||Hp(e)}function jS(e){if(NS(e))return e.split(".").map(t=>parseInt(t,10));if(Hp(e)){let t=RS(e);if(!t)return null;let n=t.split(":"),r=[];for(let s of n)r.push(parseInt(s,16));return r}return null}function RS(e){if(!e||typeof e!="string"||!e.includes(":")||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes("::")){let r=t.split("::");if(r.length>2)return null;let[s,a]=r,i=s?s.split(":"):[],o=a?a.split(":"):[],c=8-(i.length+o.length);if(c<0)return null;let u=Array(c).fill("0");t=[...i,...u,...o].filter(l=>l!=="").join(":")}let n=t.split(":");if(n.length!==8)return null;for(let r of n)if(r.length===0||r.length>4||!/^[0-9a-fA-F]+$/.test(r))return null;return n.map(r=>r.padStart(4,"0").toLowerCase()).join(":")}function Gz(e){let[t,n]=e.split("/");if(!t||!n)return null;let r=jS(t);if(!r)return null;let s=parseInt(n,10);if(isNaN(s))return null;let a=Hp(t);return a&&s>128||!a&&s>32?null:{addr:r,prefixLen:s,isIpv6:a}}function Kz(e,t){let n=jS(e);if(!n)return!1;let r=Gz(t);if(!r)return!1;let s=Hp(e);if(s!==r.isIpv6)return!1;let{addr:a,prefixLen:i}=r;if(s)for(let o=0;o<Math.ceil(i/16);o++){let c=65535<<16-Math.min(16,i-o*16)&65535;if((n[o]&c)!==(a[o]&c))return!1}else for(let o=0;o<Math.ceil(i/8);o++){let c=255<<8-Math.min(8,i-o*8)&255;if((n[o]&c)!==(a[o]&c))return!1}return!0}function MS(e){if(!PS(e))return!1;for(let t of qz)if(Kz(e,t))return!0;return!1}function fg(e,t){if(Vz.includes(t||""))return!0;let n=e.toLowerCase();return!!Hz.includes(n)}function mg(e,t){if(t&&(t==="127.0.0.1"||t==="::1"||t==="0.0.0.0"||t.startsWith("127.")))return!0;let n=e.toLowerCase();return!!Wz.includes(n)}function LS(e,t){let n=t?.allowPrivate??!1,r=t?.allowHttp??!1;try{let s;try{s=new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}let a=s.hostname;if(!a)throw new Error("URL missing hostname.");if(fg(a))throw new Error(`URL points to cloud metadata endpoint: ${a}`);if(mg(a)){if(!n)throw new Error(`URL points to localhost: ${a}`);return e}let i=s.protocol;if(i!=="http:"&&i!=="https:")throw new Error(`Invalid URL scheme: ${i}. Only http and https are allowed.`);if(i==="http:"&&!r)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(PS(a)){let o=a;if(mg(a,o)){if(!n)throw new Error(`URL points to localhost: ${a}`);return e}if(fg(a,o))throw new Error(`URL resolves to cloud metadata IP: ${o} (${a})`);if(MS(o)&&!n)throw new Error(`URL resolves to private IP: ${o} (${a}). Set allowPrivate: true to allow.`);return e}return e}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function Xz(e,t){try{return LS(e,t),!0}catch{return!1}}function Yz(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var Qz=Q({SaveableVectorStore:()=>e9,VectorStore:()=>x_,VectorStoreRetriever:()=>ll}),ll=class extends m_{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},x_=class extends Rn{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,n,r,s,a){if(typeof e=="number")return new ll({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:a,callbacks:n});{let i={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ll({...i,searchKwargs:e.searchKwargs}):new ll({...i})}}},e9=class extends x_{static load(e,t){throw new Error("Not implemented")}},t9=class extends Pa{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new Ke(t.stop[0]),text:t.stop[0]}]};let r=e.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
256
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new Ke(r),text:r}],llmOutput:{}}}},n9=class zS extends Pa{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:a,...i}){super(i),this.sleep=t,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(t){let n=[...this.tools,...t],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:It(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:It(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:It(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:It(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new zS({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:s})}async _generate(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new Ke({content:this.responses?.[0]?.content??t[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let i of this.chunks){let o=new Wr({message:new mn({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield o,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:o})}return}let s=this.responses?.[0]??new Ke(typeof t[0].content=="string"?t[0].content:""),a=typeof s.content=="string"?s.content:"";for(let i of a){await new Promise(c=>setTimeout(c,this.sleep));let o=new Wr({message:new mn({content:i}),text:i});if(n.signal?.aborted)break;yield o,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:o})}}},r9=class US extends Pa{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:n,sleep:r,emitCustomEvent:s,generationInfo:a}=t;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=a}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{let s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(t){return{message:new Ke(t),text:t}}async*_streamResponseChunks(t,n,r){let s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});let a=[...s];for(let i=0;i<a.length;i++){let o=a[i],c=i===a.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);let u=this._createResponseChunk(o,c?this.generationInfo:void 0);if(n.signal?.aborted)break;yield u,r?.handleLLMNewToken(o)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,n){return new Wr({message:new mn({content:t}),text:t,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:It(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:It(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:It(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:It(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new US({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:s})}withStructuredOutput(t,n){return lr.from(async r=>{let s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},s9=class extends Yy{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=t.length+r;t=t.padEnd(s," ");let a=t.length/this.vectorSize,i=[];for(let o=0;o<t.length;o+=a)i.push(t.slice(o,o+a));return i.map(o=>{let c=0;for(let u=0;u<o.length;u+=1)c+=o===" "?0:o.charCodeAt(u);return c%26/26})}},a9=class extends Yy{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},i9=class extends u_{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},o9=class extends u_{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let s of r??e)await new Promise(a=>setTimeout(a,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},c9=class extends wO{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new vn(e))}async addAIMessage(e){this.messages.push(new Ke(e))}async clear(){this.messages=[]}},u9=class extends Xy{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},l9=class extends Xr{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},d9=class extends so{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},p9=class extends m_{lc_namespace=["test","fake"];output=[new gs({pageContent:"foo"}),new gs({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},h9=class extends je{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},f9=class extends qp{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},m9=class extends Xr{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},g9=class DS extends x_{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:n,...r}={}){super(t,r),this.similarity=n??$S}async addDocuments(t){let n=t.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),t)}async addVectors(t,n){let r=t.map((s,a)=>({content:n[a].pageContent,embedding:s,metadata:n[a].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(t,n,r){let s=i=>r?r(new gs({metadata:i.metadata,pageContent:i.content})):!0,a=this.memoryVectors.filter(s);return a.map((i,o)=>({similarity:this.similarity(t,i.embedding),index:o})).sort((i,o)=>i.similarity>o.similarity?-1:0).slice(0,n).map(i=>[new gs({metadata:a[i.index].metadata,pageContent:a[i.index].content}),i.similarity])}static async fromTexts(t,n,r,s){let a=[];for(let i=0;i<t.length;i+=1){let o=Array.isArray(n)?n[i]:n,c=new gs({pageContent:t[i],metadata:o});a.push(c)}return DS.fromDocuments(a,r,s)}static async fromDocuments(t,n,r){let s=new this(n,r);return await s.addDocuments(t),s}static async fromExistingIndex(t,n){return new this(t,n)}},y9=Q({FakeChatMessageHistory:()=>c9,FakeChatModel:()=>t9,FakeEmbeddings:()=>a9,FakeLLM:()=>i9,FakeListChatMessageHistory:()=>u9,FakeListChatModel:()=>r9,FakeRetriever:()=>p9,FakeRunnable:()=>h9,FakeSplitIntoListParser:()=>d9,FakeStreamingChatModel:()=>n9,FakeStreamingLLM:()=>o9,FakeTool:()=>f9,FakeTracer:()=>l9,FakeVectorStore:()=>g9,SingleRunExtractor:()=>m9,SyntheticEmbeddings:()=>s9}),_9=Q({agents:()=>UA,caches:()=>U$,callbacks__base:()=>tC,callbacks__manager:()=>sj,callbacks__promises:()=>ej,chat_history:()=>dL,document_loaders__base:()=>mL,document_loaders__langsmith:()=>gL,documents:()=>fL,embeddings:()=>vL,errors:()=>ZA,example_selectors:()=>SL,index:()=>zA,indexing:()=>EL,language_models__base:()=>BL,language_models__chat_models:()=>p4,language_models__llms:()=>f4,language_models__profile:()=>m4,language_models__structured_output:()=>l4,load__serializable:()=>jA,memory:()=>g4,messages:()=>lL,messages__tool:()=>u$,output_parsers:()=>c4,output_parsers__openai_functions:()=>k4,output_parsers__openai_tools:()=>x4,outputs:()=>vj,prompt_values:()=>AL,prompts:()=>K4,retrievers:()=>Q4,retrievers__document_compressors:()=>X4,runnables:()=>GL,runnables__graph:()=>ZM,singletons:()=>oj,stores:()=>ez,structured_query:()=>oz,testing:()=>pz,tools:()=>hz,tracers__base:()=>zP,tracers__console:()=>BP,tracers__log_stream:()=>yj,tracers__run_collector:()=>_z,tracers__tracer_langchain:()=>JP,types__stream:()=>wz,utils__async_caller:()=>Ej,utils__chunk_array:()=>bz,utils__context:()=>xz,utils__env:()=>MA,utils__event_source_parse:()=>Iz,utils__format:()=>Nz,utils__function_calling:()=>Pz,utils__hash:()=>FA,utils__json_patch:()=>KL,utils__json_schema:()=>MM,utils__math:()=>Lz,utils__ssrf:()=>Zz,utils__standard_schema:()=>Cj,utils__stream:()=>uj,utils__testing:()=>y9,utils__tiktoken:()=>DL,utils__types:()=>u4,vectorstores:()=>Qz}),v9=50;function w9(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(t).reduce((n,[r,s])=>(n[s]=r,n),{})}async function dl(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:a,path:i,depth:o,maxDepth:c}=this,u=i.join(".");if(o>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((p,h)=>dl.call({...this,path:[...i,`${h}`],depth:o+1},p)));let l=e;if(uk(l))return am(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){let[p]=l.id;if(p in s)return s[p];if(a){let h=rr(p);if(h)return h}throw new Error(`Missing secret "${p}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){let p=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${p}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){let p=l,h=JSON.stringify(p),[f,...m]=p.id.slice().reverse(),v=m.reverse(),g={langchain_core:_9,langchain:r},y=null,k=[v.join("/")];v[0]==="langchain_community"&&k.push(["langchain",...v.slice(1)].join("/"));let x=k.find(I=>I in t);if(LA.concat(n).includes(v.join("/"))||x)if(x!==void 0)y=await t[x];else throw new Error(`Missing key "${v.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let I;if(v[0]==="langchain"||v[0]==="langchain_core")I=g[v[0]],v.shift();else throw new Error(`Invalid namespace: ${u} -> ${h}`);if(v.length===0)throw new Error(`Invalid namespace: ${u} -> ${h}`);let w;do{if(w=v.join("__"),w in I)break;v.pop()}while(v.length>0);w in I&&(y=I[w])}if(typeof y!="object"||y===null)throw new Error(`Invalid namespace: ${u} -> ${h}`);let S=y[f]??Object.values(y).find(I=>typeof I=="function"&&vp(I)===f);if(typeof S!="function")throw new Error(`Invalid identifer: ${u} -> ${h}`);let E=new S(ok(await dl.call({...this,path:[...i,"kwargs"],depth:o+1},p.kwargs),AA,w9(S)));return Object.defineProperty(E.constructor,"name",{value:f}),E}let d={};for(let[p,h]of Object.entries(l))d[p]=await dl.call({...this,path:[...i,p],depth:o+1},h);return d}async function b9(e,t){let n=JSON.parse(e),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:v9};return dl.call(r,n)}function k9(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function gg(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(t=>gg(t)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await gg(r);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{let n=t.id[t.id.length-1],r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;case"Uint8Array":r=Uint8Array;break;default:return t}return t.method?r[t.method](...t.args||[]):new r(...t.args||[])}catch{return t}else if(k9(t))return b9(JSON.stringify(t));return t}}return e}function Au(e,t,n,r){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function x9(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?Au(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?Au(RegExp,void 0,[e.source,e.flags]):e instanceof Error?Au(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e instanceof Uint8Array?Au(Uint8Array,"from",[Array.from(e)]):e}var O9=class{_dumps(e){return new TextEncoder().encode(wA(e,(t,n)=>x9(n)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){return gg(JSON.parse(e))}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function FS(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=FS(e[n]));return t}function BS(){return{v:4,id:ik(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Jl(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:FS(e.versions_seen)}}function ZS(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function S9(...e){return e.reduce((t,n,r)=>r===0?n:ZS(t,n)>=0?t:n)}var T9={[mA]:-1,[tl]:-2,[gA]:-3,[yA]:-4},fo=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function I9(e){if(e.length===0)throw new fo("Namespace cannot be empty.");for(let t of e){if(typeof t!="string")throw new fo(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new fo(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new fo(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new fo(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var E9=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:s=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:s,query:a}]))[0]}async put(e,t,n,r){I9(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:s=100,offset:a=0}=e,i=[];return t&&i.push({matchType:"prefix",path:t}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:a}]))[0]}start(){}stop(){}},A9=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,$9=class extends E9{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=A9(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:s=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:s,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:r})=>r),n=await this.store.batch(t);e.forEach(({resolve:r},s)=>{r(n[Array.from(e.keys()).indexOf(s)])})}catch(t){e.forEach(({reject:n})=>{n(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},C9=class{serde=new O9;constructor(e){this.serde=e||this.serde}};function qS(e){return e!=null&&e.lg_is_channel===!0}var Ls=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Et.unminifiable_name)return!1;throw e}}equals(e){return this===e}},yg=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function O_(e){if(e[yg]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];qS(r)&&(t[n]=r)}return Object.assign(t,{[yg]:!0}),t}function Gl(e,t){let n=O_(e),r={};for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=t.channel_values[s];r[s]=n[s].fromCheckpoint(a)}return Object.assign(r,{[yg]:!0}),r}function Ks(e,t,n,r){let s;if(t===void 0)s=e.channel_values;else{s={};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))try{s[a]=t[a].checkpoint()}catch(i){if(i.name!==Et.unminifiable_name)throw i}}return{v:4,id:r?.id??ik(n),ts:new Date().toISOString(),channel_values:s,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var N9=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",Kl=class VS extends Ls{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,n){super(),this.operator=t,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(t){let n=new VS(this.operator,this.initialValueFactory);return typeof t<"u"&&(n.value=t),n}update(t){let n=t;if(!n.length)return!1;if(this.value===void 0){let s=n[0],[a,i]=tm(s);a?this.value=i:this.value=s,n=n.slice(1)}let r=!1;for(let s of n)if(GE(s)){if(r)throw new Xe("Can receive only one Overwrite value per step.");let[,a]=tm(s);this.value=a,r=!0;continue}else!r&&this.value!==void 0&&(this.value=this.operator(this.value,s));return!0}get(){if(this.value===void 0)throw new Et;return this.value}checkpoint(){if(this.value===void 0)throw new Et;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:N9(t)?this.operator===t.operator:!1}},Wp=class HS extends Ls{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let n=new HS(this.initialValueFactory);return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0)return!1;if(t.length!==1)throw new Xe("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Et;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Et;return this.value[0]}isAvailable(){return this.value.length!==0}},P9=class WS extends Ls{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let n=new WS;if(typeof t<"u"){let[r,s]=t;n.value=[r],n.finished=s}return n}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Et;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},_g=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},gt=function(e){return e?JS(e):new Wp};gt.Root=e=>new _g(e);function JS(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new Kl(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new Kl(e.value,e.default):new Wp}var j9=["tags","metadata","callbacks","configurable"],R9=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],M9=25;function GS(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:M9,configurable:{}},n=Mt.getRunnableConfig();if(n!==void 0){for(let[r,s]of Object.entries(n))if(s!==void 0)if(j9.includes(r)){let a;Array.isArray(s)?a=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?a=s.copy():a={...s}:a=s,t[r]=a}else t[r]=s}for(let r of e)if(r!==void 0)for(let[s,a]of Object.entries(r))a!==void 0&&R9.includes(s)&&(t[s]=a);for(let[r,s]of Object.entries(t.configurable))t.metadata=t.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in t.metadata)&&(t.metadata[r]=s);return t}function L9(){return Mt.getRunnableConfig()}function Ef(e){return e.split("|").filter(t=>!t.match(/^\d+$/)).map(t=>t.split(":")[0]).join("|")}function z9(e){let t=e.split("|");for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join("|")}var ja=class extends je{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,s)=>{let a=qe(t,{callbacks:n?.getChild()});Mt.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(i){s(i)}})})}async invoke(e,t){let n,r=GS(t),s=jn(this.config,r);return this.trace?n=await this._callWithConfig(this._tracedInvoke,e,s):n=await Mt.runWithConfig(s,async()=>this.func(e,s)),je.isRunnable(n)&&this.recurse?await Mt.runWithConfig(s,async()=>n.invoke(e,s)):n}};function*Qr(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function is(e){let t=[];for await(let n of await e)t.push(n);return t}function xo(e){let t=[];for(let n of e)t.push(n);return t}function Da(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function U9(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var ca={[Symbol.for("LG_PASSTHROUGH")]:!0};function $u(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var Af=Symbol("IS_WRITER"),Xt=class vg extends ja{writes;constructor(t,n){let r=`ChannelWrite<${t.map(s=>fn(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:t,name:r,tags:n,trace:!1,func:async(s,a)=>this._write(s,a??{})}),this.writes=t}async _write(t,n){let r=this.writes.map(s=>$f(s)&&$u(s.value)?{mapper:s.mapper,value:t}:pl(s)&&$u(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await vg.doWrite(n,r),t}static async doWrite(t,n){for(let a of n){if(pl(a)){if(a.channel==="__pregel_tasks")throw new Xe("Cannot write to the reserved channel TASKS");if($u(a.value))throw new Xe("PASSTHROUGH value must be replaced")}if($f(a)&&$u(a.value))throw new Xe("PASSTHROUGH value must be replaced")}let r=[];for(let a of n)if(fn(a))r.push([_i,a]);else if($f(a)){let i=await a.mapper.invoke(a.value,t);i!=null&&i.length>0&&r.push(...i)}else if(pl(a)){let i=a.mapper!==void 0?await a.mapper.invoke(a.value,t):a.value;if(U9(i)||a.skipNone&&i===void 0)continue;r.push([a.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(a)}`);let s=t.configurable?.[ds];s(r)}static isWriter(t){return t instanceof vg||Af in t&&!!t[Af]}static registerWriter(t){return Object.defineProperty(t,Af,{value:!0})}};function pl(e){return e!==void 0&&typeof e.channel=="string"}function $f(e){return e!==void 0&&!pl(e)&&je.isRunnable(e.mapper)}var D9=class KS extends ja{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(s,a)=>KS.doRead(a,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,n,r,s){let a=t.configurable?.[ra];if(!a)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(a(n,r)):a(n,r)}},Fa=new ic,dc=class Oo extends Ss{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Fa;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){let{channels:n,triggers:r,mapper:s,writers:a,bound:i,kwargs:o,metadata:c,retryPolicy:u,cachePolicy:l,tags:d,subgraphs:p,ends:h}=t,f=[...t.config?.tags?t.config.tags:[],...d??[]];super({...t,bound:t.bound??Fa,config:{...t.config?t.config:{},tags:f}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=a??this.writers,this.bound=i??this.bound,this.kwargs=o??this.kwargs,this.metadata=c??this.metadata,this.tags=f,this.retryPolicy=u,this.cachePolicy=l,this.subgraphs=p,this.ends=h}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof Xt&&t[t.length-2]instanceof Xt;){let n=t.slice(-2),r=n[0].writes.concat(n[1].writes);t[t.length-2]=new Xt(r,n[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===Fa&&t.length===0))return this.bound===Fa&&t.length===1?t[0]:this.bound===Fa?new Ts({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new Ts({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new Oo({channels:{...this.channels,...Object.fromEntries(t.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return Xt.isWriter(t)?new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===Fa?new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Rt(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function F9(e){return"steps"in e&&Array.isArray(e.steps)}function S_(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function XS(e){let t=[e];for(let n of t){if(S_(n))return n;F9(n)&&t.push(...n.steps)}}var U=e=>BigInt(e),Ge=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),YS=U("0x9E3779B1"),QS=U("0x85EBCA77"),B9=U("0xC2B2AE3D"),Is=U("0x9E3779B185EBCA87"),ma=U("0xC2B2AE3D27D4EB4F"),eT=U("0x165667B19E3779F9"),T_=U("0x85EBCA77C2B2AE63"),Z9=U("0x27D4EB2F165667C5"),q9=U("0x165667919E3779F9"),V9=U("0x9FB21C651E98DF25"),H9=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let n=t/2,r=new Uint8Array(n),s=0,a=0;for(;a<n;){let i=e.slice(s,s+=2);r[a]=Number.parseInt(i,16),a+=1}return Ge(r)},mr=H9("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),gi=(U(1)<<U(128))-U(1),Ie=(U(1)<<U(64))-U(1),Xl=(U(1)<<U(32))-U(1),Ur=64,tT=Ur/8,W9=8,Cu=4;function Ni(e){if(!e)throw new Error("Assert failed")}function J9(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function G9(e){let t=e;return t=(t&U(65535))<<U(16)|(t&U(4294901760))>>U(16),t=(t&U(16711935))<<U(8)|(t&U(4278255360))>>U(8),t}function K9(e,t){return(e&Xl)*(t&Xl)&Ie}function X9(e,t){return(e<<t|e>>U(32)-t)&Xl}function nT(e,t,n){for(let r=0;r<tT;r+=1){let s=t.getBigUint64(r*8,!0),a=s^n.getBigUint64(r*8,!0);e[r^1]+=s,e[r]+=K9(a,a>>U(32))}return e}function mb(e,t,n,r){for(let s=0;s<r;s+=1)nT(e,Ge(t,s*Ur),Ge(n,s*8));return e}function Y9(e,t){for(let n=0;n<tT;n+=1){let r=t.getBigUint64(n*8,!0),s=e[n];s=wg(s,U(47)),s^=r,s*=YS,e[n]=s&Ie}return e}function Nu(e,t){return rT(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(W9,!0))}function gb(e,t,n){let r=n;return r+=Nu(e.slice(0),Ge(t,0*Cu)),r+=Nu(e.slice(2),Ge(t,4*Cu)),r+=Nu(e.slice(4),Ge(t,8*Cu)),r+=Nu(e.slice(6),Ge(t,12*Cu)),wr(r&Ie)}function Q9(e,t,n,r,s){let a=e,i=Math.floor((n.byteLength-Ur)/8),o=Ur*i,c=Math.floor((t.byteLength-1)/o);for(let u=0;u<c;u+=1)a=mb(a,Ge(t,u*o),n,i),a=s(a,Ge(n,n.byteLength-Ur));{let u=Math.floor((t.byteLength-1-o*c)/Ur);a=mb(a,Ge(t,c*o),n,u),a=r(a,Ge(t,t.byteLength-Ur),Ge(n,n.byteLength-Ur-7))}return a}function e5(e,t){let n=new BigUint64Array([B9,Is,ma,eT,T_,QS,Z9,YS]);Ni(e.byteLength>128),n=Q9(n,e,t,nT,Y9),Ni(n.length*8===64);{let r=gb(n,Ge(t,11),U(e.byteLength)*Is&Ie);return gb(n,Ge(t,t.byteLength-Ur-11),~(U(e.byteLength)*ma)&Ie)<<U(64)|r}}function rT(e,t){let n=e*t&gi;return n&Ie^n>>U(64)}function yb(e,t,n){return rT((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&Ie,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&Ie)}function hl(e,t,n,r,s){let a=e&Ie,i=e>>U(64)&Ie;return a+=yb(t,r,s),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=Ie,i+=yb(n,Ge(r,16),s),i^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),i&=Ie,i<<U(64)|a}function wr(e){let t=e;return t^=t>>U(37),t*=q9,t&=Ie,t^=t>>U(32),t}function Yl(e){let t=e;return t^=t>>U(33),t*=ma,t&=Ie,t^=t>>U(29),t*=eT,t&=Ie,t^=t>>U(32),t}function t5(e,t,n){let r=e.byteLength;Ni(r>0&&r<=3);let s=U(e.getUint8(r-1))|U(r<<8)|U(e.getUint8(0)<<16)|U(e.getUint8(r>>1)<<24),a=(s^(U(t.getUint32(0,!0))^U(t.getUint32(4,!0)))+n)&Ie,i=(U(t.getUint32(8,!0))^U(t.getUint32(12,!0)))-n;return(Yl((X9(G9(s),U(13))^i)&Ie)&Ie)<<U(64)|Yl(a)}function wg(e,t){return e^e>>t}function n5(e,t,n){let r=e.byteLength;Ni(r>=4&&r<=8);{let s=e.getUint32(0,!0),a=e.getUint32(r-4,!0),i=((U(s)|U(a)<<U(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&Ie)*(Is+(U(r)<<U(2)))&gi;return i+=(i&Ie)<<U(65),i&=gi,i^=i>>U(67),wg(wg(i&Ie,U(35))*V9&Ie,U(28))|wr(i>>U(64))<<U(64)}}function r5(e,t,n){let r=e.byteLength;Ni(r>=9&&r<=16);{let s=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&Ie,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&Ie,i=e.getBigUint64(0,!0),o=e.getBigUint64(r-8,!0),c=(i^o^s)*Is,u=(c&Ie)+(U(r-1)<<U(54));c=c&(gi^Ie)|u,o^=a,c+=o+(o&Xl)*(QS-U(1))<<U(64),c&=gi,c^=J9(c>>U(64));let l=(c&Ie)*ma;return l+=(c>>U(64))*ma<<U(64),l&=gi,wr(l&Ie)|wr(l>>U(64))<<U(64)}}function s5(e,t){let n=e.byteLength;return Ni(n<=16),n>8?r5(e,mr,t):n>=4?n5(e,mr,t):n>0?t5(e,mr,t):Yl(t^mr.getBigUint64(64,!0)^mr.getBigUint64(72,!0))|Yl(t^mr.getBigUint64(80,!0)^mr.getBigUint64(88,!0))<<U(64)}function bg(e){return~e+U(1)&Ie}function a5(e,t,n){let r=U(e.byteLength)*Is&Ie,s=U(e.byteLength-1)/U(32);for(;s>=0;){let o=Number(s);r=hl(r,Ge(e,16*o),Ge(e,e.byteLength-16*(o+1)),Ge(t,32*o),n),s-=U(1)}let a=r+(r>>U(64))&Ie;a=wr(a);let i=(r&Ie)*Is+(r>>U(64))*T_+(U(e.byteLength)-n&Ie)*ma;return i&=Ie,i=bg(wr(i)),a|i<<U(64)}function i5(e,t,n){let r=U(e.byteLength)*Is&Ie;for(let i=32;i<160;i+=32)r=hl(r,Ge(e,i-32),Ge(e,i-16),Ge(t,i-32),n);r=wr(r&Ie)|wr(r>>U(64))<<U(64);for(let i=160;i<=e.byteLength;i+=32)r=hl(r,Ge(e,i-32),Ge(e,i-16),Ge(t,3+i-160),n);r=hl(r,Ge(e,e.byteLength-16),Ge(e,e.byteLength-32),Ge(t,103),bg(n));let s=r+(r>>U(64))&Ie;s=wr(s);let a=(r&Ie)*Is+(r>>U(64))*T_+(U(e.byteLength)-n&Ie)*ma;return a&=Ie,a=bg(wr(a)),s|a<<U(64)}function Hs(e,t=U(0)){let n=new TextEncoder,r=Ge(typeof e=="string"?n.encode(e):e),s=r.byteLength,a=i=>i.toString(16).padStart(32,"0");return s<=16?a(s5(r,t)):s<=128?a(a5(r,mr,t)):s<=240?a(i5(r,mr,t)):a(e5(r,mr))}function sT(e){return/^[0-9a-f]{32}$/.test(e)}function yi(e,t,n=!0,r=!1){try{return e[t].get()}catch(s){if(s.name===Et.unminifiable_name){if(r)return s;if(n)return null}throw s}}function ga(e,t,n=!0){if(Array.isArray(t)){let r={};for(let s of t)try{r[s]=yi(e,s,!n)}catch(a){if(a.name===Et.unminifiable_name)continue}return r}else return yi(e,t)}function*o5(e,t){if(e.graph===_r.PARENT)throw new Xe("There is no parent graph.");if(e.goto){let n;Array.isArray(e.goto)?n=e.goto:n=[e.goto];for(let r of n)if(fn(r))yield[yr,_i,r];else if(typeof r=="string")yield[yr,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(sT))for(let[n,r]of Object.entries(e.resume)){let s=t.filter(a=>a[0]===n&&a[1]==="__resume__").map(a=>a[2]).slice(0,1)??[];s.push(r),yield[n,vs,s]}else yield[yr,vs,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[n,r]of e.update)yield[yr,n,r];else for(let[n,r]of Object.entries(e.update))yield[yr,n,r]}}function*aT(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Cf(e,t,n){Array.isArray(e)?(t===!0||t.find(([r,s])=>e.includes(r)))&&(yield ga(n,e)):(t===!0||t.some(([r,s])=>r===e))&&(yield yi(n,e))}function*c5(e,t,n){let r=t.filter(([o,c])=>(o.config===void 0||!o.config.tags?.includes("langsmith:hidden"))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__");if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,u])=>c==="__return__"))?s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===_p).map(([c,u])=>[o.name,u])):Array.isArray(e)?s=r.flatMap(([o])=>{let{writes:c}=o,u={};for(let[l]of c)e.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>e.includes(l)).map(([l,d])=>[o.name,{[l]:d}]):[[o.name,Object.fromEntries(c.filter(([l])=>e.includes(l)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===e).map(([c,u])=>[o.name,u]));let a={};for(let[o,c]of s)o in a||(a[o]=[]),a[o].push(c);let i={};for(let o in a)if(a[o].length===1){let[c]=a[o];i[o]=c}else i[o]=a[o];n&&(i.__metadata__={cached:n}),yield i}function I_(e){let t=typeof e[wt];if(t==="number")return 0;if(t==="string")return"";for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=typeof e[n];if(r==="number")return 0;if(r==="string")return"";break}}function fl(e,t){if(Object.keys(e).length>0){let n=I_(t);return Object.fromEntries(Object.entries(t).filter(([r,s])=>s>(e[r]??n)))}else return t}function u5(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function Yn(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Bs(e,t){let n=t?.parents??{};return Object.keys(n).length>0?Yn(e,{[Mr]:{...n,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function Ql(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};if(typeof AbortSignal.any=="function")return{signal:AbortSignal.any(t),dispose:void 0};let n=new AbortController,r=()=>{let a=t.find(i=>i.aborted)?.reason;n.abort(a),t.forEach(i=>i.removeEventListener("abort",r))};t.forEach(a=>a.addEventListener("abort",r,{once:!0}));let s=t.find(a=>a.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{t.forEach(a=>a.removeEventListener("abort",r))}}}var l5=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t},d5=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:n,retry:r,cache:s,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=s,this.callbacks=a}};function p5(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function h5(e,t){return new Ts({name:e,first:new ja({func:n=>t(...n),name:e,trace:!1,recurse:!1}),last:new Xt([{channel:_p,value:ca}],[dn])})}var f5=e=>e!==void 0?e+1:1;function m5(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function g5(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t==null?t=e[n]:t=S9(t,e[n]));return t}function Pu(e,t,n){let r=I_(e.channel_versions),s=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(s.__start__??r))a=!0;else for(let o in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,o)&&e.channel_versions[o]>(s[o]??r)){a=!0;break}let i=n.some(o=>t==="*"?!o.config?.tags?.includes(dn):t.includes(o.name));return a&&i}function ml(e,t,n,r,s=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(o=>n.writes.some(([c,u])=>c===o)));else{for(let[o]of n.writes)if(o===r){a=new Set([o]);break}a=a||new Set}let i;if(s&&a.size>0){let o=Object.fromEntries(Object.entries(t).filter(([l,d])=>a.has(l))),c=Ks(e,o,-1),u=Gl(o,c);Tn(Jl(c),u,[n],void 0,void 0),i=ga({...t,...u},r)}else i=ga(t,r);return i}function Nf(e,t,n){for(let[r,s]of n)if(["__pregel_push","__pregel_tasks"].includes(r)&&s!=null){if(!fn(s))throw new Xe(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new Xe(`Invalid node name "${s.node}" in Send packet`)}e(n)}var y5=new Set([uy,Zr,vs,Tt,_p,yp]);function Tn(e,t,n,r,s){n.sort((p,h)=>{let f=p.path?.slice(0,3)||[],m=h.path?.slice(0,3)||[];for(let v=0;v<Math.min(f.length,m.length);v+=1){if(f[v]<m[v])return-1;if(f[v]>m[v])return 1}return f.length-m.length});let a=n.some(p=>p.triggers.length>0),i=O_(t);for(let p of n){e.versions_seen[p.name]??={};for(let h of p.triggers)h in e.channel_versions&&(e.versions_seen[p.name][h]=e.channel_versions[h])}let o=g5(e.channel_versions),c=new Set(n.flatMap(p=>p.triggers).filter(p=>!HE.includes(p))),u=!1;for(let p of c)p in i&&i[p].consume()&&r!==void 0&&(e.channel_versions[p]=r(o),u=!0);let l={};for(let p of n)for(let[h,f]of p.writes)y5.has(h)||h in i&&(l[h]??=[],l[h].push(f));o!=null&&r!=null&&(o=u?r(o):o);let d=new Set;for(let[p,h]of Object.entries(l))if(p in i){let f=i[p],m;try{m=f.update(h)}catch(v){if(v.name===Xe.unminifiable_name){let g=new Xe(`Invalid update for channel "${p}" with values ${JSON.stringify(h)}: ${v.message}`);throw g.lc_error_code=v.lc_error_code,g}else throw v}m&&r!==void 0&&(e.channel_versions[p]=r(o),f.isAvailable()&&d.add(p))}if(a)for(let p in i){if(!Object.prototype.hasOwnProperty.call(i,p))continue;let h=i[p];h.isAvailable()&&!d.has(p)&&h.update([])&&r!==void 0&&(e.channel_versions[p]=r(o),h.isAvailable()&&d.add(p))}if(a&&!m5(d,s))for(let p in i){if(!Object.prototype.hasOwnProperty.call(i,p))continue;let h=i[p];h.finish()&&r!==void 0&&(e.channel_versions[p]=r(o),h.isAvailable()&&d.add(p))}return d}function*_5(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let r=new Set;for(let s of n.updatedChannels){let a=n.triggerToNodes[s];for(let i of a??[])r.add(i)}yield*[...r].sort();return}if(!(()=>{for(let r in e.channel_versions)if(e.channel_versions[r]!==null)return!1;return!0})())for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(yield r)}function ci(e,t,n,r,s,a,i){let o={},c=r[_i];if(c?.isAvailable()){let u=c.get().length;for(let l=0;l<u;l+=1){let d=kg([Zr,l],e,t,n,r,s,a,i);d!==void 0&&(o[d.id]=d)}}for(let u of _5(e,n,i)){let l=kg([Qf,u],e,t,n,r,s,a,i);l!==void 0&&(o[l.id]=l)}return o}function kg(e,t,n,r,s,a,i,o){let{step:c,checkpointer:u,manager:l}=o,d=a.configurable??{},p=d.checkpoint_ns??"";if(e[0]==="__pregel_push"&&p5(e[e.length-1])){let h=e[e.length-1],f=h5(h.name,h.func),m=[Zr],v=p===""?h.name:`${p}|${h.name}`,g=ni(JSON.stringify([v,c.toString(),h.name,Zr,e[1],e[2]]),t.id),y=`${v}:${g}`,k=[...e.slice(0,3),!0],x={langgraph_step:c,langgraph_node:h.name,langgraph_triggers:m,langgraph_path:k,langgraph_checkpoint_ns:y};if(i){let S=[];return{name:h.name,input:h.input,proc:f,writes:S,config:qe(jn(a,{metadata:x,store:o.store??a.store}),{runName:h.name,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:g,[ds]:E=>Nf(I=>S.push(...I),r,E),[ra]:(E,I=!1)=>ml(t,s,{name:h.name,writes:S,triggers:m,path:k},E,I),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:g,currentTaskInput:h.input,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(y)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:m,retry_policy:h.retry,cache_key:h.cache?{key:Hs((h.cache.keyFunc??JSON.stringify)([h.input])),ns:[rh,h.name??"__dynamic__"],ttl:h.cache.ttl}:void 0,id:g,path:k,writers:[]}}else return{id:g,name:h.name,interrupts:[],path:k}}else if(e[0]==="__pregel_push"){let h=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s.__pregel_tasks?.isAvailable())return;let f=s[_i].get();if(h<0||h>=f.length)return;let m=em(f[h])&&!fn(f[h])?new Jo(f[h].node,f[h].args):f[h];if(!em(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in r)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}let v=[Zr],g=p===""?m.node:`${p}|${m.node}`,y=ni(JSON.stringify([g,c.toString(),m.node,Zr,h.toString()]),t.id),k=`${g}:${y}`,x={langgraph_step:c,langgraph_node:m.node,langgraph_triggers:v,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:k};if(i){let S=r[m.node],E=S.getNode();if(E!==void 0){S.metadata!==void 0&&(x={...x,...S.metadata});let I=[];return{name:m.node,input:m.args,proc:E,subgraphs:S.subgraphs,writes:I,config:qe(jn(a,{metadata:x,tags:S.tags,store:o.store??a.store}),{runName:m.node,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:y,[ds]:w=>Nf(P=>I.push(...P),r,w),[ra]:(w,P=!1)=>ml(t,s,{name:m.node,writes:I,triggers:v,path:e},w,P),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:y,currentTaskInput:m.args,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(k)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:v,retry_policy:S.retryPolicy,cache_key:S.cachePolicy?{key:Hs((S.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[rh,S.name??"__dynamic__",m.node],ttl:S.cachePolicy.ttl}:void 0,id:y,path:e,writers:S.getWriters()}}}else return{id:y,name:m.node,interrupts:[],path:e}}else if(e[0]==="__pregel_pull"){let h=e[1].toString(),f=r[h];if(f===void 0)return;if(n?.length){let y=p===""?h:`${p}|${h}`,k=ni(JSON.stringify([y,c.toString(),h,Qf,h]),t.id);if(n.some(x=>x[0]===k&&x[1]!=="__error__"))return}let m=I_(t.channel_versions);if(m===void 0)return;let v=t.versions_seen[h]??{},g=f.triggers.find(y=>s[y].isAvailable()?(t.channel_versions[y]??m)>(v[y]??m):!1);if(g!==void 0){let y=v5(f,s,i);if(y===void 0)return;let k=p===""?h:`${p}|${h}`,x=ni(JSON.stringify([k,c.toString(),h,Qf,[g]]),t.id),S=`${k}:${x}`,E={langgraph_step:c,langgraph_node:h,langgraph_triggers:[g],langgraph_path:e,langgraph_checkpoint_ns:S};if(i){let I=f.getNode();if(I!==void 0){f.metadata!==void 0&&(E={...E,...f.metadata});let w=[];return{name:h,input:y,proc:I,subgraphs:f.subgraphs,writes:w,config:qe(jn(a,{metadata:E,tags:f.tags,store:o.store??a.store}),{runName:h,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:x,[ds]:P=>Nf(A=>{w.push(...A)},r,P),[ra]:(P,A=!1)=>ml(t,s,{name:h,writes:w,triggers:[g],path:e},P,A),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:x,currentTaskInput:y,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(S)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:S}}),triggers:[g],retry_policy:f.retryPolicy,cache_key:f.cachePolicy?{key:Hs((f.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[rh,f.name??"__dynamic__",h],ttl:f.cachePolicy.ttl}:void 0,id:x,path:e,writers:f.getWriters()}}}else return{id:x,name:h,interrupts:[],path:e}}}}function v5(e,t,n){let r;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){r={};for(let[s,a]of Object.entries(e.channels))if(e.triggers.includes(a))try{r[s]=yi(t,a,!1)}catch(i){if(i.name===Et.unminifiable_name)return;throw i}else if(a in t)try{r[s]=yi(t,a,!1)}catch(i){if(i.name===Et.unminifiable_name)continue;throw i}}else if(Array.isArray(e.channels)){let s=!1;for(let a of e.channels)try{r=yi(t,a,!1),s=!0;break}catch(i){if(i.name===Et.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function w5(e,t){if(typeof e.args!="object"||e.args===null)return e;let n={};for(let[r,s]of Object.entries(e.args)){let a=t[r];(!a||a.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new Jo(e.node,n)}function Pf({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:s}){let a=e.find(([o,c])=>o==="00000000-0000-0000-0000-000000000000"&&c==="__resume__")?.[2],i={callCounter:0,interruptCounter:-1,resume:(()=>{let o=e.filter(([c,u])=>c===t&&u==="__resume__").flatMap(([c,u,l])=>l);if(r!=null&&s in r){let c=r[s];o.push(c)}return o})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(i.nullResume)return delete i.nullResume,e.splice(e.findIndex(([o,c])=>o==="00000000-0000-0000-0000-000000000000"&&c==="__resume__"),1),a}};return i}var pc={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},hc=(e,t)=>`${e.start}${t}${e.end}`;function*_b(e){for(let{id:t,name:n,input:r,config:s,triggers:a,writes:i}of e)s?.tags?.includes("langsmith:hidden")||(yield{id:t,name:n,input:r,triggers:a,interrupts:i.filter(([o,c])=>o===t&&c==="__interrupt__").map(([,o])=>o)})}function b5(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function iT(e){let t={};for(let[n,r]of e){let s=String(n);if(s in t){let a=b5(t[s])?t[s].$writes:[t[s]];a.push(r),t[s]={$writes:a}}else t[s]=r}return t}function*k5(e,t){for(let[{id:n,name:r,config:s},a]of e)s?.tags?.includes("langsmith:hidden")||(yield{id:n,name:r,result:iT(a.filter(([i])=>Array.isArray(t)?t.includes(i):i===t)),interrupts:a.filter(i=>i[0]===Tt).map(i=>i[1])})}function*x5(e,t,n,r,s,a,i,o){function c(d){let p={};return d.callbacks!=null&&(p.callbacks=d.callbacks),d.configurable!=null&&(p.configurable=d.configurable),d.maxConcurrency!=null&&(p.max_concurrency=d.maxConcurrency),d.metadata!=null&&(p.metadata=d.metadata),d.recursionLimit!=null&&(p.recursion_limit=d.recursionLimit),d.runId!=null&&(p.run_id=d.runId),d.runName!=null&&(p.run_name=d.runName),d.tags!=null&&(p.tags=d.tags),p}let u=e.configurable?.checkpoint_ns,l={};for(let d of s){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(XS))continue;let p=`${d.name}:${d.id}`;u&&(p=`${u}|${p}`),l[d.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:p}}}yield{config:c(e),values:ga(t,n),metadata:r,next:s.map(d=>d.name),tasks:oT(s,a,l,o),parentConfig:i?c(i):void 0}}function oT(e,t,n,r){return e.map(s=>{let a=t.find(([u,l])=>u===s.id&&l==="__error__")?.[2],i=t.filter(([u,l])=>u===s.id&&l==="__interrupt__").map(([,,u])=>u),o=(()=>{if(a||i.length||!t.length)return;let u=t.findIndex(([l,d])=>l===s.id&&d==="__return__");if(u>=0)return t[u][2];if(typeof r=="string")return t.find(([l,d])=>l===s.id&&d===r)?.[2];if(Array.isArray(r)){let l=t.filter(([d,p])=>d===s.id&&r.includes(p)).map(([,d,p])=>[d,p]);return l.length?iT(l):void 0}})();if(a)return{id:s.id,name:s.name,path:s.path,error:a,interrupts:i,result:o};let c=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...c!==void 0?{state:c}:{},result:o}})}function O5(e,t,n){console.log([`${hc(pc.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
256
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new Ke(r),text:r}],llmOutput:{}}}},n9=class zS extends Pa{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:a,...i}){super(i),this.sleep=t,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(t){let n=[...this.tools,...t],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:It(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:It(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:It(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:It(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new zS({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:s})}async _generate(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new Ke({content:this.responses?.[0]?.content??t[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let i of this.chunks){let o=new Wr({message:new mn({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield o,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:o})}return}let s=this.responses?.[0]??new Ke(typeof t[0].content=="string"?t[0].content:""),a=typeof s.content=="string"?s.content:"";for(let i of a){await new Promise(c=>setTimeout(c,this.sleep));let o=new Wr({message:new mn({content:i}),text:i});if(n.signal?.aborted)break;yield o,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:o})}}},r9=class US extends Pa{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:n,sleep:r,emitCustomEvent:s,generationInfo:a}=t;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=a}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{let s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(t){return{message:new Ke(t),text:t}}async*_streamResponseChunks(t,n,r){let s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});let a=[...s];for(let i=0;i<a.length;i++){let o=a[i],c=i===a.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);let u=this._createResponseChunk(o,c?this.generationInfo:void 0);if(n.signal?.aborted)break;yield u,r?.handleLLMNewToken(o)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,n){return new Wr({message:new mn({content:t}),text:t,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:It(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:It(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:It(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:It(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new US({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:s})}withStructuredOutput(t,n){return lr.from(async r=>{let s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},s9=class extends Yy{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=t.length+r;t=t.padEnd(s," ");let a=t.length/this.vectorSize,i=[];for(let o=0;o<t.length;o+=a)i.push(t.slice(o,o+a));return i.map(o=>{let c=0;for(let u=0;u<o.length;u+=1)c+=o===" "?0:o.charCodeAt(u);return c%26/26})}},a9=class extends Yy{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},i9=class extends u_{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},o9=class extends u_{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let s of r??e)await new Promise(a=>setTimeout(a,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},c9=class extends wO{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new vn(e))}async addAIMessage(e){this.messages.push(new Ke(e))}async clear(){this.messages=[]}},u9=class extends Xy{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},l9=class extends Xr{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},d9=class extends so{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},p9=class extends m_{lc_namespace=["test","fake"];output=[new gs({pageContent:"foo"}),new gs({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},h9=class extends je{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},f9=class extends qp{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},m9=class extends Xr{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},g9=class DS extends x_{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:n,...r}={}){super(t,r),this.similarity=n??$S}async addDocuments(t){let n=t.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),t)}async addVectors(t,n){let r=t.map((s,a)=>({content:n[a].pageContent,embedding:s,metadata:n[a].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(t,n,r){let s=i=>r?r(new gs({metadata:i.metadata,pageContent:i.content})):!0,a=this.memoryVectors.filter(s);return a.map((i,o)=>({similarity:this.similarity(t,i.embedding),index:o})).sort((i,o)=>i.similarity>o.similarity?-1:0).slice(0,n).map(i=>[new gs({metadata:a[i.index].metadata,pageContent:a[i.index].content}),i.similarity])}static async fromTexts(t,n,r,s){let a=[];for(let i=0;i<t.length;i+=1){let o=Array.isArray(n)?n[i]:n,c=new gs({pageContent:t[i],metadata:o});a.push(c)}return DS.fromDocuments(a,r,s)}static async fromDocuments(t,n,r){let s=new this(n,r);return await s.addDocuments(t),s}static async fromExistingIndex(t,n){return new this(t,n)}},y9=Q({FakeChatMessageHistory:()=>c9,FakeChatModel:()=>t9,FakeEmbeddings:()=>a9,FakeLLM:()=>i9,FakeListChatMessageHistory:()=>u9,FakeListChatModel:()=>r9,FakeRetriever:()=>p9,FakeRunnable:()=>h9,FakeSplitIntoListParser:()=>d9,FakeStreamingChatModel:()=>n9,FakeStreamingLLM:()=>o9,FakeTool:()=>f9,FakeTracer:()=>l9,FakeVectorStore:()=>g9,SingleRunExtractor:()=>m9,SyntheticEmbeddings:()=>s9}),_9=Q({agents:()=>UA,caches:()=>U$,callbacks__base:()=>tC,callbacks__manager:()=>sj,callbacks__promises:()=>ej,chat_history:()=>dL,document_loaders__base:()=>mL,document_loaders__langsmith:()=>gL,documents:()=>fL,embeddings:()=>vL,errors:()=>ZA,example_selectors:()=>SL,index:()=>zA,indexing:()=>EL,language_models__base:()=>BL,language_models__chat_models:()=>p4,language_models__llms:()=>f4,language_models__profile:()=>m4,language_models__structured_output:()=>l4,load__serializable:()=>jA,memory:()=>g4,messages:()=>lL,messages__tool:()=>u$,output_parsers:()=>c4,output_parsers__openai_functions:()=>k4,output_parsers__openai_tools:()=>x4,outputs:()=>vj,prompt_values:()=>AL,prompts:()=>K4,retrievers:()=>Q4,retrievers__document_compressors:()=>X4,runnables:()=>GL,runnables__graph:()=>ZM,singletons:()=>oj,stores:()=>ez,structured_query:()=>oz,testing:()=>pz,tools:()=>hz,tracers__base:()=>zP,tracers__console:()=>BP,tracers__log_stream:()=>yj,tracers__run_collector:()=>_z,tracers__tracer_langchain:()=>JP,types__stream:()=>wz,utils__async_caller:()=>Ej,utils__chunk_array:()=>bz,utils__context:()=>xz,utils__env:()=>MA,utils__event_source_parse:()=>Iz,utils__format:()=>Nz,utils__function_calling:()=>Pz,utils__hash:()=>FA,utils__json_patch:()=>KL,utils__json_schema:()=>MM,utils__math:()=>Lz,utils__ssrf:()=>Zz,utils__standard_schema:()=>Cj,utils__stream:()=>uj,utils__testing:()=>y9,utils__tiktoken:()=>DL,utils__types:()=>u4,vectorstores:()=>Qz}),v9=50;function w9(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(t).reduce((n,[r,s])=>(n[s]=r,n),{})}async function dl(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:a,path:i,depth:o,maxDepth:c}=this,u=i.join(".");if(o>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((p,h)=>dl.call({...this,path:[...i,`${h}`],depth:o+1},p)));let l=e;if(uk(l))return am(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){let[p]=l.id;if(p in s)return s[p];if(a){let h=rr(p);if(h)return h}throw new Error(`Missing secret "${p}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){let p=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${p}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){let p=l,h=JSON.stringify(p),[f,...m]=p.id.slice().reverse(),v=m.reverse(),g={langchain_core:_9,langchain:r},y=null,k=[v.join("/")];v[0]==="langchain_community"&&k.push(["langchain",...v.slice(1)].join("/"));let x=k.find(I=>I in t);if(LA.concat(n).includes(v.join("/"))||x)if(x!==void 0)y=await t[x];else throw new Error(`Missing key "${v.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let I;if(v[0]==="langchain"||v[0]==="langchain_core")I=g[v[0]],v.shift();else throw new Error(`Invalid namespace: ${u} -> ${h}`);if(v.length===0)throw new Error(`Invalid namespace: ${u} -> ${h}`);let w;do{if(w=v.join("__"),w in I)break;v.pop()}while(v.length>0);w in I&&(y=I[w])}if(typeof y!="object"||y===null)throw new Error(`Invalid namespace: ${u} -> ${h}`);let S=y[f]??Object.values(y).find(I=>typeof I=="function"&&vp(I)===f);if(typeof S!="function")throw new Error(`Invalid identifer: ${u} -> ${h}`);let E=new S(ok(await dl.call({...this,path:[...i,"kwargs"],depth:o+1},p.kwargs),AA,w9(S)));return Object.defineProperty(E.constructor,"name",{value:f}),E}let d={};for(let[p,h]of Object.entries(l))d[p]=await dl.call({...this,path:[...i,p],depth:o+1},h);return d}async function b9(e,t){let n=JSON.parse(e),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:v9};return dl.call(r,n)}function k9(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function gg(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(t=>gg(t)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await gg(r);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{let n=t.id[t.id.length-1],r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;case"Uint8Array":r=Uint8Array;break;default:return t}return t.method?r[t.method](...t.args||[]):new r(...t.args||[])}catch{return t}else if(k9(t))return b9(JSON.stringify(t));return t}}return e}function Au(e,t,n,r){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function x9(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?Au(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?Au(RegExp,void 0,[e.source,e.flags]):e instanceof Error?Au(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e instanceof Uint8Array?Au(Uint8Array,"from",[Array.from(e)]):e}var O9=class{_dumps(e){return new TextEncoder().encode(wA(e,(t,n)=>x9(n)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){return gg(JSON.parse(e))}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function FS(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=FS(e[n]));return t}function BS(){return{v:4,id:ik(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Jl(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:FS(e.versions_seen)}}function ZS(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function S9(...e){return e.reduce((t,n,r)=>r===0?n:ZS(t,n)>=0?t:n)}var T9={[mA]:-1,[tl]:-2,[gA]:-3,[yA]:-4},fo=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function I9(e){if(e.length===0)throw new fo("Namespace cannot be empty.");for(let t of e){if(typeof t!="string")throw new fo(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new fo(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new fo(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new fo(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var E9=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:s=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:s,query:a}]))[0]}async put(e,t,n,r){I9(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:s=100,offset:a=0}=e,i=[];return t&&i.push({matchType:"prefix",path:t}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:a}]))[0]}start(){}stop(){}},A9=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,$9=class extends E9{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=A9(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:s=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:s,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:r})=>r),n=await this.store.batch(t);e.forEach(({resolve:r},s)=>{r(n[Array.from(e.keys()).indexOf(s)])})}catch(t){e.forEach(({reject:n})=>{n(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},C9=class{serde=new O9;constructor(e){this.serde=e||this.serde}};function qS(e){return e!=null&&e.lg_is_channel===!0}var Ls=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Et.unminifiable_name)return!1;throw e}}equals(e){return this===e}},yg=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function O_(e){if(e[yg]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];qS(r)&&(t[n]=r)}return Object.assign(t,{[yg]:!0}),t}function Gl(e,t){let n=O_(e),r={};for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=t.channel_values[s];r[s]=n[s].fromCheckpoint(a)}return Object.assign(r,{[yg]:!0}),r}function Ks(e,t,n,r){let s;if(t===void 0)s=e.channel_values;else{s={};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))try{s[a]=t[a].checkpoint()}catch(i){if(i.name!==Et.unminifiable_name)throw i}}return{v:4,id:r?.id??ik(n),ts:new Date().toISOString(),channel_values:s,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var N9=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",Kl=class VS extends Ls{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,n){super(),this.operator=t,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(t){let n=new VS(this.operator,this.initialValueFactory);return typeof t<"u"&&(n.value=t),n}update(t){let n=t;if(!n.length)return!1;if(this.value===void 0){let s=n[0],[a,i]=tm(s);a?this.value=i:this.value=s,n=n.slice(1)}let r=!1;for(let s of n)if(GE(s)){if(r)throw new Xe("Can receive only one Overwrite value per step.");let[,a]=tm(s);this.value=a,r=!0;continue}else!r&&this.value!==void 0&&(this.value=this.operator(this.value,s));return!0}get(){if(this.value===void 0)throw new Et;return this.value}checkpoint(){if(this.value===void 0)throw new Et;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:N9(t)?this.operator===t.operator:!1}},Wp=class HS extends Ls{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let n=new HS(this.initialValueFactory);return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0)return!1;if(t.length!==1)throw new Xe("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Et;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Et;return this.value[0]}isAvailable(){return this.value.length!==0}},P9=class WS extends Ls{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let n=new WS;if(typeof t<"u"){let[r,s]=t;n.value=[r],n.finished=s}return n}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Et;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},_g=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},mt=function(e){return e?JS(e):new Wp};mt.Root=e=>new _g(e);function JS(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new Kl(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new Kl(e.value,e.default):new Wp}var j9=["tags","metadata","callbacks","configurable"],R9=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],M9=25;function GS(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:M9,configurable:{}},n=Mt.getRunnableConfig();if(n!==void 0){for(let[r,s]of Object.entries(n))if(s!==void 0)if(j9.includes(r)){let a;Array.isArray(s)?a=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?a=s.copy():a={...s}:a=s,t[r]=a}else t[r]=s}for(let r of e)if(r!==void 0)for(let[s,a]of Object.entries(r))a!==void 0&&R9.includes(s)&&(t[s]=a);for(let[r,s]of Object.entries(t.configurable))t.metadata=t.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in t.metadata)&&(t.metadata[r]=s);return t}function L9(){return Mt.getRunnableConfig()}function Ef(e){return e.split("|").filter(t=>!t.match(/^\d+$/)).map(t=>t.split(":")[0]).join("|")}function z9(e){let t=e.split("|");for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join("|")}var ja=class extends je{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,s)=>{let a=qe(t,{callbacks:n?.getChild()});Mt.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(i){s(i)}})})}async invoke(e,t){let n,r=GS(t),s=jn(this.config,r);return this.trace?n=await this._callWithConfig(this._tracedInvoke,e,s):n=await Mt.runWithConfig(s,async()=>this.func(e,s)),je.isRunnable(n)&&this.recurse?await Mt.runWithConfig(s,async()=>n.invoke(e,s)):n}};function*Qr(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function is(e){let t=[];for await(let n of await e)t.push(n);return t}function xo(e){let t=[];for(let n of e)t.push(n);return t}function Da(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function U9(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var ca={[Symbol.for("LG_PASSTHROUGH")]:!0};function $u(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var Af=Symbol("IS_WRITER"),Xt=class vg extends ja{writes;constructor(t,n){let r=`ChannelWrite<${t.map(s=>fn(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:t,name:r,tags:n,trace:!1,func:async(s,a)=>this._write(s,a??{})}),this.writes=t}async _write(t,n){let r=this.writes.map(s=>$f(s)&&$u(s.value)?{mapper:s.mapper,value:t}:pl(s)&&$u(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await vg.doWrite(n,r),t}static async doWrite(t,n){for(let a of n){if(pl(a)){if(a.channel==="__pregel_tasks")throw new Xe("Cannot write to the reserved channel TASKS");if($u(a.value))throw new Xe("PASSTHROUGH value must be replaced")}if($f(a)&&$u(a.value))throw new Xe("PASSTHROUGH value must be replaced")}let r=[];for(let a of n)if(fn(a))r.push([_i,a]);else if($f(a)){let i=await a.mapper.invoke(a.value,t);i!=null&&i.length>0&&r.push(...i)}else if(pl(a)){let i=a.mapper!==void 0?await a.mapper.invoke(a.value,t):a.value;if(U9(i)||a.skipNone&&i===void 0)continue;r.push([a.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(a)}`);let s=t.configurable?.[ds];s(r)}static isWriter(t){return t instanceof vg||Af in t&&!!t[Af]}static registerWriter(t){return Object.defineProperty(t,Af,{value:!0})}};function pl(e){return e!==void 0&&typeof e.channel=="string"}function $f(e){return e!==void 0&&!pl(e)&&je.isRunnable(e.mapper)}var D9=class KS extends ja{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(s,a)=>KS.doRead(a,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,n,r,s){let a=t.configurable?.[ra];if(!a)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(a(n,r)):a(n,r)}},Fa=new ic,dc=class Oo extends Ss{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Fa;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){let{channels:n,triggers:r,mapper:s,writers:a,bound:i,kwargs:o,metadata:c,retryPolicy:u,cachePolicy:l,tags:d,subgraphs:p,ends:h}=t,f=[...t.config?.tags?t.config.tags:[],...d??[]];super({...t,bound:t.bound??Fa,config:{...t.config?t.config:{},tags:f}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=a??this.writers,this.bound=i??this.bound,this.kwargs=o??this.kwargs,this.metadata=c??this.metadata,this.tags=f,this.retryPolicy=u,this.cachePolicy=l,this.subgraphs=p,this.ends=h}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof Xt&&t[t.length-2]instanceof Xt;){let n=t.slice(-2),r=n[0].writes.concat(n[1].writes);t[t.length-2]=new Xt(r,n[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===Fa&&t.length===0))return this.bound===Fa&&t.length===1?t[0]:this.bound===Fa?new Ts({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new Ts({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new Oo({channels:{...this.channels,...Object.fromEntries(t.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return Xt.isWriter(t)?new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===Fa?new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Rt(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new Oo({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function F9(e){return"steps"in e&&Array.isArray(e.steps)}function S_(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function XS(e){let t=[e];for(let n of t){if(S_(n))return n;F9(n)&&t.push(...n.steps)}}var U=e=>BigInt(e),Ge=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),YS=U("0x9E3779B1"),QS=U("0x85EBCA77"),B9=U("0xC2B2AE3D"),Is=U("0x9E3779B185EBCA87"),ma=U("0xC2B2AE3D27D4EB4F"),eT=U("0x165667B19E3779F9"),T_=U("0x85EBCA77C2B2AE63"),Z9=U("0x27D4EB2F165667C5"),q9=U("0x165667919E3779F9"),V9=U("0x9FB21C651E98DF25"),H9=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let n=t/2,r=new Uint8Array(n),s=0,a=0;for(;a<n;){let i=e.slice(s,s+=2);r[a]=Number.parseInt(i,16),a+=1}return Ge(r)},mr=H9("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),gi=(U(1)<<U(128))-U(1),Ie=(U(1)<<U(64))-U(1),Xl=(U(1)<<U(32))-U(1),Ur=64,tT=Ur/8,W9=8,Cu=4;function Ni(e){if(!e)throw new Error("Assert failed")}function J9(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function G9(e){let t=e;return t=(t&U(65535))<<U(16)|(t&U(4294901760))>>U(16),t=(t&U(16711935))<<U(8)|(t&U(4278255360))>>U(8),t}function K9(e,t){return(e&Xl)*(t&Xl)&Ie}function X9(e,t){return(e<<t|e>>U(32)-t)&Xl}function nT(e,t,n){for(let r=0;r<tT;r+=1){let s=t.getBigUint64(r*8,!0),a=s^n.getBigUint64(r*8,!0);e[r^1]+=s,e[r]+=K9(a,a>>U(32))}return e}function mb(e,t,n,r){for(let s=0;s<r;s+=1)nT(e,Ge(t,s*Ur),Ge(n,s*8));return e}function Y9(e,t){for(let n=0;n<tT;n+=1){let r=t.getBigUint64(n*8,!0),s=e[n];s=wg(s,U(47)),s^=r,s*=YS,e[n]=s&Ie}return e}function Nu(e,t){return rT(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(W9,!0))}function gb(e,t,n){let r=n;return r+=Nu(e.slice(0),Ge(t,0*Cu)),r+=Nu(e.slice(2),Ge(t,4*Cu)),r+=Nu(e.slice(4),Ge(t,8*Cu)),r+=Nu(e.slice(6),Ge(t,12*Cu)),wr(r&Ie)}function Q9(e,t,n,r,s){let a=e,i=Math.floor((n.byteLength-Ur)/8),o=Ur*i,c=Math.floor((t.byteLength-1)/o);for(let u=0;u<c;u+=1)a=mb(a,Ge(t,u*o),n,i),a=s(a,Ge(n,n.byteLength-Ur));{let u=Math.floor((t.byteLength-1-o*c)/Ur);a=mb(a,Ge(t,c*o),n,u),a=r(a,Ge(t,t.byteLength-Ur),Ge(n,n.byteLength-Ur-7))}return a}function e5(e,t){let n=new BigUint64Array([B9,Is,ma,eT,T_,QS,Z9,YS]);Ni(e.byteLength>128),n=Q9(n,e,t,nT,Y9),Ni(n.length*8===64);{let r=gb(n,Ge(t,11),U(e.byteLength)*Is&Ie);return gb(n,Ge(t,t.byteLength-Ur-11),~(U(e.byteLength)*ma)&Ie)<<U(64)|r}}function rT(e,t){let n=e*t&gi;return n&Ie^n>>U(64)}function yb(e,t,n){return rT((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&Ie,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&Ie)}function hl(e,t,n,r,s){let a=e&Ie,i=e>>U(64)&Ie;return a+=yb(t,r,s),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=Ie,i+=yb(n,Ge(r,16),s),i^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),i&=Ie,i<<U(64)|a}function wr(e){let t=e;return t^=t>>U(37),t*=q9,t&=Ie,t^=t>>U(32),t}function Yl(e){let t=e;return t^=t>>U(33),t*=ma,t&=Ie,t^=t>>U(29),t*=eT,t&=Ie,t^=t>>U(32),t}function t5(e,t,n){let r=e.byteLength;Ni(r>0&&r<=3);let s=U(e.getUint8(r-1))|U(r<<8)|U(e.getUint8(0)<<16)|U(e.getUint8(r>>1)<<24),a=(s^(U(t.getUint32(0,!0))^U(t.getUint32(4,!0)))+n)&Ie,i=(U(t.getUint32(8,!0))^U(t.getUint32(12,!0)))-n;return(Yl((X9(G9(s),U(13))^i)&Ie)&Ie)<<U(64)|Yl(a)}function wg(e,t){return e^e>>t}function n5(e,t,n){let r=e.byteLength;Ni(r>=4&&r<=8);{let s=e.getUint32(0,!0),a=e.getUint32(r-4,!0),i=((U(s)|U(a)<<U(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&Ie)*(Is+(U(r)<<U(2)))&gi;return i+=(i&Ie)<<U(65),i&=gi,i^=i>>U(67),wg(wg(i&Ie,U(35))*V9&Ie,U(28))|wr(i>>U(64))<<U(64)}}function r5(e,t,n){let r=e.byteLength;Ni(r>=9&&r<=16);{let s=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&Ie,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&Ie,i=e.getBigUint64(0,!0),o=e.getBigUint64(r-8,!0),c=(i^o^s)*Is,u=(c&Ie)+(U(r-1)<<U(54));c=c&(gi^Ie)|u,o^=a,c+=o+(o&Xl)*(QS-U(1))<<U(64),c&=gi,c^=J9(c>>U(64));let l=(c&Ie)*ma;return l+=(c>>U(64))*ma<<U(64),l&=gi,wr(l&Ie)|wr(l>>U(64))<<U(64)}}function s5(e,t){let n=e.byteLength;return Ni(n<=16),n>8?r5(e,mr,t):n>=4?n5(e,mr,t):n>0?t5(e,mr,t):Yl(t^mr.getBigUint64(64,!0)^mr.getBigUint64(72,!0))|Yl(t^mr.getBigUint64(80,!0)^mr.getBigUint64(88,!0))<<U(64)}function bg(e){return~e+U(1)&Ie}function a5(e,t,n){let r=U(e.byteLength)*Is&Ie,s=U(e.byteLength-1)/U(32);for(;s>=0;){let o=Number(s);r=hl(r,Ge(e,16*o),Ge(e,e.byteLength-16*(o+1)),Ge(t,32*o),n),s-=U(1)}let a=r+(r>>U(64))&Ie;a=wr(a);let i=(r&Ie)*Is+(r>>U(64))*T_+(U(e.byteLength)-n&Ie)*ma;return i&=Ie,i=bg(wr(i)),a|i<<U(64)}function i5(e,t,n){let r=U(e.byteLength)*Is&Ie;for(let i=32;i<160;i+=32)r=hl(r,Ge(e,i-32),Ge(e,i-16),Ge(t,i-32),n);r=wr(r&Ie)|wr(r>>U(64))<<U(64);for(let i=160;i<=e.byteLength;i+=32)r=hl(r,Ge(e,i-32),Ge(e,i-16),Ge(t,3+i-160),n);r=hl(r,Ge(e,e.byteLength-16),Ge(e,e.byteLength-32),Ge(t,103),bg(n));let s=r+(r>>U(64))&Ie;s=wr(s);let a=(r&Ie)*Is+(r>>U(64))*T_+(U(e.byteLength)-n&Ie)*ma;return a&=Ie,a=bg(wr(a)),s|a<<U(64)}function Hs(e,t=U(0)){let n=new TextEncoder,r=Ge(typeof e=="string"?n.encode(e):e),s=r.byteLength,a=i=>i.toString(16).padStart(32,"0");return s<=16?a(s5(r,t)):s<=128?a(a5(r,mr,t)):s<=240?a(i5(r,mr,t)):a(e5(r,mr))}function sT(e){return/^[0-9a-f]{32}$/.test(e)}function yi(e,t,n=!0,r=!1){try{return e[t].get()}catch(s){if(s.name===Et.unminifiable_name){if(r)return s;if(n)return null}throw s}}function ga(e,t,n=!0){if(Array.isArray(t)){let r={};for(let s of t)try{r[s]=yi(e,s,!n)}catch(a){if(a.name===Et.unminifiable_name)continue}return r}else return yi(e,t)}function*o5(e,t){if(e.graph===_r.PARENT)throw new Xe("There is no parent graph.");if(e.goto){let n;Array.isArray(e.goto)?n=e.goto:n=[e.goto];for(let r of n)if(fn(r))yield[yr,_i,r];else if(typeof r=="string")yield[yr,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(sT))for(let[n,r]of Object.entries(e.resume)){let s=t.filter(a=>a[0]===n&&a[1]==="__resume__").map(a=>a[2]).slice(0,1)??[];s.push(r),yield[n,vs,s]}else yield[yr,vs,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[n,r]of e.update)yield[yr,n,r];else for(let[n,r]of Object.entries(e.update))yield[yr,n,r]}}function*aT(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Cf(e,t,n){Array.isArray(e)?(t===!0||t.find(([r,s])=>e.includes(r)))&&(yield ga(n,e)):(t===!0||t.some(([r,s])=>r===e))&&(yield yi(n,e))}function*c5(e,t,n){let r=t.filter(([o,c])=>(o.config===void 0||!o.config.tags?.includes("langsmith:hidden"))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__");if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,u])=>c==="__return__"))?s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===_p).map(([c,u])=>[o.name,u])):Array.isArray(e)?s=r.flatMap(([o])=>{let{writes:c}=o,u={};for(let[l]of c)e.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>e.includes(l)).map(([l,d])=>[o.name,{[l]:d}]):[[o.name,Object.fromEntries(c.filter(([l])=>e.includes(l)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===e).map(([c,u])=>[o.name,u]));let a={};for(let[o,c]of s)o in a||(a[o]=[]),a[o].push(c);let i={};for(let o in a)if(a[o].length===1){let[c]=a[o];i[o]=c}else i[o]=a[o];n&&(i.__metadata__={cached:n}),yield i}function I_(e){let t=typeof e[wt];if(t==="number")return 0;if(t==="string")return"";for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=typeof e[n];if(r==="number")return 0;if(r==="string")return"";break}}function fl(e,t){if(Object.keys(e).length>0){let n=I_(t);return Object.fromEntries(Object.entries(t).filter(([r,s])=>s>(e[r]??n)))}else return t}function u5(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function Yn(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Bs(e,t){let n=t?.parents??{};return Object.keys(n).length>0?Yn(e,{[Mr]:{...n,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function Ql(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};if(typeof AbortSignal.any=="function")return{signal:AbortSignal.any(t),dispose:void 0};let n=new AbortController,r=()=>{let a=t.find(i=>i.aborted)?.reason;n.abort(a),t.forEach(i=>i.removeEventListener("abort",r))};t.forEach(a=>a.addEventListener("abort",r,{once:!0}));let s=t.find(a=>a.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{t.forEach(a=>a.removeEventListener("abort",r))}}}var l5=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t},d5=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:n,retry:r,cache:s,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=s,this.callbacks=a}};function p5(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function h5(e,t){return new Ts({name:e,first:new ja({func:n=>t(...n),name:e,trace:!1,recurse:!1}),last:new Xt([{channel:_p,value:ca}],[dn])})}var f5=e=>e!==void 0?e+1:1;function m5(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function g5(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t==null?t=e[n]:t=S9(t,e[n]));return t}function Pu(e,t,n){let r=I_(e.channel_versions),s=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(s.__start__??r))a=!0;else for(let o in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,o)&&e.channel_versions[o]>(s[o]??r)){a=!0;break}let i=n.some(o=>t==="*"?!o.config?.tags?.includes(dn):t.includes(o.name));return a&&i}function ml(e,t,n,r,s=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(o=>n.writes.some(([c,u])=>c===o)));else{for(let[o]of n.writes)if(o===r){a=new Set([o]);break}a=a||new Set}let i;if(s&&a.size>0){let o=Object.fromEntries(Object.entries(t).filter(([l,d])=>a.has(l))),c=Ks(e,o,-1),u=Gl(o,c);Tn(Jl(c),u,[n],void 0,void 0),i=ga({...t,...u},r)}else i=ga(t,r);return i}function Nf(e,t,n){for(let[r,s]of n)if(["__pregel_push","__pregel_tasks"].includes(r)&&s!=null){if(!fn(s))throw new Xe(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new Xe(`Invalid node name "${s.node}" in Send packet`)}e(n)}var y5=new Set([uy,Zr,vs,Tt,_p,yp]);function Tn(e,t,n,r,s){n.sort((p,h)=>{let f=p.path?.slice(0,3)||[],m=h.path?.slice(0,3)||[];for(let v=0;v<Math.min(f.length,m.length);v+=1){if(f[v]<m[v])return-1;if(f[v]>m[v])return 1}return f.length-m.length});let a=n.some(p=>p.triggers.length>0),i=O_(t);for(let p of n){e.versions_seen[p.name]??={};for(let h of p.triggers)h in e.channel_versions&&(e.versions_seen[p.name][h]=e.channel_versions[h])}let o=g5(e.channel_versions),c=new Set(n.flatMap(p=>p.triggers).filter(p=>!HE.includes(p))),u=!1;for(let p of c)p in i&&i[p].consume()&&r!==void 0&&(e.channel_versions[p]=r(o),u=!0);let l={};for(let p of n)for(let[h,f]of p.writes)y5.has(h)||h in i&&(l[h]??=[],l[h].push(f));o!=null&&r!=null&&(o=u?r(o):o);let d=new Set;for(let[p,h]of Object.entries(l))if(p in i){let f=i[p],m;try{m=f.update(h)}catch(v){if(v.name===Xe.unminifiable_name){let g=new Xe(`Invalid update for channel "${p}" with values ${JSON.stringify(h)}: ${v.message}`);throw g.lc_error_code=v.lc_error_code,g}else throw v}m&&r!==void 0&&(e.channel_versions[p]=r(o),f.isAvailable()&&d.add(p))}if(a)for(let p in i){if(!Object.prototype.hasOwnProperty.call(i,p))continue;let h=i[p];h.isAvailable()&&!d.has(p)&&h.update([])&&r!==void 0&&(e.channel_versions[p]=r(o),h.isAvailable()&&d.add(p))}if(a&&!m5(d,s))for(let p in i){if(!Object.prototype.hasOwnProperty.call(i,p))continue;let h=i[p];h.finish()&&r!==void 0&&(e.channel_versions[p]=r(o),h.isAvailable()&&d.add(p))}return d}function*_5(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let r=new Set;for(let s of n.updatedChannels){let a=n.triggerToNodes[s];for(let i of a??[])r.add(i)}yield*[...r].sort();return}if(!(()=>{for(let r in e.channel_versions)if(e.channel_versions[r]!==null)return!1;return!0})())for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(yield r)}function ci(e,t,n,r,s,a,i){let o={},c=r[_i];if(c?.isAvailable()){let u=c.get().length;for(let l=0;l<u;l+=1){let d=kg([Zr,l],e,t,n,r,s,a,i);d!==void 0&&(o[d.id]=d)}}for(let u of _5(e,n,i)){let l=kg([Qf,u],e,t,n,r,s,a,i);l!==void 0&&(o[l.id]=l)}return o}function kg(e,t,n,r,s,a,i,o){let{step:c,checkpointer:u,manager:l}=o,d=a.configurable??{},p=d.checkpoint_ns??"";if(e[0]==="__pregel_push"&&p5(e[e.length-1])){let h=e[e.length-1],f=h5(h.name,h.func),m=[Zr],v=p===""?h.name:`${p}|${h.name}`,g=ni(JSON.stringify([v,c.toString(),h.name,Zr,e[1],e[2]]),t.id),y=`${v}:${g}`,k=[...e.slice(0,3),!0],x={langgraph_step:c,langgraph_node:h.name,langgraph_triggers:m,langgraph_path:k,langgraph_checkpoint_ns:y};if(i){let S=[];return{name:h.name,input:h.input,proc:f,writes:S,config:qe(jn(a,{metadata:x,store:o.store??a.store}),{runName:h.name,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:g,[ds]:E=>Nf(I=>S.push(...I),r,E),[ra]:(E,I=!1)=>ml(t,s,{name:h.name,writes:S,triggers:m,path:k},E,I),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:g,currentTaskInput:h.input,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(y)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:m,retry_policy:h.retry,cache_key:h.cache?{key:Hs((h.cache.keyFunc??JSON.stringify)([h.input])),ns:[rh,h.name??"__dynamic__"],ttl:h.cache.ttl}:void 0,id:g,path:k,writers:[]}}else return{id:g,name:h.name,interrupts:[],path:k}}else if(e[0]==="__pregel_push"){let h=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s.__pregel_tasks?.isAvailable())return;let f=s[_i].get();if(h<0||h>=f.length)return;let m=em(f[h])&&!fn(f[h])?new Jo(f[h].node,f[h].args):f[h];if(!em(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in r)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}let v=[Zr],g=p===""?m.node:`${p}|${m.node}`,y=ni(JSON.stringify([g,c.toString(),m.node,Zr,h.toString()]),t.id),k=`${g}:${y}`,x={langgraph_step:c,langgraph_node:m.node,langgraph_triggers:v,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:k};if(i){let S=r[m.node],E=S.getNode();if(E!==void 0){S.metadata!==void 0&&(x={...x,...S.metadata});let I=[];return{name:m.node,input:m.args,proc:E,subgraphs:S.subgraphs,writes:I,config:qe(jn(a,{metadata:x,tags:S.tags,store:o.store??a.store}),{runName:m.node,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:y,[ds]:w=>Nf(P=>I.push(...P),r,w),[ra]:(w,P=!1)=>ml(t,s,{name:m.node,writes:I,triggers:v,path:e},w,P),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:y,currentTaskInput:m.args,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(k)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:v,retry_policy:S.retryPolicy,cache_key:S.cachePolicy?{key:Hs((S.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[rh,S.name??"__dynamic__",m.node],ttl:S.cachePolicy.ttl}:void 0,id:y,path:e,writers:S.getWriters()}}}else return{id:y,name:m.node,interrupts:[],path:e}}else if(e[0]==="__pregel_pull"){let h=e[1].toString(),f=r[h];if(f===void 0)return;if(n?.length){let y=p===""?h:`${p}|${h}`,k=ni(JSON.stringify([y,c.toString(),h,Qf,h]),t.id);if(n.some(x=>x[0]===k&&x[1]!=="__error__"))return}let m=I_(t.channel_versions);if(m===void 0)return;let v=t.versions_seen[h]??{},g=f.triggers.find(y=>s[y].isAvailable()?(t.channel_versions[y]??m)>(v[y]??m):!1);if(g!==void 0){let y=v5(f,s,i);if(y===void 0)return;let k=p===""?h:`${p}|${h}`,x=ni(JSON.stringify([k,c.toString(),h,Qf,[g]]),t.id),S=`${k}:${x}`,E={langgraph_step:c,langgraph_node:h,langgraph_triggers:[g],langgraph_path:e,langgraph_checkpoint_ns:S};if(i){let I=f.getNode();if(I!==void 0){f.metadata!==void 0&&(E={...E,...f.metadata});let w=[];return{name:h,input:y,proc:I,subgraphs:f.subgraphs,writes:w,config:qe(jn(a,{metadata:E,tags:f.tags,store:o.store??a.store}),{runName:h,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ku]:x,[ds]:P=>Nf(A=>{w.push(...A)},r,P),[ra]:(P,A=!1)=>ml(t,s,{name:h,writes:w,triggers:[g],path:e},P,A),[Fr]:u??d.__pregel_checkpointer,[Mr]:{...d[Mr],[p]:t.id},[ps]:Pf({pendingWrites:n??[],taskId:x,currentTaskInput:y,resumeMap:a.configurable?.[Xu],namespaceHash:Hs(S)}),[Yu]:t.channel_values[sh],checkpoint_id:void 0,checkpoint_ns:S}}),triggers:[g],retry_policy:f.retryPolicy,cache_key:f.cachePolicy?{key:Hs((f.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[rh,f.name??"__dynamic__",h],ttl:f.cachePolicy.ttl}:void 0,id:x,path:e,writers:f.getWriters()}}}else return{id:x,name:h,interrupts:[],path:e}}}}function v5(e,t,n){let r;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){r={};for(let[s,a]of Object.entries(e.channels))if(e.triggers.includes(a))try{r[s]=yi(t,a,!1)}catch(i){if(i.name===Et.unminifiable_name)return;throw i}else if(a in t)try{r[s]=yi(t,a,!1)}catch(i){if(i.name===Et.unminifiable_name)continue;throw i}}else if(Array.isArray(e.channels)){let s=!1;for(let a of e.channels)try{r=yi(t,a,!1),s=!0;break}catch(i){if(i.name===Et.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function w5(e,t){if(typeof e.args!="object"||e.args===null)return e;let n={};for(let[r,s]of Object.entries(e.args)){let a=t[r];(!a||a.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new Jo(e.node,n)}function Pf({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:s}){let a=e.find(([o,c])=>o==="00000000-0000-0000-0000-000000000000"&&c==="__resume__")?.[2],i={callCounter:0,interruptCounter:-1,resume:(()=>{let o=e.filter(([c,u])=>c===t&&u==="__resume__").flatMap(([c,u,l])=>l);if(r!=null&&s in r){let c=r[s];o.push(c)}return o})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(i.nullResume)return delete i.nullResume,e.splice(e.findIndex(([o,c])=>o==="00000000-0000-0000-0000-000000000000"&&c==="__resume__"),1),a}};return i}var pc={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},hc=(e,t)=>`${e.start}${t}${e.end}`;function*_b(e){for(let{id:t,name:n,input:r,config:s,triggers:a,writes:i}of e)s?.tags?.includes("langsmith:hidden")||(yield{id:t,name:n,input:r,triggers:a,interrupts:i.filter(([o,c])=>o===t&&c==="__interrupt__").map(([,o])=>o)})}function b5(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function iT(e){let t={};for(let[n,r]of e){let s=String(n);if(s in t){let a=b5(t[s])?t[s].$writes:[t[s]];a.push(r),t[s]={$writes:a}}else t[s]=r}return t}function*k5(e,t){for(let[{id:n,name:r,config:s},a]of e)s?.tags?.includes("langsmith:hidden")||(yield{id:n,name:r,result:iT(a.filter(([i])=>Array.isArray(t)?t.includes(i):i===t)),interrupts:a.filter(i=>i[0]===Tt).map(i=>i[1])})}function*x5(e,t,n,r,s,a,i,o){function c(d){let p={};return d.callbacks!=null&&(p.callbacks=d.callbacks),d.configurable!=null&&(p.configurable=d.configurable),d.maxConcurrency!=null&&(p.max_concurrency=d.maxConcurrency),d.metadata!=null&&(p.metadata=d.metadata),d.recursionLimit!=null&&(p.recursion_limit=d.recursionLimit),d.runId!=null&&(p.run_id=d.runId),d.runName!=null&&(p.run_name=d.runName),d.tags!=null&&(p.tags=d.tags),p}let u=e.configurable?.checkpoint_ns,l={};for(let d of s){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(XS))continue;let p=`${d.name}:${d.id}`;u&&(p=`${u}|${p}`),l[d.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:p}}}yield{config:c(e),values:ga(t,n),metadata:r,next:s.map(d=>d.name),tasks:oT(s,a,l,o),parentConfig:i?c(i):void 0}}function oT(e,t,n,r){return e.map(s=>{let a=t.find(([u,l])=>u===s.id&&l==="__error__")?.[2],i=t.filter(([u,l])=>u===s.id&&l==="__interrupt__").map(([,,u])=>u),o=(()=>{if(a||i.length||!t.length)return;let u=t.findIndex(([l,d])=>l===s.id&&d==="__return__");if(u>=0)return t[u][2];if(typeof r=="string")return t.find(([l,d])=>l===s.id&&d===r)?.[2];if(Array.isArray(r)){let l=t.filter(([d,p])=>d===s.id&&r.includes(p)).map(([,d,p])=>[d,p]);return l.length?iT(l):void 0}})();if(a)return{id:s.id,name:s.name,path:s.path,error:a,interrupts:i,result:o};let c=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...c!==void 0?{state:c}:{},result:o}})}function O5(e,t,n){console.log([`${hc(pc.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
257
257
  `,JSON.stringify(ga(t,n),null,2)].join(""))}function cT(e,t){let n=t.length;console.log([`${hc(pc.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${n} task${n===1?"":"s"}:\x1B[0m
258
258
  `,t.map(r=>`- ${hc(pc.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
259
259
  `)].join(""))}function S5(e,t,n){let r={};for(let[s,a]of t)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(a));console.log([`${hc(pc.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
@@ -263,7 +263,7 @@ data: ${I5(s.data)}
263
263
 
264
264
  `))};try{for await(let s of e){let[a,i,o]=s,c=o;if(i==="debug"){let u=o;u.type==="checkpoint"&&(c={...u,payload:bb(u.payload)})}i==="checkpoints"&&(c=bb(o)),r({event:a?.length?`${i}|${a.join("|")}`:i,data:c})}}catch(s){r({event:"error",data:E5(s)})}n.close()}})}var ju=Symbol.for("INPUT_DONE"),Rf=Symbol.for("INPUT_RESUMING"),$5=25;function C5(...e){return new uT({passthroughFn:t=>{for(let n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var N5=class extends C9{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>{},()=>{}),n}},P5=class lT{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if("__start__"in this.checkpoint.channel_versions)t=!0;else for(let o in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,o)){t=!0;break}let n=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,r=this.input===null||this.input===void 0,s=Ut(this.input)&&this.input.resume!=null,a=this.input===Rf,i=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(n||r||s||a||i)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=f5,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new N5(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=C5(r,n.configurable[cy]));let s=n.configurable?!("checkpoint_id"in n.configurable):!0,a=n.configurable?.[ps];n.configurable&&a&&(a.subgraphCounter>0&&(n=Yn(n,{[Br]:[n.configurable[Br],a.subgraphCounter.toString()].join("|")})),a.subgraphCounter+=1);let i=ra in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Yn(n,{checkpoint_ns:"",checkpoint_id:void 0}));let o=n;n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(o=Yn(n,{checkpoint_id:n.configurable[Mr][n.configurable?.checkpoint_ns]}));let c=n.configurable?.checkpoint_ns?.split("|")??[],u=await t.checkpointer?.getTuple(o)??{config:n,checkpoint:BS(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...n,...u.config,configurable:{checkpoint_ns:"",...n.configurable,...u.config.configurable}};let l=u.parentConfig,d=Jl(u.checkpoint),p={...u.metadata},h=u.pendingWrites??[],f=Gl(t.channelSpecs,d),m=(p.step??0)+1,v=m+(n.recursionLimit??$5)+1,g={...d.channel_versions},y=t.store?new $9(t.store):void 0;return y&&await y.start(),new lT({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:p,checkpointConfig:o,prevCheckpointConfig:l,checkpointNamespace:c,channels:f,isNested:i,manager:t.manager,skipDoneTasks:s,step:m,stop:v,checkpointPreviousVersions:g,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:y,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,n){let r=n;if(r.length===0)return;r.every(([c])=>c in T9)&&(r=Array.from(new Map(r.map(c=>[c[0],c])).values()));let s=!1;for(let c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.channels[c].lc_graph_name==="UntrackedValue"){s=!0;break}let a=r;s&&(a=r.filter(([c])=>{let u=this.channels[c];return!u||u.lc_graph_name!=="UntrackedValue"}).map(([c,u])=>c==="__pregel_tasks"&&fn(u)?[c,w5(u,this.channels)]:[c,u])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,u]of a)this.checkpointPendingWrites.push([t,c,u]);let i=Yn(this.checkpointConfig,{[Br]:this.config.configurable?.checkpoint_ns??"",[Yf]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(i,a,t)),this.tasks&&this._outputWrites(t,r),!n.length||!this.cache||!this.tasks)return;let o=this.tasks[t];o==null||o.cache_key==null||n[0][0]==="__error__"||n[0][0]==="__interrupt__"||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(t,n,r=!1){let s=this.tasks[t];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes("langsmith:hidden"))return;if(n.length>0)if(n[0][0]==="__interrupt__"){if(s.path?.[0]==="__pregel_push"&&s.path?.[s.path.length-1]===!0)return;let a=n.filter(i=>i[0]===Tt).flatMap(i=>i[1]);this._emit([["updates",{[Tt]:a}],["values",{[Tt]:a}]])}else n[0][0]!=="__error__"&&this._emit(xo(Qr(c5(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(xo(Qr(k5([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],n=([i,o])=>`ns:${i.join(",")}|key:${o}`,r=[],s={};for(let i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];let a=await this.cache.get(r);for(let{key:i,value:o}of a){let c=s[n(i)];c!=null&&(c.writes.push(...o),t.push({task:c,result:o}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:n=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ju,Rf].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new hi;if(Object.values(this.tasks).every(s=>s.writes.length>0)){let s=Object.values(this.tasks).flatMap(i=>i.writes);this.updatedChannels=Tn(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let a=await is(Qr(Cf(this.outputKeys,s,this.channels),"values"));if(this._emit(a),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Pu(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new hi;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Tl]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=ci(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await is(Qr(x5(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[s,a,i]of this.checkpointPendingWrites){if(a==="__error__"||a==="__interrupt__"||a==="__resume__")continue;let o=Object.values(this.tasks).find(c=>c.id===s);o&&o.writes.push([a,i])}for(let s of Object.values(this.tasks))s.writes.length>0&&this._outputWrites(s.id,s.writes,!0)}if(Object.values(this.tasks).every(s=>s.writes.length>0))return this.tick({inputKeys:n});if(Pu(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new hi;let r=await is(Qr(_b(Object.values(this.tasks)),"tasks"));return this._emit(r),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(r=>!r.includes(":")))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let n=this._suppressInterrupt(t);return(n||t===void 0)&&(this.output=ga(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=Tn(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(xo(Qr(Cf(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),ti(t)&&!t.interrupts.length&&this._emit([["updates",{[Tt]:[]}],["values",{[Tt]:[]}]])),n}async acceptPush(t,n,r){if(this.interruptAfter?.length>0&&Pu(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let s=kg([Zr,t.path??[],n,t.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&Pu(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(xo(Qr(_b([s]),"tasks"))),this.debug&&cT(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});let a=await this._matchCachedWrites();for(let{task:i}of a)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(t){return ti(t)&&!this.isNested}async _first(t){let{configurable:n}=this.config,r=n?.[ps];if(r&&r.nullResume!==void 0&&this.putWrites(yr,[[vs,r.nullResume]]),Ut(this.input)){let i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(sT)&&(this.config.configurable??={},this.config.configurable[Xu]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let o={};for(let[c,u,l]of o5(this.input,this.checkpointPendingWrites))o[c]??=[],o[c].push([u,l]);if(Object.keys(o).length===0)throw new k0("Received empty Command input");for(let[c,u]of Object.entries(o))this.putWrites(c,u)}let s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===yr).map(i=>i.slice(1));s.length>0&&Tn(this.checkpoint,this.channels,[{name:as,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let a=Ut(this.input)&&s.length>0;if(this.isResuming||a){for(let o in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,o)&&this.checkpoint.channel_versions[o]!==void 0){let c=this.checkpoint.channel_versions[o];this.checkpoint.versions_seen[Tt]={...this.checkpoint.versions_seen[Tt],[o]:c}}let i=await is(Qr(Cf(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=Rf;else if(a)await this._putCheckpoint({source:"input"}),this.input=ju;else{let i=await is(aT(t,this.input));if(i.length>0){let o=ci(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Tn(this.checkpoint,this.channels,Object.values(o).concat([{name:as,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=ju}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=ju;else throw new k0(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=Yn(this.config,{[Tl]:this.isResuming}))}_emit(t){for(let[n,r]of t)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){let s=n==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:a,payload:r}])}}_putCheckpoint(t){let n=this.checkpointMetadata===t,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=a=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Yn(this.checkpointConfig,{[Br]:this.config.configurable?.checkpoint_ns??""});let i={...this.checkpoint.channel_versions},o=fl(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Jl(a),metadata:{...this.checkpointMetadata},newVersions:o}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}),this.checkpoint=Ks(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=Yn(this.checkpointConfig,{[Br]:this.config.configurable?.checkpoint_ns??"",[Yf]:this.checkpoint.id}),n={};for(let[r,s,a]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,a]);for(let[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(t,s,r))}_matchWrites(t){for(let[n,r,s]of this.checkpointPendingWrites){if(r==="__error__"||r==="__interrupt__"||r==="__resume__")continue;let a=Object.values(t).find(i=>i.id===n);a&&a.writes.push([r,s])}for(let n of Object.values(t))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function j5(e){return jt(e?.message)}var R5=class extends Ca{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let s=t.id;n!=null&&(ky(t)?s??=`run-${n}-tool-${t.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,n,r,s,a,i,o){i&&(!a||!a.includes("langsmith:nostream")&&!a.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:a,name:o,...i}])}handleLLMNewToken(e,t,n,r,s,a){let i=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(j5(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new mn({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];jt(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,s,a,i,o){if(a!==void 0&&o===a.langgraph_node&&(s===void 0||!s.includes("langsmith:hidden"))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}],typeof t=="object")){for(let c of Object.values(t))if((jt(c)||Xo(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let u of c)(jt(u)||Xo(u))&&u.id!==void 0&&(this.seen[u.id]=u)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(jt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)jt(r)&&this._emit(n,r,t,!0);else if(e!=null&&typeof e=="object"){for(let r of Object.values(e))if(jt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let s of r)jt(s)&&this._emit(n,s,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}},M5=[400,401,402,403,404,405,406,407,409],L5=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;let t=e?.response?.status??e?.status;return!(t&&M5.includes(+t)||e?.error?.code==="insufficient_quota")};async function dT(e,t,n,r){let s=e.retry_policy??t,a=s!==void 0?s.initialInterval??500:0,i=0,o,c,{config:u}=e;for(n&&(u=Yn(u,n)),u={...u,signal:r};!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{c=await e.proc.invoke(e.input,u);break}catch(l){if(o=l,o.pregelTaskId=e.id,XE(o)){let h=u?.configurable?.checkpoint_ns,f=o.command;if(f.graph===h){for(let m of e.writers)await m.invoke(f,u);o=void 0;break}else if(f.graph===_r.PARENT){let m=z9(h);o.command=new _r({...o.command,graph:m})}}if(el(o)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??L5)(o))break;a=Math.min(s.maxInterval??128e3,a*(s.backoffFactor??2));let d=s.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(h=>setTimeout(h,d));let p=o.name??o.constructor.unminifiable_name??o.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${i}) after ${p}: ${o}`),u=Yn(u,{[Tl]:!0})}}return{task:e,result:c,error:o,signalAborted:r?.aborted}}var xg=Symbol.for("promiseAdded");function z5(){let e={next:()=>{},wait:Promise.resolve(xg)};function t(n){e.next=()=>{e.wait=new Promise(t),n(xg)}}return e.wait=new Promise(t),e}var U5=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=e,a=new Set,i,o=new AbortController,c=o.signal,u=t?AbortSignal.timeout(t):void 0,l=Object.values(this.loop.tasks).filter(f=>f.writes.length===0),{signals:d,disposeCombinedSignal:p}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:e.signal}),h=this._executeTasksWithRetry(l,{signals:d,retryPolicy:n,maxConcurrency:s});for await(let{task:f,error:m,signalAborted:v}of h)this._commit(f,m),ti(m)||el(m)&&!ti(i)?i=m:m&&(a.size===0||!v)&&(o.abort(),a.add(m));if(p?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(f=>f.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(ti(i)||el(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},s=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:i,dispose:o}=Ql(s,a,e),c={externalAbortSignal:s,timeoutAbortSignal:a,composedAbortSignal:i};return this.loop.config=Yn(this.loop.config,{[VE]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:s}=t??{},a=z5(),i={},o={executingTasksMap:i,barrier:a,retryPolicy:n,scheduleTask:async(p,h,f)=>this.loop.acceptPush(p,h,f)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,u,l=Ql(s?.externalAbortSignal,s?.timeoutAbortSignal),d=l.signal?new Promise((p,h)=>{u=()=>h(new Error("Abort")),l.signal?.addEventListener("abort",u,{once:!0})}):void 0;for(;(c===0||Object.keys(i).length>0)&&e.length;){for(;Object.values(i).length<(r??e.length)&&c<e.length;c+=1){let h=e[c];i[h.id]=dT(h,n,{[oy]:pT?.bind(o,this,h)},s?.composedAbortSignal).catch(f=>({task:h,error:f,signalAborted:s?.composedAbortSignal?.aborted}))}let p=await Promise.race([...Object.values(i),...d?[d]:[],a.wait]);p!==xg&&(yield p,u!=null&&(l.signal?.removeEventListener("abort",u),l.dispose?.()),delete i[p.task.id])}}_commit(e,t){if(t!==void 0)if(ti(t)){if(t.interrupts.length){let n=t.interrupts.map(s=>[Tt,s]),r=e.writes.filter(s=>s[0]===vs);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else el(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[yp,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([uy,null]),this.loop.putWrites(e.id,e.writes)}};async function pT(e,t,n,r,s,a={}){let i=t.config?.configurable?.[ps];if(!i)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let o=i.callCounter;i.callCounter+=1;let c=new d5({func:n,name:r,input:s,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),u=await this.scheduleTask(t,o,c);if(!u)return;let l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){let d=u.writes.filter(([h])=>h===_p),p=u.writes.filter(([h])=>h===yp);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(p.length>0){if(p.length===1){let h=p[0][1],f=h instanceof Error?h:new Error(String(h));return Promise.reject(f)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{let d=dT(u,a.retry,{[oy]:pT.bind(this,e,u)});return this.executingTasksMap[u.id]=d,this.barrier.next(),d.then(({result:p,error:h})=>h?Promise.reject(h):p)}}var Nr=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function D5({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new Nr("Channels not provided");let o=new Set,c=new Set;for(let[u,l]of Object.entries(e)){if(u==="__interrupt__")throw new Nr(`"Node name ${Tt} is reserved"`);if(l.constructor===dc)l.triggers.forEach(d=>o.add(d));else throw new Nr(`Invalid node type ${typeof l}, expected PregelNode`)}for(let u of o)if(!(u in t))throw new Nr(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(n)){if(n.every(u=>!o.has(u)))throw new Nr(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new Nr(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(u=>c.add(u)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(u=>c.add(u));for(let u of c)if(!(u in t))throw new Nr(`Output channel '${String(u)}' not in channels`);if(a&&a!=="*"){for(let u of a)if(!(u in e))throw new Nr(`Node ${String(u)} not in nodes`)}if(i&&i!=="*"){for(let u of i)if(!(u in e))throw new Nr(`Node ${String(u)} not in nodes`)}}function kb(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var F5=class hT extends Ls{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new hT({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(t){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);let r=t.flat();if(r.length>0)if(this.unique)for(let s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Et;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function B5(e){let t=Mt.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let n=t.configurable;if(!n)throw new Error("No configurable found in config");if(!n.__pregel_checkpointer)throw new Qu("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let r=n[ps];r.interruptCounter+=1;let s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return n[ds]?.([[vs,r.resume]]),r.resume[s];if(r.nullResume!==void 0){if(r.resume.length!==s)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${s}`);let i=r.consumeNullResume();return r.resume.push(i),n[ds]?.([[vs,r.resume]]),i}let a=n[Br]?.split("|");throw new hi([{id:a?Hs(a.join("|")):void 0,value:e}])}var Z5=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof e=="string"?n?s={[n]:e}:s=[e]:s=Object.fromEntries(e.map(a=>[a,a])),new dc({channels:s,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let r of e)n.push({channel:r,value:ca,skipNone:!1});for(let[r,s]of Object.entries(t??{}))je.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:ca,skipNone:!0,mapper:Rt(s)}):n.push({channel:r,value:s,skipNone:!1});return new Xt(n)}},q5=class extends je{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},V5=class extends q5{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${_i}' is reserved and cannot be used in the graph.`);this.channels[_i]=new F5({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){let t=jn(this.config,e);return new this.constructor({...this,config:t})}validate(){D5({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let s=r.subgraphs?.length?r.subgraphs:[r.bound];for(let a of s){let i=XS(a);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let o=e;e!==void 0&&(o=e.slice(n.length+1));for(let[c,u]of i.getSubgraphs(o,t))yield[`${n}|${c}`,u]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let s=Gl(this.channels,t.checkpoint);if(t.pendingWrites?.length){let d=t.pendingWrites.filter(([p,h])=>p===yr).map(([p,h,f])=>[String(h),f]);d.length>0&&Tn(t.checkpoint,s,[{name:as,writes:d,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(ci(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),i=await is(this.getSubgraphsAsync()),o=t.config.configurable?.checkpoint_ns??"",c={};for(let d of a){let p=i.find(([f])=>f===d.name);if(!p)continue;let h=`${String(d.name)}:${d.id}`;if(o&&(h=`${o}|${h}`),n===void 0){let f={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:h}};c[d.id]=f}else{let f={configurable:{[Fr]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:h}},m=p[1];c[d.id]=await m.getState(f,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let d=Object.fromEntries(a.map(h=>[h.id,h]));for(let[h,f,m]of t.pendingWrites)["__error__","__interrupt__",tl].includes(f)||h in d&&d[h].writes.push([String(f),m]);let p=a.filter(h=>h.writes.length>0);p.length>0&&Tn(t.checkpoint,s,p,void 0,this.triggerToNodes)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});let l=a.filter(d=>d.writes.length===0).map(d=>d.name);return{values:ga(s,this.streamChannelsAsIs),next:l,tasks:oT(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:u,config:Bs(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Qu("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.__pregel_checkpointer===void 0){let i=Ef(r);for await(let[o,c]of this.getSubgraphsAsync(i,!0))if(o===i)return await c.getState(Da(e,{[Fr]:n}),{subgraphs:t?.subgraphs})}let s=jn(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Qu("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.__pregel_checkpointer===void 0){let a=Ef(r);for await(let[i,o]of this.getSubgraphsAsync(a,!0))if(i===a){yield*o.getStateHistory(Da(e,{[Fr]:n}),t);return}}let s=jn(this.config,e,{configurable:{checkpoint_ns:r}});for await(let a of n.list(s,t))yield this._prepareStateSnapshot({config:a.config,saved:a})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Qu("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(i=>i.updates.length===0))throw new Error("No updates provided");let r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.__pregel_checkpointer===void 0){let i=Ef(r);for await(let[,o]of this.getSubgraphsAsync(i,!0))return await o.bulkUpdateState(Da(e,{[Fr]:n}),t);throw new Error(`Subgraph "${i}" not found`)}let s=async(i,o)=>{let c=this.config?jn(this.config,i):i,u=await n.getTuple(c),l=u!==void 0?Jl(u.checkpoint):BS(),d={...u?.checkpoint.channel_versions},p=u?.metadata?.step??-1,h=Da(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),f=c.metadata??{};u?.config.configurable&&(h=Da(c,u.config.configurable),f={...u.metadata,...f});let{values:m,asNode:v}=o[0];if(m==null&&v===void 0){if(o.length>1)throw new Xe("Cannot create empty checkpoint with multiple updates");return Bs(await n.put(h,Ks(l,void 0,p),{source:"update",step:p+1,parents:u?.metadata?.parents??{}},{}),u?u.metadata:void 0)}let g=Gl(this.channels,l);if(m===null&&v==="__end__"){if(o.length>1)throw new Xe("Cannot apply multiple updates when clearing state");if(u){let I=ci(l,u.pendingWrites||[],this.nodes,g,u.config,!0,{step:(u.metadata?.step??-1)+1,checkpointer:n,store:this.store}),w=(u.pendingWrites||[]).filter(P=>P[0]===yr).map(P=>P.slice(1));w.length>0&&Tn(l,g,[{name:as,writes:w,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[P,A,Z]of u.pendingWrites||[])["__error__","__interrupt__",tl].includes(A)||P in I&&I[P].writes.push([A,Z]);Tn(l,g,Object.values(I),n.getNextVersion.bind(n),this.triggerToNodes)}return Bs(await n.put(h,Ks(l,g,p),{...f,source:"update",step:p+1,parents:u?.metadata?.parents??{}},fl(d,l.channel_versions)),u?u.metadata:void 0)}if(v==="__copy__"){if(o.length>1)throw new Xe("Cannot copy checkpoint with multiple updates");if(u==null)throw new Xe("Cannot copy a non-existent checkpoint");let I=A=>!Array.isArray(A)||A.length===0?!1:A.every(Z=>Array.isArray(Z)&&Z.length===2),w=Ks(l,void 0,p),P=await n.put(u.parentConfig??Da(u.config,{checkpoint_id:void 0}),w,{source:"fork",step:p+1,parents:u.metadata?.parents??{}},{});if(I(m)){let A=ci(w,u.pendingWrites,this.nodes,g,P,!1,{step:p+2}),Z=Object.values(A).reduce((rt,{name:B,id:L})=>(rt[B]??=[],rt[B].push({id:L}),rt),{}),ze=m.reduce((rt,B)=>{let[L,z]=B;rt[z]??=[];let ee=rt[z].length,oe=Z[z]?.[ee]?.id;return rt[z].push({values:L,asNode:z,taskId:oe}),rt},{});return s(Bs(P,u.metadata),Object.values(ze).flat())}return Bs(P,u.metadata)}if(v==="__input__"){if(o.length>1)throw new Xe("Cannot apply multiple updates when updating as input");let I=await is(aT(this.inputChannels,m));if(I.length===0)throw new Xe(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Tn(l,g,[{name:as,writes:I,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let w=u?.metadata?.step!=null?u.metadata.step+1:-1,P=await n.put(h,Ks(l,g,w),{source:"input",step:w,parents:u?.metadata?.parents??{}},fl(d,l.channel_versions));return await n.putWrites(P,I,ni(as,l.id)),Bs(P,u?u.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&u?.pendingWrites!==void 0&&u.pendingWrites.length>0){let I=ci(l,u.pendingWrites,this.nodes,g,u.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(u.metadata?.step??-1)+1}),w=(u.pendingWrites??[]).filter(A=>A[0]===yr).map(A=>A.slice(1));w.length>0&&Tn(u.checkpoint,g,[{name:as,writes:w,triggers:[]}],void 0,this.triggerToNodes);for(let[A,Z,ze]of u.pendingWrites)["__error__","__interrupt__",tl].includes(Z)||I[A]===void 0||I[A].writes.push([Z,ze]);let P=Object.values(I).filter(A=>A.writes.length>0);P.length>0&&Tn(l,g,P,void 0,this.triggerToNodes)}let y=Object.values(l.versions_seen).map(I=>Object.values(I)).flat().find(I=>!!I),k=[];if(o.length===1){let{values:I,asNode:w,taskId:P}=o[0];if(w===void 0&&Object.keys(this.nodes).length===1)[w]=Object.keys(this.nodes);else if(w===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(w=this.inputChannels);else if(w===void 0){let A=Object.entries(l.versions_seen).map(([Z,ze])=>Object.values(ze).map(rt=>[rt,Z])).flat().filter(([Z,ze])=>ze!==Tt).sort(([Z],[ze])=>ZS(Z,ze));A&&(A.length===1?w=A[0][1]:A[A.length-1][0]!==A[A.length-2][0]&&(w=A[A.length-1][1]))}if(w===void 0)throw new Xe('Ambiguous update, specify "asNode"');k.push({values:I,asNode:w,taskId:P})}else for(let{asNode:I,values:w,taskId:P}of o){if(I==null)throw new Xe('"asNode" is required when applying multiple updates');k.push({values:w,asNode:I,taskId:P})}let x=[];for(let{asNode:I,values:w,taskId:P}of k){if(this.nodes[I]===void 0)throw new Xe(`Node "${I.toString()}" does not exist`);let A=this.nodes[I].getWriters();if(!A.length)throw new Xe(`No writers found for node "${I.toString()}"`);x.push({name:I,input:w,proc:A.length>1?Ts.from(A,{omitSequenceTags:!0}):A[0],writes:[],triggers:[Tt],id:P??ni("__interrupt__",l.id),writers:[]})}for(let I of x)await I.proc.invoke(I.input,qe({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[ds]:w=>I.writes.push(...w),[ra]:(w,P=!1)=>ml(l,g,I,w,P)}}));for(let I of x){let w=I.writes.filter(P=>P[0]!==Zr);u!==void 0&&w.length>0&&await n.putWrites(h,w,I.id)}Tn(l,g,x,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let S=fl(d,l.channel_versions),E=await n.put(h,Ks(l,g,p+1),{source:"update",step:p+1,parents:u?.metadata?.parents??{}},S);for(let I of x){let w=I.writes.filter(P=>P[0]===Zr);w.length>0&&await n.putWrites(E,w,I.id)}return Bs(E,u?u.metadata:void 0)},a=e;for(let{updates:i}of t)a=await s(a,i);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:a,interruptBefore:i,...o}=e,c=!0,u=t!==void 0?t:this.debug,l=s;l===void 0?l=this.streamChannelsAsIs:kb(l,this.channels);let d=r;d===void 0?d=this.inputChannels:kb(d,this.channels);let p=i??this.interruptBefore??[],h=a??this.interruptAfter??[],f;n!==void 0?(f=Array.isArray(n)?n:[n],c=typeof n=="string"):(e.configurable?.__pregel_task_id!==void 0?f=["values"]:f=this.streamMode,c=!0);let m;if(this.checkpointer===!1)m=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)m=e.configurable[Fr];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");m=this.checkpointer}let v=e.store??this.store,g=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let y=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),k=e.durability??y??e?.configurable?.__pregel_durability??"async";return[u,f,d,l,o,p,h,m,v,c,g,k]}async stream(e,t){let n=new AbortController,{signal:r,dispose:s}=Ql(t?.signal,n.signal),a={recursionLimit:this.config?.recursionLimit,...t,signal:r},i=await super.stream(e,a);return new vb(t?.encoding==="text/event-stream"?A5(i):i,n,s)}streamEvents(e,t,n){let r=new AbortController,{signal:s,dispose:a}=Ql(t?.signal,r.signal),i={recursionLimit:this.config?.recursionLimit,...t,callbacks:l5(this.config?.callbacks,t?.callbacks),signal:s};return new vb(super.streamEvents(e,i,n),r,a)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n="version"in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,s=GS(this.config,t);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let a=await this._validateInput(e),{runId:i,...o}=s,[c,u,,l,d,p,h,f,m,v,g,y]=this._defaults(o);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);let k=new uT({modes:new Set(u)});if(this.checkpointer===!0){d.configurable??={};let P=d.configurable.checkpoint_ns??"";d.configurable[Br]=P.split("|").map(A=>A.split(":")[0]).join("|")}if(u.includes("messages")){let P=new R5(Z=>k.push(Z)),{callbacks:A}=d;if(A===void 0)d.callbacks=[P];else if(Array.isArray(A))d.callbacks=A.concat(P);else{let Z=A.copy();Z.addHandler(P,!0),d.callbacks=Z}}if(u.includes("tools")){let P=new T5(Z=>k.push(Z)),{callbacks:A}=d;if(A===void 0)d.callbacks=[P];else if(Array.isArray(A))d.callbacks=A.concat(P);else{let Z=A.copy();Z.addHandler(P,!0),d.callbacks=Z}}d.writer??=P=>{if(!u.includes("custom"))return;let A=L9()?.configurable?.[Br]?.split("|").slice(0,-1);k.push([A??[],"custom",P])},d.interrupt??=this.userInterrupt??B5;let x=await(await tn(d))?.handleChainStart(this.toJSON(),u5(e,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),S=O_(this.channels),E,I,w=(async()=>{try{E=await P5.initialize({input:a,config:d,checkpointer:f,nodes:this.nodes,channelSpecs:S,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:m,cache:g,stream:k,interruptAfter:h,interruptBefore:p,manager:x,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let P=new U5({loop:E,nodeFinished:d.configurable?.[qE]});t?.subgraphs&&(E.config.configurable={...E.config.configurable,[cy]:E.stream}),await this._runLoop({loop:E,runner:P,debug:c,config:d}),y==="sync"&&await Promise.all(E?.checkpointerPromises??[])}catch(P){I=P}finally{try{E&&(await E.store?.stop(),await E.cache?.stop()),await Promise.all(E?.checkpointerPromises??[])}catch(P){I=I??P}I?k.error(I):k.close()}})();try{for await(let P of k){if(P===void 0)throw new Error("Data structure error.");let[A,Z,ze]=P;if(u.includes(Z)){if(n==="text/event-stream"){r?yield[A,Z,ze]:yield[null,Z,ze];continue}r&&!v?yield[A,Z,ze]:v?r?yield[A,ze]:yield ze:yield[Z,ze]}}}catch(P){throw await x?.handleChainError(I),P}finally{await w}await x?.handleChainEnd(E?.output??{},i,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??"values",r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],a=await this.stream(e,r),i=[],o;for await(let c of a)n==="values"?ek(c)?i.push(c[Tt]):o=c:s.push(c);if(n==="values"){if(i.length>0){let c=i.flat(1);if(o==null)return{[Tt]:c};if(typeof o=="object")return{...o,[Tt]:c}}return o}return s}async _runLoop(e){let{loop:t,runner:n,debug:r,config:s}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:i}of await t._matchCachedWrites())t._outputWrites(i.id,i.writes,!0);r&&O5(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&cT(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,o)=>{r&&S5(i,o,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="out_of_steps")throw new KE([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(a=i,!await t.finishAndHandleError(a))throw i}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Pi=class fT extends Ls{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let n=new fT(this.guard);return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0){let n=this.value.length>0;return this.value=[],n}if(t.length!==1&&this.guard)throw new Xe("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Et;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Et;return this.value[0]}isAvailable(){return this.value.length!==0}};function Ce(e,t,n){function r(o,c){var u;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(u=o._zod).traits??(u.traits=new Set),o._zod.traits.add(e),t(o,c);for(let l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=c}let s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:e});function i(o){var c;let u=n?.Parent?new a:this;r(u,o),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>n?.Parent&&o instanceof n.Parent?!0:o?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var fc=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},H5={};function ya(e){return H5}function W5(e,t){return typeof t=="bigint"?t.toString():t}function A_(e){return e==null}function $_(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function ut(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}var mT=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function xb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ob(e){if(xb(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(xb(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function J5(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function zs(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qo(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function G5(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ru(e){return typeof e=="string"?e:e?.message}function _a(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let s=Ru(e.inst?._zod.def?.error?.(e))??Ru(t?.error?.(e))??Ru(n.customError?.(e))??Ru(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function C_(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function mc(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}var gT=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,W5,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},yT=Ce("$ZodError",gT),_T=Ce("$ZodError",gT,{Parent:Error});function K5(e,t=n=>n.message){let n={},r=[];for(let s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}function X5(e,t){let n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(o=>s({issues:o}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(e),r}var Y5=e=>(t,n,r,s)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new fc;if(i.issues.length){let o=new(s?.Err??e)(i.issues.map(c=>_a(c,a,ya())));throw mT(o,s?.callee),o}return i.value},Q5=e=>async(t,n,r,s)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){let o=new(s?.Err??e)(i.issues.map(c=>_a(c,a,ya())));throw mT(o,s?.callee),o}return i.value},vT=e=>(t,n,r)=>{let s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new fc;return a.issues.length?{success:!1,error:new(e??yT)(a.issues.map(i=>_a(i,s,ya())))}:{success:!0,data:a.value}},eU=vT(_T),wT=e=>async(t,n,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>_a(i,s,ya())))}:{success:!0,data:a.value}},tU=wT(_T),io=Ce("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),nU=Ce("$ZodCheckMaxLength",(e,t)=>{var n;io.init(e,t),(n=e._zod.def).when??(n.when=r=>{let s=r.value;return!A_(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{let s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<s&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let s=r.value;if(s.length<=t.maximum)return;let a=C_(s);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),rU=Ce("$ZodCheckMinLength",(e,t)=>{var n;io.init(e,t),(n=e._zod.def).when??(n.when=r=>{let s=r.value;return!A_(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{let s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>s&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let s=r.value;if(s.length>=t.minimum)return;let a=C_(s);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),sU=Ce("$ZodCheckLengthEquals",(e,t)=>{var n;io.init(e,t),(n=e._zod.def).when??(n.when=r=>{let s=r.value;return!A_(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{let s=r._zod.bag;s.minimum=t.length,s.maximum=t.length,s.length=t.length}),e._zod.check=r=>{let s=r.value,a=s.length;if(a===t.length)return;let i=C_(s),o=a>t.length;r.issues.push({origin:i,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),aU=Ce("$ZodCheckOverwrite",(e,t)=>{io.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),iU={major:4,minor:0,patch:0},an=Ce("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=iU;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let s of r)for(let a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,i,o)=>{let c=qo(a),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(c)continue;let d=a.issues.length,p=l._zod.check(a);if(p instanceof Promise&&o?.async===!1)throw new fc;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,a.issues.length!==d&&(c||(c=qo(a,d)))});else{if(a.issues.length===d)continue;c||(c=qo(a,d))}}return u?u.then(()=>a):a};e._zod.run=(a,i)=>{let o=e._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new fc;return o.then(c=>s(c,r,i))}return s(o,r,i)}}e["~standard"]={validate:s=>{try{let a=eU(e,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return tU(e,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),oU=Ce("$ZodAny",(e,t)=>{an.init(e,t),e._zod.parse=n=>n});function Sb(e,t,n){e.issues.length&&t.issues.push(...G5(n,e.issues)),t.value[n]=e.value}var cU=Ce("$ZodArray",(e,t)=>{an.init(e,t),e._zod.parse=(n,r)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);let a=[];for(let i=0;i<s.length;i++){let o=s[i],c=t.element._zod.run({value:o,issues:[]},r);c instanceof Promise?a.push(c.then(u=>Sb(u,n,i))):Sb(c,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function Tb(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(a=>_a(a,r,ya())))}),t}var uU=Ce("$ZodUnion",(e,t)=>{an.init(e,t),ut(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ut(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ut(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ut(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>$_(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let s=!1,a=[];for(let i of t.options){let o=i._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)a.push(o),s=!0;else{if(o.issues.length===0)return o;a.push(o)}}return s?Promise.all(a).then(i=>Tb(i,n,e,r)):Tb(a,n,e,r)}}),lU=Ce("$ZodIntersection",(e,t)=>{an.init(e,t),e._zod.parse=(n,r)=>{let s=n.value,a=t.left._zod.run({value:s,issues:[]},r),i=t.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([o,c])=>Ib(n,o,c)):Ib(n,a,i)}});function Og(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ob(e)&&Ob(t)){let n=Object.keys(t),r=Object.keys(e).filter(a=>n.indexOf(a)!==-1),s={...e,...t};for(let a of r){let i=Og(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};s[a]=i.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let s=e[r],a=t[r],i=Og(s,a);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ib(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),qo(e))return e;let r=Og(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}var dU=Ce("$ZodTransform",(e,t)=>{an.init(e,t),e._zod.parse=(n,r)=>{let s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(n.value=a,n));if(s instanceof Promise)throw new fc;return n.value=s,n}}),pU=Ce("$ZodOptional",(e,t)=>{an.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ut(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ut(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${$_(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),hU=Ce("$ZodNullable",(e,t)=>{an.init(e,t),ut(e._zod,"optin",()=>t.innerType._zod.optin),ut(e._zod,"optout",()=>t.innerType._zod.optout),ut(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${$_(n.source)}|null)$`):void 0}),ut(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),fU=Ce("$ZodDefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",ut(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;let s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Eb(a,t)):Eb(s,t)}});function Eb(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var mU=Ce("$ZodPrefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",ut(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gU=Ce("$ZodNonOptional",(e,t)=>{an.init(e,t),ut(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Ab(a,e)):Ab(s,e)}});function Ab(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var yU=Ce("$ZodCatch",(e,t)=>{an.init(e,t),e._zod.optin="optional",ut(e._zod,"optout",()=>t.innerType._zod.optout),ut(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{let s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>_a(i,r,ya()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>_a(a,r,ya()))},input:n.value}),n.issues=[]),n)}}),_U=Ce("$ZodPipe",(e,t)=>{an.init(e,t),ut(e._zod,"values",()=>t.in._zod.values),ut(e._zod,"optin",()=>t.in._zod.optin),ut(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{let s=t.in._zod.run(n,r);return s instanceof Promise?s.then(a=>$b(a,t,r)):$b(s,t,r)}});function $b(e,t,n){return qo(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}var vU=Ce("$ZodReadonly",(e,t)=>{an.init(e,t),ut(e._zod,"propValues",()=>t.innerType._zod.propValues),ut(e._zod,"values",()=>t.innerType._zod.values),ut(e._zod,"optin",()=>t.innerType._zod.optin),ut(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{let s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(Cb):Cb(s)}});function Cb(e){return e.value=Object.freeze(e.value),e}var wU=Ce("$ZodCustom",(e,t)=>{io.init(e,t),an.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(a=>Nb(a,n,r,e));Nb(s,n,r,e)}});function Nb(e,t,n,r){if(!e){let s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),t.issues.push(mc(s))}}var bU=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function kU(){return new bU}var Mu=kU();function xU(e){return new e({type:"any"})}function OU(e,t){return new nU({check:"max_length",...zs(t),maximum:e})}function Pb(e,t){return new rU({check:"min_length",...zs(t),minimum:e})}function SU(e,t){return new sU({check:"length_equals",...zs(t),length:e})}function TU(e){return new aU({check:"overwrite",tx:e})}function IU(e,t,n){return new e({type:"array",element:t,...zs(n)})}function EU(e,t,n){let r=zs(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function AU(e,t,n){return new e({type:"custom",check:"custom",fn:t,...zs(n)})}var $U=(e,t)=>{yT.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>X5(e,n)},flatten:{value:n=>K5(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},Jp=Ce("ZodError",$U,{Parent:Error}),CU=Y5(Jp),NU=Q5(Jp),PU=vT(Jp),jU=wT(Jp),wn=Ce("ZodType",(e,t)=>(an.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>J5(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>CU(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>PU(e,n,r),e.parseAsync=async(n,r)=>NU(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>jU(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(sD(n,r)),e.superRefine=n=>e.check(aD(n)),e.overwrite=n=>e.check(TU(n)),e.optional=()=>jb(e),e.nullable=()=>Rb(e),e.nullish=()=>jb(Rb(e)),e.nonoptional=n=>XU(e,n),e.array=()=>LU(e),e.or=n=>UU([e,n]),e.and=n=>FU(e,n),e.transform=n=>Mb(e,ZU(n)),e.default=n=>WU(e,n),e.prefault=n=>GU(e,n),e.catch=n=>QU(e,n),e.pipe=n=>Mb(e,n),e.readonly=()=>nD(e),e.describe=n=>{let r=e.clone();return Mu.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Mu.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Mu.get(e);let r=e.clone();return Mu.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),RU=Ce("ZodAny",(e,t)=>{oU.init(e,t),wn.init(e,t)});function Lu(){return xU(RU)}var MU=Ce("ZodArray",(e,t)=>{cU.init(e,t),wn.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Pb(n,r)),e.nonempty=n=>e.check(Pb(1,n)),e.max=(n,r)=>e.check(OU(n,r)),e.length=(n,r)=>e.check(SU(n,r)),e.unwrap=()=>e.element});function LU(e,t){return IU(MU,e,t)}var zU=Ce("ZodUnion",(e,t)=>{uU.init(e,t),wn.init(e,t),e.options=t.options});function UU(e,t){return new zU({type:"union",options:e,...zs(t)})}var DU=Ce("ZodIntersection",(e,t)=>{lU.init(e,t),wn.init(e,t)});function FU(e,t){return new DU({type:"intersection",left:e,right:t})}var BU=Ce("ZodTransform",(e,t)=>{dU.init(e,t),wn.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(mc(a,n.value,t));else{let i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(mc(i))}};let s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function ZU(e){return new BU({type:"transform",transform:e})}var qU=Ce("ZodOptional",(e,t)=>{pU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jb(e){return new qU({type:"optional",innerType:e})}var VU=Ce("ZodNullable",(e,t)=>{hU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Rb(e){return new VU({type:"nullable",innerType:e})}var HU=Ce("ZodDefault",(e,t)=>{fU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function WU(e,t){return new HU({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var JU=Ce("ZodPrefault",(e,t)=>{mU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function GU(e,t){return new JU({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var KU=Ce("ZodNonOptional",(e,t)=>{gU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function XU(e,t){return new KU({type:"nonoptional",innerType:e,...zs(t)})}var YU=Ce("ZodCatch",(e,t)=>{yU.init(e,t),wn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function QU(e,t){return new YU({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var eD=Ce("ZodPipe",(e,t)=>{_U.init(e,t),wn.init(e,t),e.in=t.in,e.out=t.out});function Mb(e,t){return new eD({type:"pipe",in:e,out:t})}var tD=Ce("ZodReadonly",(e,t)=>{vU.init(e,t),wn.init(e,t)});function nD(e){return new tD({type:"readonly",innerType:e})}var bT=Ce("ZodCustom",(e,t)=>{wU.init(e,t),wn.init(e,t)});function rD(e){let t=new io({check:"custom"});return t._zod.check=e,t}function Lb(e,t){return EU(bT,(()=>!0),t)}function sD(e,t={}){return AU(bT,e,t)}function aD(e){let t=rD(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(mc(r,n.value,t._zod.def));else{let s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(mc(s))}},e(n.value,n)));return t}var kT=class{path;ends;constructor(e){je.isRunnable(e.path)?this.path=e.path:this.path=Rt(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,n)=>(t[n]=n,t),{}):e.pathMap}run(e,t){return Xt.registerWriter(new ja({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(s){throw s.name===ly.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
265
265
  NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,n,r){let s=await this.path.invoke(r?r(t):e,t);Array.isArray(s)||(s=[s]);let a;if(this.ends?a=s.map(i=>fn(i)?i:this.ends[i]):a=s,a.some(i=>!i))throw new Error("Branch condition returned unknown or null destination");if(a.filter(fn).some(i=>i.node==="__end__"))throw new Xe("Cannot send a packet to the END node");return await n(a,t)??e}},iD=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(let[r,s,a]of n){for(let o of["|",":"])if(r.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r==="__end__")throw new Error(`Node \`${r}\` is reserved.`);let i=Rt(s);this.nodes[r]={runnable:i,metadata:a?.metadata,subgraphs:S_(i)?[i]:a?.subgraphs,ends:a?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e==="__end__")throw new Error("END cannot be a start node");if(t==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){let r=typeof e=="object"?e:{source:e,path:t,pathMap:n};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),je.isRunnable(r.path)||(r.path=Rt(r.path));let s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new kT(r),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(wt,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,St)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let s=new xT({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[wt]:new Pi,[St]:new Pi},inputChannels:wt,outputChannels:St,streamChannels:[],streamMode:"values",name:r});for(let[a,i]of Object.entries(this.nodes))s.attachNode(a,i);for(let[a,i]of this.edges)s.attachEdge(a,i);for(let[a,i]of Object.entries(this.branches))for(let[o,c]of Object.entries(i))s.attachBranch(a,o,c);return s.validate()}validate(e){let t=new Set([...this.allEdges].map(([r,s])=>r));for(let[r]of Object.entries(this.branches))t.add(r);for(let r of t)if(r!=="__start__"&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);let n=new Set([...this.allEdges].map(([r,s])=>s));for(let[r,s]of Object.entries(this.branches))for(let a of Object.values(s))if(a.ends!=null)for(let i of Object.values(a.ends))n.add(i);else{n.add(St);for(let i of Object.keys(this.nodes))i!==r&&n.add(i)}for(let r of Object.values(this.nodes))for(let s of r.ends??[])n.add(s);for(let r of Object.keys(this.nodes))if(!n.has(r))throw new YE([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
266
- `),{lc_error_code:"UNREACHABLE_NODE"});for(let r of n)if(r!=="__end__"&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(e){for(let r of e)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},xT=class extends V5{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Pi,this.nodes[e]=new dc({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Xt([{channel:e,value:ca}],[dn])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Xt([{channel:St,value:ca}],[dn]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e==="__start__"&&!this.nodes.__start__&&(this.nodes[wt]=Z5.subscribeTo(wt,{tags:[dn]})),this.nodes[e].pipe(n.run(s=>new Xt(s.map(a=>fn(a)?a:{channel:a==="__end__"?St:`branch:${e}:${t}:${a}`,value:ca}),[dn])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let s of r)if(s!=="__end__"){let a=`branch:${e}:${t}:${s}`;this.channels[a]=new Pi,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){let t=e?.xray,n=new ac,r={[wt]:n.addNode({schema:Lu()},wt)},s={},a={};t&&(a=Object.fromEntries((await is(this.getSubgraphsAsync())).filter(c=>zb(c[1]))));function i(c,u,l,d=!1){if(u==="__end__"&&s.__end__===void 0&&(s[St]=n.addNode({schema:Lu()},St)),r[c]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return n.addEdge(r[c],s[u],l!==u?l:void 0,d)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=zt(c),d=u.runnable,p=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?p.__interrupt="before,after":this.interruptBefore?.includes(c)?p.__interrupt="before":this.interruptAfter?.includes(c)&&(p.__interrupt="after"),t){let h=typeof t=="number"?t-1:t,f=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:h}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let m=function(k){return k?k.lc_runnable:!1},v=function(k,x){if(k!==void 0&&!nm(k))return k;if(m(x))try{let S=x.getName();return S=S.startsWith("Runnable")?S.slice(8):S,S}catch{return x.getName()}else return x.name??"UnknownSchema"},[g,y]=n.extend(f,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);y!==void 0&&(r[l]={name:v(y.id,y.data),...y}),s[l]={name:v(g.id,g.data),...g}}else{let m=n.addNode(d,l,p);r[l]=m,s[l]=m}}else{let h=n.addNode(d,l,p);r[l]=h,s[l]=h}}let o=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of o)i(zt(c),zt(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[zt(d),zt(d)])),[St]:St};for(let d of Object.values(u)){let p;d.ends!==void 0?p=d.ends:p=l;for(let[h,f]of Object.entries(p))i(zt(c),zt(f),h,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)i(zt(c),zt(l),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new ac,r={[wt]:n.addNode({schema:Lu()},wt)},s={},a={};t&&(a=Object.fromEntries(xo(this.getSubgraphs()).filter(c=>zb(c[1]))));function i(c,u,l,d=!1){return u==="__end__"&&s.__end__===void 0&&(s[St]=n.addNode({schema:Lu()},St)),n.addEdge(r[c],s[u],l!==u?l:void 0,d)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=zt(c),d=u.runnable,p=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?p.__interrupt="before,after":this.interruptBefore?.includes(c)?p.__interrupt="before":this.interruptAfter?.includes(c)&&(p.__interrupt="after"),t){let h=typeof t=="number"?t-1:t,f=a[c]!==void 0?a[c].getGraph({...e,xray:h}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let m=function(k){return k?k.lc_runnable:!1},v=function(k,x){if(k!==void 0&&!nm(k))return k;if(m(x))try{let S=x.getName();return S=S.startsWith("Runnable")?S.slice(8):S,S}catch{return x.getName()}else return x.name??"UnknownSchema"},[g,y]=n.extend(f,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);y!==void 0&&(r[l]={name:v(y.id,y.data),...y}),s[l]={name:v(g.id,g.data),...g}}else{let m=n.addNode(d,l,p);r[l]=m,s[l]=m}}else{let h=n.addNode(d,l,p);r[l]=h,s[l]=h}}let o=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of o)i(zt(c),zt(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[zt(d),zt(d)])),[St]:St};for(let d of Object.values(u)){let p;d.ends!==void 0?p=d.ends:p=l;for(let[h,f]of Object.entries(p))i(zt(c),zt(f),h,!0)}}return n}};function zb(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function zt(e){return e==="subgraph"?`"${e}"`:e}function So(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function oD(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function Ba(e){if(oD(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Za(e){if(e!=null&&So(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let n=t;if(!n.issues){let r=n.value;return()=>r}}}catch{}}var Mf=Symbol.for("langgraph.channel.missing"),cD=class OT extends Ls{lc_graph_name="UntrackedValue";guard;_value=Mf;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new OT({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new Xe("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=t[t.length-1],!0}get(){if(this._value===Mf)throw new Et;return this._value}checkpoint(){}isAvailable(){return this._value!==Mf}},Ys=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n)),uD=class ST extends Ls{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let n=new ST(this.names);return typeof t<"u"&&(n.seen=new Set(t)),n}update(t){let n=!1;for(let r of t)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new Xe(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!Ys(this.names,this.seen))throw new Et}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Ys(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Ys(this.names,this.seen)}},lD=class TT extends Ls{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new TT(this.names);if(typeof t<"u"){let[r,s]=t;n.seen=new Set(r),n.finished=s}return n}update(t){let n=!1;for(let r of t)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new Xe(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!Ys(this.names,this.seen))throw new Et}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Ys(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Ys(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Ys(this.names,this.seen)}},Lf=Symbol.for("langgraph.state.reduced_value"),Ga=class{[Lf]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&Lf in e&&e[Lf]===!0}},Ub=Symbol.for("langgraph.state.untracked_value"),mo=class{[Ub]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&Ub in e}},zf=Symbol.for("langgraph.state.state_schema"),Qs=class{[zf]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(Ga.isInstance(n)){let r=Za(n.valueSchema);e[t]=new Kl(n.reducer,r)}else if(mo.isInstance(n)){let r=n.schema?Za(n.schema):void 0;e[t]=new cD({guard:n.guard,initialValueFactory:r})}else if(So(n))e[t]=new Wp(Za(n));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let s;if(Ga.isInstance(r)?(s=Ba(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):mo.isInstance(r)?s=r.schema?Ba(r.schema):void 0:So(r)&&(s=Ba(r)),s){e[n]=s;let a=!1;Ga.isInstance(r)?a=Za(r.valueSchema)!==void 0:mo.isInstance(r)?a=r.schema?Za(r.schema)!==void 0:!1:a=Za(r)!==void 0,a||t.push(n)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;Ga.isInstance(n)?(r=Ba(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):mo.isInstance(n)?r=n.schema?Ba(n.schema):void 0:So(n)&&(r=Ba(n)),r&&(e[t]=r)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[n,r]of Object.entries(e)){let s=this.fields[n];if(s===void 0){t[n]=r;continue}let a;if(Ga.isInstance(s)?a=s.inputSchema:mo.isInstance(s)?a=s.schema:So(s)&&(a=s),a){let i=await a["~standard"].validate(r);if(i.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(i.issues)}`);t[n]=i.value}else t[n]=r}return t}static isInstance(e){return typeof e=="object"&&e!==null&&zf in e&&e[zf]===!0}};function Ra(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(kr),a=r.map(kr);for(let l of s)(l.id===null||l.id===void 0)&&(l.id=Gs(),l.lc_kwargs.id=l.id);let i;for(let l=0;l<a.length;l+=1){let d=a[l];(d.id===null||d.id===void 0)&&(d.id=Gs(),d.lc_kwargs.id=d.id),sa.isInstance(d)&&d.id==="__remove_all__"&&(i=l)}if(i!=null)return a.slice(i+1);let o=[...s],c=new Map(o.map((l,d)=>[l.id,d])),u=new Set;for(let l of a){let d=c.get(l.id);if(d!==void 0)sa.isInstance(l)?u.add(l.id):(u.delete(l.id),o[d]=l);else{if(sa.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,o.length),o.push(l)}}return o.filter(l=>!u.has(l.id))}new Ga(Lb().default(()=>[]),{inputSchema:Lb(),reducer:Ra,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var dD=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=rc(e);for(let[r,s]of Object.entries(n)){let a=this.get(s);a?.reducer?t[r]=new Kl(a.reducer.fn,a.default):t[r]=new Wp(a?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let a=Object.entries(rc(e)).map(([i,o])=>{let c=this.get(o),u=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=Ti(u)??Ti(o),d=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`lg:${d}`)}return[i,u]});s=Bx(e,Object.fromEntries(a)),mt(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Vy(s)),r.set(e,s),this._extensionCache.set(n,r),s}},ed=new dD;function pD(e,t){if(t.reducer&&!t.default){let n=Zx(e);n!=null&&(t.default=n)}if(t.reducer){let n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return ed.extend(n,()=>t),n}else return ed.extend(e,()=>t),e}function Ka(e){return e==null?!1:!!(Qs.isInstance(e)||Pn(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||qS(t)))}function hD(e){if(typeof e!="object"||e==null)return!1;let t=e,n="state"in t&&Ka(t.state),r="stateSchema"in t&&Ka(t.stateSchema),s="input"in t&&Ka(t.input);return!(!n&&!r&&!s||"input"in t&&t.input!=null&&!Ka(t.input)||"output"in t&&t.output!=null&&!Ka(t.output))}var ls="__root__",td=Symbol.for("langgraph.state.partial"),N_=class extends iD{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=ed;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new ah;let s=this._getChannelsFromSchema(r);this._schemaDefinition=s,Qs.isInstance(r)?this._schemaRuntimeDefinition=r:Pn(r)&&(this._schemaRuntimeDefinition=r),n.input?Qs.isInstance(n.input)?this._inputRuntimeDefinition=n.input:Pn(n.input)?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=td:this._inputRuntimeDefinition=td,n.output?Qs.isInstance(n.output)?this._outputRuntimeDefinition=n.output:Pn(n.output)?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):s,i=n.output?this._getChannelsFromSchema(n.output):s;this._inputDefinition=a,this._outputDefinition=i,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&Pn(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(hD(e)){if(Pn(t)||_g.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(Ka(e)){if(Pn(t)||_g.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(gD(e))return{state:fD(e.channels)};throw new ah}_getChannelsFromSchema(e){if(Qs.isInstance(e))return e.getChannels();if(Pn(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new ah("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(n=>[n,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let r;if(typeof n=="function"?r=n():r=n,this.channels[t]!==void 0){if(!this.channels[t].equals(r)&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=r}}}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([r,s])=>[r,s]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(let[r,s,a]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let l of["|",":"])if(r.includes(l))throw new Error(`"${l}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r==="__end__"||r==="__start__")throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;a?.input!==void 0&&(i=this._getChannelsFromSchema(a.input)),this._addSchema(i);let o;je.isRunnable(s)?o=s:typeof s=="function"?o=new ja({func:s,name:r,trace:!1}):o=Rt(s);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:o,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:i??this._schemaDefinition,subgraphs:S_(o)?[o]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[r]=u}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let n of e){if(n==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let n;for(let[r,s,a]of t){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);let i=r;this.addNode(i,s,a),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:s,name:a,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);let o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===ls?ls:o,u=Object.keys(this.channels),l=u.length===1&&u[0]===ls?ls:u,d=this._interrupt,p=new mD({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[wt]:new Pi},inputChannels:wt,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:n,name:a,description:i,userInterrupt:d});p.attachNode(wt);for(let[h,f]of Object.entries(this.nodes))p.attachNode(h,f);p.attachBranch(wt,w0,Db(),{withReader:!1});for(let[h]of Object.entries(this.nodes))p.attachBranch(h,w0,Db(),{withReader:!1});for(let[h,f]of this.edges)p.attachEdge(h,f);for(let[h,f]of this.waitingEdges)p.attachEdge(h,f);for(let[h,f]of Object.entries(this.branches))for(let[m,v]of Object.entries(f))p.attachBranch(h,m,v);return p.validate()}};function fD(e){let t={};for(let[n,r]of Object.entries(e))t[n]=JS(r);return t}var mD=class extends xT{description;_metaRegistry=ed;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;e==="__start__"?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):n=Object.keys(this.builder.channels);function r(o){if(Ut(o))return o.graph===_r.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Ut(c))){let c=[];for(let u of o)if(Ut(u)){if(u.graph===_r.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([ls,u]);return c}else if(o!=null)return[[ls,o]];return null}let s=e;function a(o){if(o){if(Ut(o))return o.graph===_r.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Ut)){let c=[];for(let u of o)if(Ut(u)){if(u.graph===_r.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>n.includes(l)))}else{let l=a(u);l&&c.push(...l??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>n.includes(c));{let c=Array.isArray(o)?"array":typeof o;throw new Xe(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let i=[{value:ca,mapper:new ja({func:n.length&&n[0]===ls?r:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new dc({tags:[dn],triggers:[wt],channels:[wt],writers:[new Xt(i,[dn])]});else{let o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),u=Object.keys(c).length===1&&ls in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new P9:new Pi(!1),this.nodes[e]=new dc({triggers:[l],channels:u?Object.keys(c):c,writers:[new Xt(i,[dn])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([p])=>p in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new Xt([{channel:`branch:to:${t}`,value:null}],[dn]));else if(Array.isArray(e)){let n=`join:${e.join("+")}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new lD(new Set(e)):new uD(new Set(e)),this.nodes[t].triggers.push(n);for(let r of e)this.nodes[r].writers.push(new Xt([{channel:n,value:r}],[dn]))}}}attachBranch(e,t,n,r={withReader:!0}){let s=async(a,i)=>{let o=a.filter(u=>u!==St);if(!o.length)return;let c=o.map(u=>fn(u)?u:{channel:u==="__end__"?u:`branch:to:${u}`,value:e});await Xt.doWrite({...i,tags:(i.tags??[]).concat([dn])},c)};this.nodes[e].writers.push(n.run(s,r.withReader?a=>D9.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(Qs.isInstance(t)){if(Ut(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===td&&Qs.isInstance(n)){if(Ut(e)){let s=e;return e.update&&(s.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await n.validateInput(e)}let r=(()=>{let s=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(Pn(t))return s(t);if(t===td)return Pn(n)?Vy(s(n)):void 0})();if(Ut(e)){let s=e;return e.update&&r!=null&&(s.update=al(r,e.update)),s}return r!=null?al(r,e):e}isInterrupted(e){return ek(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Pn(t)&&al(t,e),e}};function gD(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function yD(e){if(fn(e))return[e];let t=[];Ut(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Ut));let n=[];for(let r of t){if(r.graph===_r.PARENT)throw new nk(r);fn(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Db(){return new kT({path:new ja({func:yD,tags:[dn],trace:!1,recurse:!1,name:"<control_branch>"})})}var Re;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},e.getValidEnumValues=s=>{let a=e.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(a){return s[a]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},e.find=(s,a)=>{for(let i of s)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=r,e.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Re||(Re={}));var Sg;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Sg||(Sg={}));var J=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Dr=e=>{switch(typeof e){case"undefined":return J.undefined;case"string":return J.string;case"number":return Number.isNaN(e)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(e)?J.array:e===null?J.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?J.promise:typeof Map<"u"&&e instanceof Map?J.map:typeof Set<"u"&&e instanceof Set?J.set:typeof Date<"u"&&e instanceof Date?J.date:J.object;default:return J.unknown}},R=Re.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"]),_D=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ar=class IT extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(t){if(!(t instanceof IT))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];n[a]=n[a]||[],n[a].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ar.create=e=>new ar(e);var ji=(e,t)=>{let n;switch(e.code){case R.invalid_type:e.received===J.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Re.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${Re.joinValues(e.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Re.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${Re.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case R.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case R.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=t.defaultError,Re.assertNever(e)}return{message:n}},ET=ji;function vD(e){ET=e}function nd(){return ET}var rd=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}},wD=[];function q(e,t){let n=nd(),r=rd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ji?void 0:ji].filter(s=>!!s)});e.common.issues.push(r)}var Zt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return fe;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let a=await s.key,i=await s.value;r.push({key:a,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return fe;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:t.value,value:r}}},fe=Object.freeze({status:"aborted"}),sd=e=>({status:"dirty",value:e}),nn=e=>({status:"valid",value:e}),Tg=e=>e.status==="aborted",Ig=e=>e.status==="dirty",va=e=>e.status==="valid",gc=e=>typeof Promise<"u"&&e instanceof Promise,ie;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ie||(ie={}));var Ln=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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}},Fb=(e,t)=>{if(va(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ar(e.common.issues);return this._error=n,this._error}}};function xe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,i)=>{let{message:o}=e;return a.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:o??n??i.defaultError}},description:s}}var Ee=class{get description(){return this._def.description}_getType(e){return Dr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Zt,ctx:{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(gc(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Fb(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return va(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>va(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(gc(r)?r:Promise.resolve(r));return Fb(n,s)}refine(e,t){let n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let a=e(r),i=()=>s.addIssue({code:R.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(o=>o?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new An({schema:this,typeName:me.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 Or.create(this,this._def)}nullable(){return $s.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Sa.create(this)}promise(){return As.create(this,this._def)}or(e){return _c.create([this,e],this._def)}and(e){return vc.create(this,e,this._def)}transform(e){return new An({...xe(this._def),schema:this,typeName:me.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new bc({...xe(this._def),innerType:this,defaultValue:t,typeName:me.ZodDefault})}brand(){return new xc({typeName:me.ZodBranded,type:this,...xe(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new kc({...xe(this._def),innerType:this,catchValue:t,typeName:me.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Oc.create(this,e)}readonly(){return Sc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bD=/^c[^\s-]{8,}$/i,kD=/^[0-9a-z]+$/,xD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,OD=/^[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,SD=/^[a-z0-9_-]{21}$/i,TD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ID=/^[-+]?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)?)??$/,ED=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,AD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Uf,$D=/^(?:(?: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])$/,CD=/^(?:(?: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])$/,ND=/^(([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]))$/,PD=/^(([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])$/,jD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,RD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,AT="((\\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])))",MD=new RegExp(`^${AT}$`);function $T(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function LD(e){return new RegExp(`^${$T(e)}$`)}function CT(e){let t=`${AT}T${$T(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function zD(e,t){return!!((t==="v4"||!t)&&$D.test(e)||(t==="v6"||!t)&&ND.test(e))}function UD(e,t){if(!TD.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function DD(e,t){return!!((t==="v4"||!t)&&CD.test(e)||(t==="v6"||!t)&&PD.test(e))}var Ri=class To extends Ee{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==J.string){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.string,received:s.parsedType}),fe}let n=new Zt,r;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(r=this._getOrReturnCtx(t,r),a?q(r,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&q(r,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ED.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"email",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Uf||(Uf=new RegExp(AD,"u")),Uf.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"emoji",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")OD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"uuid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")SD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"nanoid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")bD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cuid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")kD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cuid2",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")xD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"ulid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),q(r,{validation:"url",code:R.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"regex",code:R.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?CT(s).test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?MD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?LD(s).test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ID.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"duration",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?zD(t.data,s.version)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"ip",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?UD(t.data,s.alg)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"jwt",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?DD(t.data,s.version)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cidr",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?jD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"base64",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?RD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"base64url",code:R.invalid_string,message:s.message}),n.dirty()):Re.assertNever(s);return{status:n.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:R.invalid_string,...ie.errToObj(r)})}_addCheck(t){return new To({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ie.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ie.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ie.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ie.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ie.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ie.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ie.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ie.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ie.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ie.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ie.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ie.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ie.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ie.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ie.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ie.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ie.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...ie.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ie.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ie.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ie.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ie.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ie.errToObj(n)})}nonempty(t){return this.min(1,ie.errToObj(t))}trim(){return new To({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new To({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new To({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ri.create=e=>new Ri({checks:[],typeName:me.ZodString,coerce:e?.coerce??!1,...xe(e)});function FD(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}var yc=class Eg extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==J.number){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.number,received:s.parsedType}),fe}let n,r=new Zt;for(let s of this._def.checks)s.kind==="int"?Re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:R.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?FD(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_finite,message:s.message}),r.dirty()):Re.assertNever(s);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ie.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ie.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ie.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ie.toString(n))}setLimit(t,n,r,s){return new Eg({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ie.toString(s)}]})}_addCheck(t){return new Eg({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ie.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ie.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ie.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ie.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ie.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ie.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ie.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ie.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ie.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Re.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};yc.create=e=>new yc({checks:[],typeName:me.ZodNumber,coerce:e?.coerce||!1,...xe(e)});var wa=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==J.bigint)return this._getInvalidInput(t);let n,r=new Zt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Re.assertNever(s);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.bigint,received:n.parsedType}),fe}gte(t,n){return this.setLimit("min",t,!0,ie.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ie.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ie.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ie.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ie.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ie.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ie.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ie.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ie.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ie.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};wa.create=e=>new wa({checks:[],typeName:me.ZodBigInt,coerce:e?.coerce??!1,...xe(e)});var ba=class extends Ee{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==J.boolean){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.boolean,received:n.parsedType}),fe}return nn(t.data)}};ba.create=e=>new ba({typeName:me.ZodBoolean,coerce:e?.coerce||!1,...xe(e)});var ka=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==J.date){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.date,received:s.parsedType}),fe}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_date}),fe}let n=new Zt,r;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Re.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ie.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ie.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ka.create=e=>new ka({checks:[],coerce:e?.coerce||!1,typeName:me.ZodDate,...xe(e)});var Mi=class extends Ee{_parse(t){if(this._getType(t)!==J.symbol){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.symbol,received:n.parsedType}),fe}return nn(t.data)}};Mi.create=e=>new Mi({typeName:me.ZodSymbol,...xe(e)});var xa=class extends Ee{_parse(t){if(this._getType(t)!==J.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.undefined,received:n.parsedType}),fe}return nn(t.data)}};xa.create=e=>new xa({typeName:me.ZodUndefined,...xe(e)});var Oa=class extends Ee{_parse(t){if(this._getType(t)!==J.null){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.null,received:n.parsedType}),fe}return nn(t.data)}};Oa.create=e=>new Oa({typeName:me.ZodNull,...xe(e)});var Es=class extends Ee{constructor(){super(...arguments),this._any=!0}_parse(t){return nn(t.data)}};Es.create=e=>new Es({typeName:me.ZodAny,...xe(e)});var ua=class extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nn(e.data)}};ua.create=e=>new ua({typeName:me.ZodUnknown,...xe(e)});var Gr=class extends Ee{_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:R.invalid_type,expected:J.never,received:t.parsedType}),fe}};Gr.create=e=>new Gr({typeName:me.ZodNever,...xe(e)});var Li=class extends Ee{_parse(t){if(this._getType(t)!==J.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.void,received:n.parsedType}),fe}return nn(t.data)}};Li.create=e=>new Li({typeName:me.ZodVoid,...xe(e)});var Sa=class gl extends Ee{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==J.array)return q(n,{code:R.invalid_type,expected:J.array,received:n.parsedType}),fe;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(q(n,{code:i?R.too_big:R.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(q(n,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(q(n,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new Ln(n,i,n.path,o)))).then(i=>Zt.mergeArray(r,i));let a=[...n.data].map((i,o)=>s.type._parseSync(new Ln(n,i,n.path,o)));return Zt.mergeArray(r,a)}get element(){return this._def.type}min(t,n){return new gl({...this._def,minLength:{value:t,message:ie.toString(n)}})}max(t,n){return new gl({...this._def,maxLength:{value:t,message:ie.toString(n)}})}length(t,n){return new gl({...this._def,exactLength:{value:t,message:ie.toString(n)}})}nonempty(t){return this.min(1,t)}};Sa.create=(e,t)=>new Sa({type:e,minLength:null,maxLength:null,exactLength:null,typeName:me.ZodArray,...xe(t)});function Xa(e){if(e instanceof zn){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Or.create(Xa(r))}return new zn({...e._def,shape:()=>t})}else return e instanceof Sa?new Sa({...e._def,type:Xa(e.element)}):e instanceof Or?Or.create(Xa(e.unwrap())):e instanceof $s?$s.create(Xa(e.unwrap())):e instanceof Ar?Ar.create(e.items.map(t=>Xa(t))):e}var zn=class Jn extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Re.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==J.object){let c=this._getOrReturnCtx(t);return q(c,{code:R.invalid_type,expected:J.object,received:c.parsedType}),fe}let{status:n,ctx:r}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Gr&&this._def.unknownKeys==="strip"))for(let c in r.data)a.includes(c)||i.push(c);let o=[];for(let c of a){let u=s[c],l=r.data[c];o.push({key:{status:"valid",value:c},value:u._parse(new Ln(r,l,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Gr){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)o.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")i.length>0&&(q(r,{code:R.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=r.data[u];o.push({key:{status:"valid",value:u},value:c._parse(new Ln(r,l,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of o){let l=await u.key,d=await u.value;c.push({key:l,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>Zt.mergeObjectSync(n,c)):Zt.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(t){return ie.errToObj,new Jn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ie.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new Jn({...this._def,unknownKeys:"strip"})}passthrough(){return new Jn({...this._def,unknownKeys:"passthrough"})}extend(t){return new Jn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Jn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:me.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Jn({...this._def,catchall:t})}pick(t){let n={};for(let r of Re.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Jn({...this._def,shape:()=>n})}omit(t){let n={};for(let r of Re.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Jn({...this._def,shape:()=>n})}deepPartial(){return Xa(this)}partial(t){let n={};for(let r of Re.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new Jn({...this._def,shape:()=>n})}required(t){let n={};for(let r of Re.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Or;)s=s._def.innerType;n[r]=s}return new Jn({...this._def,shape:()=>n})}keyof(){return PT(Re.objectKeys(this.shape))}};zn.create=(e,t)=>new zn({shape:()=>e,unknownKeys:"strip",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});zn.strictCreate=(e,t)=>new zn({shape:()=>e,unknownKeys:"strict",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});zn.lazycreate=(e,t)=>new zn({shape:e,unknownKeys:"strip",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});var _c=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new ar(i.ctx.common.issues));return q(t,{code:R.invalid_union,unionErrors:a}),fe}if(t.common.async)return Promise.all(n.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let s,a=[];for(let o of n){let c={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(o=>new ar(o));return q(t,{code:R.invalid_union,unionErrors:i}),fe}}get options(){return this._def.options}};_c.create=(e,t)=>new _c({options:e,typeName:me.ZodUnion,...xe(t)});var ns=e=>e instanceof Ta?ns(e.schema):e instanceof An?ns(e.innerType()):e instanceof wc?[e.value]:e instanceof nu?e.options:e instanceof Ia?Re.objectValues(e.enum):e instanceof bc?ns(e._def.innerType):e instanceof xa?[void 0]:e instanceof Oa?[null]:e instanceof Or?[void 0,...ns(e.unwrap())]:e instanceof $s?[null,...ns(e.unwrap())]:e instanceof xc||e instanceof Sc?ns(e.unwrap()):e instanceof kc?ns(e._def.innerType):[],ad=class e extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.object)return q(n,{code:R.invalid_type,expected:J.object,received:n.parsedType}),fe;let r=this.discriminator,s=n.data[r],a=this.optionsMap.get(s);return a?n.common.async?a._parseAsync({data:n.data,path:n.path,parent:n}):a._parseSync({data:n.data,path:n.path,parent:n}):(q(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),fe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let a of n){let i=ns(a.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,a)}}return new e({typeName:me.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...xe(r)})}};function Ag(e,t){let n=Dr(e),r=Dr(t);if(e===t)return{valid:!0,data:e};if(n===J.object&&r===J.object){let s=Re.objectKeys(t),a=Re.objectKeys(e).filter(o=>s.indexOf(o)!==-1),i={...e,...t};for(let o of a){let c=Ag(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===J.array&&r===J.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let a=0;a<e.length;a++){let i=e[a],o=t[a],c=Ag(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===J.date&&r===J.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var vc=class extends Ee{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(s,a)=>{if(Tg(s)||Tg(a))return fe;let i=Ag(s.value,a.value);return i.valid?((Ig(s)||Ig(a))&&t.dirty(),{status:t.value,value:i.data}):(q(n,{code:R.invalid_intersection_types}),fe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>r(s,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};vc.create=(e,t,n)=>new vc({left:e,right:t,typeName:me.ZodIntersection,...xe(n)});var Ar=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.array)return q(r,{code:R.invalid_type,expected:J.array,received:r.parsedType}),fe;if(r.data.length<this._def.items.length)return q(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),fe;!this._def.rest&&r.data.length>this._def.items.length&&(q(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,i)=>{let o=this._def.items[i]||this._def.rest;return o?o._parse(new Ln(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>Zt.mergeArray(n,a)):Zt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ar.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ar({items:e,typeName:me.ZodTuple,rest:null,...xe(t)})};var NT=class $g extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.object)return q(r,{code:R.invalid_type,expected:J.object,received:r.parsedType}),fe;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in r.data)s.push({key:a._parse(new Ln(r,o,r.path,o)),value:i._parse(new Ln(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Zt.mergeObjectAsync(n,s):Zt.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ee?new $g({keyType:t,valueType:n,typeName:me.ZodRecord,...xe(r)}):new $g({keyType:Ri.create(),valueType:t,typeName:me.ZodRecord,...xe(n)})}},zi=class extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.map)return q(r,{code:R.invalid_type,expected:J.map,received:r.parsedType}),fe;let s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new Ln(r,o,r.path,[u,"key"])),value:a._parse(new Ln(r,c,r.path,[u,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return fe;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return fe;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}}}};zi.create=(e,t,n)=>new zi({valueType:t,keyType:e,typeName:me.ZodMap,...xe(n)});var Ui=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.set)return q(r,{code:R.invalid_type,expected:J.set,received:r.parsedType}),fe;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(q(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(q(r,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return fe;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let o=[...r.data.values()].map((c,u)=>a._parse(new Ln(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:ie.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:ie.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Ui.create=(e,t)=>new Ui({valueType:e,minSize:null,maxSize:null,typeName:me.ZodSet,...xe(t)});var id=class e extends Ee{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.function)return q(n,{code:R.invalid_type,expected:J.function,received:n.parsedType}),fe;function r(o,c){return rd({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nd(),ji].filter(u=>!!u),issueData:{code:R.invalid_arguments,argumentsError:c}})}function s(o,c){return rd({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nd(),ji].filter(u=>!!u),issueData:{code:R.invalid_return_type,returnTypeError:c}})}let a={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof As){let o=this;return nn(async function(...c){let u=new ar([]),l=await o._def.args.parseAsync(c,a).catch(p=>{throw u.addIssue(r(c,p)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,a).catch(p=>{throw u.addIssue(s(d,p)),u})})}else{let o=this;return nn(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new ar([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,a);if(!d.success)throw new ar([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ar.create(t).rest(ua.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ar.create([]).rest(ua.create()),returns:n||ua.create(),typeName:me.ZodFunction,...xe(r)})}},Ta=class extends Ee{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ta.create=(e,t)=>new Ta({getter:e,typeName:me.ZodLazy,...xe(t)});var wc=class extends Ee{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),fe}return{status:"valid",value:e.data}}get value(){return this._def.value}};wc.create=(e,t)=>new wc({value:e,typeName:me.ZodLiteral,...xe(t)});function PT(e,t){return new nu({values:e,typeName:me.ZodEnum,...xe(t)})}var nu=class Cg extends Ee{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return q(n,{expected:Re.joinValues(r),received:n.parsedType,code:R.invalid_type}),fe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return q(n,{received:n.data,code:R.invalid_enum_value,options:r}),fe}return nn(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Cg.create(t,{...this._def,...n})}exclude(t,n=this._def){return Cg.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};nu.create=PT;var Ia=class extends Ee{_parse(t){let n=Re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==J.string&&r.parsedType!==J.number){let s=Re.objectValues(n);return q(r,{expected:Re.joinValues(s),received:r.parsedType,code:R.invalid_type}),fe}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=Re.objectValues(n);return q(r,{received:r.data,code:R.invalid_enum_value,options:s}),fe}return nn(t.data)}get enum(){return this._def.values}};Ia.create=(e,t)=>new Ia({values:e,typeName:me.ZodNativeEnum,...xe(t)});var As=class extends Ee{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.promise&&n.common.async===!1)return q(n,{code:R.invalid_type,expected:J.promise,received:n.parsedType}),fe;let r=n.parsedType===J.promise?n.data:Promise.resolve(n.data);return nn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};As.create=(e,t)=>new As({type:e,typeName:me.ZodPromise,...xe(t)});var An=class extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===me.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,a={addIssue:i=>{q(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(n.value==="aborted")return fe;let c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?fe:c.status==="dirty"||n.value==="dirty"?sd(c.value):c});{if(n.value==="aborted")return fe;let o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?fe:o.status==="dirty"||n.value==="dirty"?sd(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?fe:(o.status==="dirty"&&n.dirty(),i(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?fe:(o.status==="dirty"&&n.dirty(),i(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!va(i))return fe;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>va(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:n.value,value:o})):fe);Re.assertNever(s)}};An.create=(e,t,n)=>new An({schema:e,typeName:me.ZodEffects,effect:t,...xe(n)});An.createWithPreprocess=(e,t,n)=>new An({schema:t,effect:{type:"preprocess",transform:e},typeName:me.ZodEffects,...xe(n)});var Or=class extends Ee{_parse(e){return this._getType(e)===J.undefined?nn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Or.create=(e,t)=>new Or({innerType:e,typeName:me.ZodOptional,...xe(t)});var $s=class extends Ee{_parse(e){return this._getType(e)===J.null?nn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$s.create=(e,t)=>new $s({innerType:e,typeName:me.ZodNullable,...xe(t)});var bc=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===J.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};bc.create=(e,t)=>new bc({innerType:e,typeName:me.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...xe(t)});var kc=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gc(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};kc.create=(e,t)=>new kc({innerType:e,typeName:me.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...xe(t)});var Di=class extends Ee{_parse(t){if(this._getType(t)!==J.nan){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.nan,received:n.parsedType}),fe}return{status:"valid",value:t.data}}};Di.create=e=>new Di({typeName:me.ZodNaN,...xe(e)});var BD=Symbol("zod_brand"),xc=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Oc=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?fe:s.status==="dirty"?(n.dirty(),sd(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?fe:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:me.ZodPipeline})}},Sc=class extends Ee{_parse(e){let t=this._def.innerType._parse(e),n=r=>(va(r)&&(r.value=Object.freeze(r.value)),r);return gc(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:me.ZodReadonly,...xe(t)});function Bb(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function P_(e,t={},n){return e?Es.create().superRefine((r,s)=>{let a=e(r);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Bb(t,r),c=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Bb(t,r),o=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:o})}}):Es.create()}var ZD={object:zn.lazycreate},me;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(me||(me={}));var qD=(e,t={message:`Input not instance of ${e.name}`})=>P_(n=>n instanceof e,t),un=Ri.create,Vo=yc.create,VD=Di.create,HD=wa.create,jT=ba.create,WD=ka.create,JD=Mi.create,GD=xa.create,KD=Oa.create,XD=Es.create,YD=ua.create,QD=Gr.create,e3=Li.create,ui=Sa.create,os=zn.create,t3=zn.strictCreate,n3=_c.create,r3=ad.create,s3=vc.create,a3=Ar.create,i3=NT.create,o3=zi.create,c3=Ui.create,u3=id.create,l3=Ta.create,Io=wc.create,d3=nu.create,p3=Ia.create,h3=As.create,Zb=An.create,f3=Or.create,m3=$s.create,g3=An.createWithPreprocess,y3=Oc.create,_3=()=>un().optional(),v3=()=>Vo().optional(),w3=()=>jT().optional(),b3={string:(e=>Ri.create({...e,coerce:!0})),number:(e=>yc.create({...e,coerce:!0})),boolean:(e=>ba.create({...e,coerce:!0})),bigint:(e=>wa.create({...e,coerce:!0})),date:(e=>ka.create({...e,coerce:!0}))},k3=fe,Dt=Object.freeze(Object.defineProperty({__proto__:null,BRAND:BD,DIRTY:sd,EMPTY_PATH:wD,INVALID:fe,NEVER:k3,OK:nn,ParseStatus:Zt,Schema:Ee,ZodAny:Es,ZodArray:Sa,ZodBigInt:wa,ZodBoolean:ba,ZodBranded:xc,ZodCatch:kc,ZodDate:ka,ZodDefault:bc,ZodDiscriminatedUnion:ad,ZodEffects:An,ZodEnum:nu,ZodError:ar,get ZodFirstPartyTypeKind(){return me},ZodFunction:id,ZodIntersection:vc,ZodIssueCode:R,ZodLazy:Ta,ZodLiteral:wc,ZodMap:zi,ZodNaN:Di,ZodNativeEnum:Ia,ZodNever:Gr,ZodNull:Oa,ZodNullable:$s,ZodNumber:yc,ZodObject:zn,ZodOptional:Or,ZodParsedType:J,ZodPipeline:Oc,ZodPromise:As,ZodReadonly:Sc,ZodRecord:NT,ZodSchema:Ee,ZodSet:Ui,ZodString:Ri,ZodSymbol:Mi,ZodTransformer:An,ZodTuple:Ar,ZodType:Ee,ZodUndefined:xa,ZodUnion:_c,ZodUnknown:ua,ZodVoid:Li,addIssueToContext:q,any:XD,array:ui,bigint:HD,boolean:jT,coerce:b3,custom:P_,date:WD,datetimeRegex:CT,defaultErrorMap:ji,discriminatedUnion:r3,effect:Zb,enum:d3,function:u3,getErrorMap:nd,getParsedType:Dr,instanceof:qD,intersection:s3,isAborted:Tg,isAsync:gc,isDirty:Ig,isValid:va,late:ZD,lazy:l3,literal:Io,makeIssue:rd,map:o3,nan:VD,nativeEnum:p3,never:QD,null:KD,nullable:m3,number:Vo,object:os,get objectUtil(){return Sg},oboolean:w3,onumber:v3,optional:f3,ostring:_3,pipeline:y3,preprocess:g3,promise:h3,quotelessJson:_D,record:i3,set:c3,setErrorMap:vD,strictObject:t3,string:un,symbol:JD,transformer:Zb,tuple:a3,undefined:GD,union:n3,unknown:YD,get util(){return Re},void:e3},Symbol.toStringTag,{value:"Module"}));gt.Root({messages:gt({reducer:Ra,default:()=>[]})});var x3={reducer:{fn:Ra},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};os({messages:pD(P_(),x3)});async function O3(e,t,n){if(n===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
266
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(let r of n)if(r!=="__end__"&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(e){for(let r of e)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},xT=class extends V5{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Pi,this.nodes[e]=new dc({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Xt([{channel:e,value:ca}],[dn])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Xt([{channel:St,value:ca}],[dn]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e==="__start__"&&!this.nodes.__start__&&(this.nodes[wt]=Z5.subscribeTo(wt,{tags:[dn]})),this.nodes[e].pipe(n.run(s=>new Xt(s.map(a=>fn(a)?a:{channel:a==="__end__"?St:`branch:${e}:${t}:${a}`,value:ca}),[dn])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let s of r)if(s!=="__end__"){let a=`branch:${e}:${t}:${s}`;this.channels[a]=new Pi,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){let t=e?.xray,n=new ac,r={[wt]:n.addNode({schema:Lu()},wt)},s={},a={};t&&(a=Object.fromEntries((await is(this.getSubgraphsAsync())).filter(c=>zb(c[1]))));function i(c,u,l,d=!1){if(u==="__end__"&&s.__end__===void 0&&(s[St]=n.addNode({schema:Lu()},St)),r[c]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return n.addEdge(r[c],s[u],l!==u?l:void 0,d)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=zt(c),d=u.runnable,p=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?p.__interrupt="before,after":this.interruptBefore?.includes(c)?p.__interrupt="before":this.interruptAfter?.includes(c)&&(p.__interrupt="after"),t){let h=typeof t=="number"?t-1:t,f=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:h}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let m=function(k){return k?k.lc_runnable:!1},v=function(k,x){if(k!==void 0&&!nm(k))return k;if(m(x))try{let S=x.getName();return S=S.startsWith("Runnable")?S.slice(8):S,S}catch{return x.getName()}else return x.name??"UnknownSchema"},[g,y]=n.extend(f,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);y!==void 0&&(r[l]={name:v(y.id,y.data),...y}),s[l]={name:v(g.id,g.data),...g}}else{let m=n.addNode(d,l,p);r[l]=m,s[l]=m}}else{let h=n.addNode(d,l,p);r[l]=h,s[l]=h}}let o=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of o)i(zt(c),zt(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[zt(d),zt(d)])),[St]:St};for(let d of Object.values(u)){let p;d.ends!==void 0?p=d.ends:p=l;for(let[h,f]of Object.entries(p))i(zt(c),zt(f),h,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)i(zt(c),zt(l),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new ac,r={[wt]:n.addNode({schema:Lu()},wt)},s={},a={};t&&(a=Object.fromEntries(xo(this.getSubgraphs()).filter(c=>zb(c[1]))));function i(c,u,l,d=!1){return u==="__end__"&&s.__end__===void 0&&(s[St]=n.addNode({schema:Lu()},St)),n.addEdge(r[c],s[u],l!==u?l:void 0,d)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=zt(c),d=u.runnable,p=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?p.__interrupt="before,after":this.interruptBefore?.includes(c)?p.__interrupt="before":this.interruptAfter?.includes(c)&&(p.__interrupt="after"),t){let h=typeof t=="number"?t-1:t,f=a[c]!==void 0?a[c].getGraph({...e,xray:h}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let m=function(k){return k?k.lc_runnable:!1},v=function(k,x){if(k!==void 0&&!nm(k))return k;if(m(x))try{let S=x.getName();return S=S.startsWith("Runnable")?S.slice(8):S,S}catch{return x.getName()}else return x.name??"UnknownSchema"},[g,y]=n.extend(f,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);y!==void 0&&(r[l]={name:v(y.id,y.data),...y}),s[l]={name:v(g.id,g.data),...g}}else{let m=n.addNode(d,l,p);r[l]=m,s[l]=m}}else{let h=n.addNode(d,l,p);r[l]=h,s[l]=h}}let o=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of o)i(zt(c),zt(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[zt(d),zt(d)])),[St]:St};for(let d of Object.values(u)){let p;d.ends!==void 0?p=d.ends:p=l;for(let[h,f]of Object.entries(p))i(zt(c),zt(f),h,!0)}}return n}};function zb(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function zt(e){return e==="subgraph"?`"${e}"`:e}function So(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function oD(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function Ba(e){if(oD(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Za(e){if(e!=null&&So(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let n=t;if(!n.issues){let r=n.value;return()=>r}}}catch{}}var Mf=Symbol.for("langgraph.channel.missing"),cD=class OT extends Ls{lc_graph_name="UntrackedValue";guard;_value=Mf;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new OT({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new Xe("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=t[t.length-1],!0}get(){if(this._value===Mf)throw new Et;return this._value}checkpoint(){}isAvailable(){return this._value!==Mf}},Ys=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n)),uD=class ST extends Ls{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let n=new ST(this.names);return typeof t<"u"&&(n.seen=new Set(t)),n}update(t){let n=!1;for(let r of t)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new Xe(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!Ys(this.names,this.seen))throw new Et}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Ys(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Ys(this.names,this.seen)}},lD=class TT extends Ls{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new TT(this.names);if(typeof t<"u"){let[r,s]=t;n.seen=new Set(r),n.finished=s}return n}update(t){let n=!1;for(let r of t)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new Xe(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!Ys(this.names,this.seen))throw new Et}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Ys(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Ys(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Ys(this.names,this.seen)}},Lf=Symbol.for("langgraph.state.reduced_value"),Ga=class{[Lf]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&Lf in e&&e[Lf]===!0}},Ub=Symbol.for("langgraph.state.untracked_value"),mo=class{[Ub]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&Ub in e}},zf=Symbol.for("langgraph.state.state_schema"),Qs=class{[zf]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(Ga.isInstance(n)){let r=Za(n.valueSchema);e[t]=new Kl(n.reducer,r)}else if(mo.isInstance(n)){let r=n.schema?Za(n.schema):void 0;e[t]=new cD({guard:n.guard,initialValueFactory:r})}else if(So(n))e[t]=new Wp(Za(n));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let s;if(Ga.isInstance(r)?(s=Ba(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):mo.isInstance(r)?s=r.schema?Ba(r.schema):void 0:So(r)&&(s=Ba(r)),s){e[n]=s;let a=!1;Ga.isInstance(r)?a=Za(r.valueSchema)!==void 0:mo.isInstance(r)?a=r.schema?Za(r.schema)!==void 0:!1:a=Za(r)!==void 0,a||t.push(n)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;Ga.isInstance(n)?(r=Ba(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):mo.isInstance(n)?r=n.schema?Ba(n.schema):void 0:So(n)&&(r=Ba(n)),r&&(e[t]=r)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[n,r]of Object.entries(e)){let s=this.fields[n];if(s===void 0){t[n]=r;continue}let a;if(Ga.isInstance(s)?a=s.inputSchema:mo.isInstance(s)?a=s.schema:So(s)&&(a=s),a){let i=await a["~standard"].validate(r);if(i.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(i.issues)}`);t[n]=i.value}else t[n]=r}return t}static isInstance(e){return typeof e=="object"&&e!==null&&zf in e&&e[zf]===!0}};function Ra(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(kr),a=r.map(kr);for(let l of s)(l.id===null||l.id===void 0)&&(l.id=Gs(),l.lc_kwargs.id=l.id);let i;for(let l=0;l<a.length;l+=1){let d=a[l];(d.id===null||d.id===void 0)&&(d.id=Gs(),d.lc_kwargs.id=d.id),sa.isInstance(d)&&d.id==="__remove_all__"&&(i=l)}if(i!=null)return a.slice(i+1);let o=[...s],c=new Map(o.map((l,d)=>[l.id,d])),u=new Set;for(let l of a){let d=c.get(l.id);if(d!==void 0)sa.isInstance(l)?u.add(l.id):(u.delete(l.id),o[d]=l);else{if(sa.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,o.length),o.push(l)}}return o.filter(l=>!u.has(l.id))}new Ga(Lb().default(()=>[]),{inputSchema:Lb(),reducer:Ra,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var dD=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=rc(e);for(let[r,s]of Object.entries(n)){let a=this.get(s);a?.reducer?t[r]=new Kl(a.reducer.fn,a.default):t[r]=new Wp(a?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let a=Object.entries(rc(e)).map(([i,o])=>{let c=this.get(o),u=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=Ti(u)??Ti(o),d=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`lg:${d}`)}return[i,u]});s=Bx(e,Object.fromEntries(a)),gt(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Vy(s)),r.set(e,s),this._extensionCache.set(n,r),s}},ed=new dD;function pD(e,t){if(t.reducer&&!t.default){let n=Zx(e);n!=null&&(t.default=n)}if(t.reducer){let n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return ed.extend(n,()=>t),n}else return ed.extend(e,()=>t),e}function Ka(e){return e==null?!1:!!(Qs.isInstance(e)||Pn(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||qS(t)))}function hD(e){if(typeof e!="object"||e==null)return!1;let t=e,n="state"in t&&Ka(t.state),r="stateSchema"in t&&Ka(t.stateSchema),s="input"in t&&Ka(t.input);return!(!n&&!r&&!s||"input"in t&&t.input!=null&&!Ka(t.input)||"output"in t&&t.output!=null&&!Ka(t.output))}var ls="__root__",td=Symbol.for("langgraph.state.partial"),N_=class extends iD{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=ed;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new ah;let s=this._getChannelsFromSchema(r);this._schemaDefinition=s,Qs.isInstance(r)?this._schemaRuntimeDefinition=r:Pn(r)&&(this._schemaRuntimeDefinition=r),n.input?Qs.isInstance(n.input)?this._inputRuntimeDefinition=n.input:Pn(n.input)?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=td:this._inputRuntimeDefinition=td,n.output?Qs.isInstance(n.output)?this._outputRuntimeDefinition=n.output:Pn(n.output)?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):s,i=n.output?this._getChannelsFromSchema(n.output):s;this._inputDefinition=a,this._outputDefinition=i,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&Pn(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(hD(e)){if(Pn(t)||_g.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(Ka(e)){if(Pn(t)||_g.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(gD(e))return{state:fD(e.channels)};throw new ah}_getChannelsFromSchema(e){if(Qs.isInstance(e))return e.getChannels();if(Pn(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new ah("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(n=>[n,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let r;if(typeof n=="function"?r=n():r=n,this.channels[t]!==void 0){if(!this.channels[t].equals(r)&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=r}}}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([r,s])=>[r,s]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(let[r,s,a]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let l of["|",":"])if(r.includes(l))throw new Error(`"${l}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r==="__end__"||r==="__start__")throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;a?.input!==void 0&&(i=this._getChannelsFromSchema(a.input)),this._addSchema(i);let o;je.isRunnable(s)?o=s:typeof s=="function"?o=new ja({func:s,name:r,trace:!1}):o=Rt(s);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:o,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:i??this._schemaDefinition,subgraphs:S_(o)?[o]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[r]=u}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let n of e){if(n==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let n;for(let[r,s,a]of t){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);let i=r;this.addNode(i,s,a),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:s,name:a,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);let o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===ls?ls:o,u=Object.keys(this.channels),l=u.length===1&&u[0]===ls?ls:u,d=this._interrupt,p=new mD({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[wt]:new Pi},inputChannels:wt,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:n,name:a,description:i,userInterrupt:d});p.attachNode(wt);for(let[h,f]of Object.entries(this.nodes))p.attachNode(h,f);p.attachBranch(wt,w0,Db(),{withReader:!1});for(let[h]of Object.entries(this.nodes))p.attachBranch(h,w0,Db(),{withReader:!1});for(let[h,f]of this.edges)p.attachEdge(h,f);for(let[h,f]of this.waitingEdges)p.attachEdge(h,f);for(let[h,f]of Object.entries(this.branches))for(let[m,v]of Object.entries(f))p.attachBranch(h,m,v);return p.validate()}};function fD(e){let t={};for(let[n,r]of Object.entries(e))t[n]=JS(r);return t}var mD=class extends xT{description;_metaRegistry=ed;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;e==="__start__"?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):n=Object.keys(this.builder.channels);function r(o){if(Ut(o))return o.graph===_r.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Ut(c))){let c=[];for(let u of o)if(Ut(u)){if(u.graph===_r.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([ls,u]);return c}else if(o!=null)return[[ls,o]];return null}let s=e;function a(o){if(o){if(Ut(o))return o.graph===_r.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Ut)){let c=[];for(let u of o)if(Ut(u)){if(u.graph===_r.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>n.includes(l)))}else{let l=a(u);l&&c.push(...l??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>n.includes(c));{let c=Array.isArray(o)?"array":typeof o;throw new Xe(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let i=[{value:ca,mapper:new ja({func:n.length&&n[0]===ls?r:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new dc({tags:[dn],triggers:[wt],channels:[wt],writers:[new Xt(i,[dn])]});else{let o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),u=Object.keys(c).length===1&&ls in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new P9:new Pi(!1),this.nodes[e]=new dc({triggers:[l],channels:u?Object.keys(c):c,writers:[new Xt(i,[dn])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([p])=>p in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new Xt([{channel:`branch:to:${t}`,value:null}],[dn]));else if(Array.isArray(e)){let n=`join:${e.join("+")}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new lD(new Set(e)):new uD(new Set(e)),this.nodes[t].triggers.push(n);for(let r of e)this.nodes[r].writers.push(new Xt([{channel:n,value:r}],[dn]))}}}attachBranch(e,t,n,r={withReader:!0}){let s=async(a,i)=>{let o=a.filter(u=>u!==St);if(!o.length)return;let c=o.map(u=>fn(u)?u:{channel:u==="__end__"?u:`branch:to:${u}`,value:e});await Xt.doWrite({...i,tags:(i.tags??[]).concat([dn])},c)};this.nodes[e].writers.push(n.run(s,r.withReader?a=>D9.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(Qs.isInstance(t)){if(Ut(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===td&&Qs.isInstance(n)){if(Ut(e)){let s=e;return e.update&&(s.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await n.validateInput(e)}let r=(()=>{let s=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(Pn(t))return s(t);if(t===td)return Pn(n)?Vy(s(n)):void 0})();if(Ut(e)){let s=e;return e.update&&r!=null&&(s.update=al(r,e.update)),s}return r!=null?al(r,e):e}isInterrupted(e){return ek(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Pn(t)&&al(t,e),e}};function gD(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function yD(e){if(fn(e))return[e];let t=[];Ut(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Ut));let n=[];for(let r of t){if(r.graph===_r.PARENT)throw new nk(r);fn(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Db(){return new kT({path:new ja({func:yD,tags:[dn],trace:!1,recurse:!1,name:"<control_branch>"})})}var Re;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},e.getValidEnumValues=s=>{let a=e.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(a){return s[a]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},e.find=(s,a)=>{for(let i of s)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=r,e.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Re||(Re={}));var Sg;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Sg||(Sg={}));var J=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Dr=e=>{switch(typeof e){case"undefined":return J.undefined;case"string":return J.string;case"number":return Number.isNaN(e)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(e)?J.array:e===null?J.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?J.promise:typeof Map<"u"&&e instanceof Map?J.map:typeof Set<"u"&&e instanceof Set?J.set:typeof Date<"u"&&e instanceof Date?J.date:J.object;default:return J.unknown}},R=Re.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"]),_D=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ar=class IT extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(t){if(!(t instanceof IT))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];n[a]=n[a]||[],n[a].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ar.create=e=>new ar(e);var ji=(e,t)=>{let n;switch(e.code){case R.invalid_type:e.received===J.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Re.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${Re.joinValues(e.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Re.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${Re.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case R.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case R.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=t.defaultError,Re.assertNever(e)}return{message:n}},ET=ji;function vD(e){ET=e}function nd(){return ET}var rd=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}},wD=[];function q(e,t){let n=nd(),r=rd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ji?void 0:ji].filter(s=>!!s)});e.common.issues.push(r)}var Zt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return fe;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let a=await s.key,i=await s.value;r.push({key:a,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return fe;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:t.value,value:r}}},fe=Object.freeze({status:"aborted"}),sd=e=>({status:"dirty",value:e}),nn=e=>({status:"valid",value:e}),Tg=e=>e.status==="aborted",Ig=e=>e.status==="dirty",va=e=>e.status==="valid",gc=e=>typeof Promise<"u"&&e instanceof Promise,ie;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ie||(ie={}));var Ln=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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}},Fb=(e,t)=>{if(va(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ar(e.common.issues);return this._error=n,this._error}}};function xe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,i)=>{let{message:o}=e;return a.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:o??n??i.defaultError}},description:s}}var Ee=class{get description(){return this._def.description}_getType(e){return Dr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Zt,ctx:{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(gc(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Fb(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return va(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>va(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(gc(r)?r:Promise.resolve(r));return Fb(n,s)}refine(e,t){let n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let a=e(r),i=()=>s.addIssue({code:R.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(o=>o?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new An({schema:this,typeName:me.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 Or.create(this,this._def)}nullable(){return $s.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Sa.create(this)}promise(){return As.create(this,this._def)}or(e){return _c.create([this,e],this._def)}and(e){return vc.create(this,e,this._def)}transform(e){return new An({...xe(this._def),schema:this,typeName:me.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new bc({...xe(this._def),innerType:this,defaultValue:t,typeName:me.ZodDefault})}brand(){return new xc({typeName:me.ZodBranded,type:this,...xe(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new kc({...xe(this._def),innerType:this,catchValue:t,typeName:me.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Oc.create(this,e)}readonly(){return Sc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bD=/^c[^\s-]{8,}$/i,kD=/^[0-9a-z]+$/,xD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,OD=/^[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,SD=/^[a-z0-9_-]{21}$/i,TD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ID=/^[-+]?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)?)??$/,ED=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,AD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Uf,$D=/^(?:(?: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])$/,CD=/^(?:(?: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])$/,ND=/^(([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]))$/,PD=/^(([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])$/,jD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,RD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,AT="((\\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])))",MD=new RegExp(`^${AT}$`);function $T(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function LD(e){return new RegExp(`^${$T(e)}$`)}function CT(e){let t=`${AT}T${$T(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function zD(e,t){return!!((t==="v4"||!t)&&$D.test(e)||(t==="v6"||!t)&&ND.test(e))}function UD(e,t){if(!TD.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function DD(e,t){return!!((t==="v4"||!t)&&CD.test(e)||(t==="v6"||!t)&&PD.test(e))}var Ri=class To extends Ee{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==J.string){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.string,received:s.parsedType}),fe}let n=new Zt,r;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(r=this._getOrReturnCtx(t,r),a?q(r,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&q(r,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ED.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"email",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Uf||(Uf=new RegExp(AD,"u")),Uf.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"emoji",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")OD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"uuid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")SD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"nanoid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")bD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cuid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")kD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cuid2",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")xD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"ulid",code:R.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),q(r,{validation:"url",code:R.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"regex",code:R.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?CT(s).test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?MD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?LD(s).test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{code:R.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ID.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"duration",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?zD(t.data,s.version)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"ip",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?UD(t.data,s.alg)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"jwt",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?DD(t.data,s.version)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"cidr",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?jD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"base64",code:R.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?RD.test(t.data)||(r=this._getOrReturnCtx(t,r),q(r,{validation:"base64url",code:R.invalid_string,message:s.message}),n.dirty()):Re.assertNever(s);return{status:n.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:R.invalid_string,...ie.errToObj(r)})}_addCheck(t){return new To({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ie.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ie.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ie.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ie.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ie.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ie.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ie.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ie.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ie.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ie.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ie.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ie.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ie.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ie.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ie.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ie.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ie.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...ie.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ie.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ie.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ie.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ie.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ie.errToObj(n)})}nonempty(t){return this.min(1,ie.errToObj(t))}trim(){return new To({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new To({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new To({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ri.create=e=>new Ri({checks:[],typeName:me.ZodString,coerce:e?.coerce??!1,...xe(e)});function FD(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}var yc=class Eg extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==J.number){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.number,received:s.parsedType}),fe}let n,r=new Zt;for(let s of this._def.checks)s.kind==="int"?Re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:R.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?FD(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_finite,message:s.message}),r.dirty()):Re.assertNever(s);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ie.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ie.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ie.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ie.toString(n))}setLimit(t,n,r,s){return new Eg({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ie.toString(s)}]})}_addCheck(t){return new Eg({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ie.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ie.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ie.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ie.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ie.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ie.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ie.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ie.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ie.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Re.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};yc.create=e=>new yc({checks:[],typeName:me.ZodNumber,coerce:e?.coerce||!1,...xe(e)});var wa=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==J.bigint)return this._getInvalidInput(t);let n,r=new Zt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),q(n,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Re.assertNever(s);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.bigint,received:n.parsedType}),fe}gte(t,n){return this.setLimit("min",t,!0,ie.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ie.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ie.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ie.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ie.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ie.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ie.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ie.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ie.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ie.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};wa.create=e=>new wa({checks:[],typeName:me.ZodBigInt,coerce:e?.coerce??!1,...xe(e)});var ba=class extends Ee{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==J.boolean){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.boolean,received:n.parsedType}),fe}return nn(t.data)}};ba.create=e=>new ba({typeName:me.ZodBoolean,coerce:e?.coerce||!1,...xe(e)});var ka=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==J.date){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_type,expected:J.date,received:s.parsedType}),fe}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return q(s,{code:R.invalid_date}),fe}let n=new Zt,r;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(r=this._getOrReturnCtx(t,r),q(r,{code:R.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Re.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ie.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ie.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ka.create=e=>new ka({checks:[],coerce:e?.coerce||!1,typeName:me.ZodDate,...xe(e)});var Mi=class extends Ee{_parse(t){if(this._getType(t)!==J.symbol){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.symbol,received:n.parsedType}),fe}return nn(t.data)}};Mi.create=e=>new Mi({typeName:me.ZodSymbol,...xe(e)});var xa=class extends Ee{_parse(t){if(this._getType(t)!==J.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.undefined,received:n.parsedType}),fe}return nn(t.data)}};xa.create=e=>new xa({typeName:me.ZodUndefined,...xe(e)});var Oa=class extends Ee{_parse(t){if(this._getType(t)!==J.null){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.null,received:n.parsedType}),fe}return nn(t.data)}};Oa.create=e=>new Oa({typeName:me.ZodNull,...xe(e)});var Es=class extends Ee{constructor(){super(...arguments),this._any=!0}_parse(t){return nn(t.data)}};Es.create=e=>new Es({typeName:me.ZodAny,...xe(e)});var ua=class extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nn(e.data)}};ua.create=e=>new ua({typeName:me.ZodUnknown,...xe(e)});var Gr=class extends Ee{_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:R.invalid_type,expected:J.never,received:t.parsedType}),fe}};Gr.create=e=>new Gr({typeName:me.ZodNever,...xe(e)});var Li=class extends Ee{_parse(t){if(this._getType(t)!==J.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.void,received:n.parsedType}),fe}return nn(t.data)}};Li.create=e=>new Li({typeName:me.ZodVoid,...xe(e)});var Sa=class gl extends Ee{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==J.array)return q(n,{code:R.invalid_type,expected:J.array,received:n.parsedType}),fe;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(q(n,{code:i?R.too_big:R.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(q(n,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(q(n,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new Ln(n,i,n.path,o)))).then(i=>Zt.mergeArray(r,i));let a=[...n.data].map((i,o)=>s.type._parseSync(new Ln(n,i,n.path,o)));return Zt.mergeArray(r,a)}get element(){return this._def.type}min(t,n){return new gl({...this._def,minLength:{value:t,message:ie.toString(n)}})}max(t,n){return new gl({...this._def,maxLength:{value:t,message:ie.toString(n)}})}length(t,n){return new gl({...this._def,exactLength:{value:t,message:ie.toString(n)}})}nonempty(t){return this.min(1,t)}};Sa.create=(e,t)=>new Sa({type:e,minLength:null,maxLength:null,exactLength:null,typeName:me.ZodArray,...xe(t)});function Xa(e){if(e instanceof zn){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Or.create(Xa(r))}return new zn({...e._def,shape:()=>t})}else return e instanceof Sa?new Sa({...e._def,type:Xa(e.element)}):e instanceof Or?Or.create(Xa(e.unwrap())):e instanceof $s?$s.create(Xa(e.unwrap())):e instanceof Ar?Ar.create(e.items.map(t=>Xa(t))):e}var zn=class Jn extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Re.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==J.object){let c=this._getOrReturnCtx(t);return q(c,{code:R.invalid_type,expected:J.object,received:c.parsedType}),fe}let{status:n,ctx:r}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Gr&&this._def.unknownKeys==="strip"))for(let c in r.data)a.includes(c)||i.push(c);let o=[];for(let c of a){let u=s[c],l=r.data[c];o.push({key:{status:"valid",value:c},value:u._parse(new Ln(r,l,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Gr){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)o.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")i.length>0&&(q(r,{code:R.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=r.data[u];o.push({key:{status:"valid",value:u},value:c._parse(new Ln(r,l,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of o){let l=await u.key,d=await u.value;c.push({key:l,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>Zt.mergeObjectSync(n,c)):Zt.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(t){return ie.errToObj,new Jn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ie.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new Jn({...this._def,unknownKeys:"strip"})}passthrough(){return new Jn({...this._def,unknownKeys:"passthrough"})}extend(t){return new Jn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Jn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:me.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Jn({...this._def,catchall:t})}pick(t){let n={};for(let r of Re.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Jn({...this._def,shape:()=>n})}omit(t){let n={};for(let r of Re.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Jn({...this._def,shape:()=>n})}deepPartial(){return Xa(this)}partial(t){let n={};for(let r of Re.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new Jn({...this._def,shape:()=>n})}required(t){let n={};for(let r of Re.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Or;)s=s._def.innerType;n[r]=s}return new Jn({...this._def,shape:()=>n})}keyof(){return PT(Re.objectKeys(this.shape))}};zn.create=(e,t)=>new zn({shape:()=>e,unknownKeys:"strip",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});zn.strictCreate=(e,t)=>new zn({shape:()=>e,unknownKeys:"strict",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});zn.lazycreate=(e,t)=>new zn({shape:e,unknownKeys:"strip",catchall:Gr.create(),typeName:me.ZodObject,...xe(t)});var _c=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new ar(i.ctx.common.issues));return q(t,{code:R.invalid_union,unionErrors:a}),fe}if(t.common.async)return Promise.all(n.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let s,a=[];for(let o of n){let c={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(o=>new ar(o));return q(t,{code:R.invalid_union,unionErrors:i}),fe}}get options(){return this._def.options}};_c.create=(e,t)=>new _c({options:e,typeName:me.ZodUnion,...xe(t)});var ns=e=>e instanceof Ta?ns(e.schema):e instanceof An?ns(e.innerType()):e instanceof wc?[e.value]:e instanceof nu?e.options:e instanceof Ia?Re.objectValues(e.enum):e instanceof bc?ns(e._def.innerType):e instanceof xa?[void 0]:e instanceof Oa?[null]:e instanceof Or?[void 0,...ns(e.unwrap())]:e instanceof $s?[null,...ns(e.unwrap())]:e instanceof xc||e instanceof Sc?ns(e.unwrap()):e instanceof kc?ns(e._def.innerType):[],ad=class e extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.object)return q(n,{code:R.invalid_type,expected:J.object,received:n.parsedType}),fe;let r=this.discriminator,s=n.data[r],a=this.optionsMap.get(s);return a?n.common.async?a._parseAsync({data:n.data,path:n.path,parent:n}):a._parseSync({data:n.data,path:n.path,parent:n}):(q(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),fe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let a of n){let i=ns(a.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,a)}}return new e({typeName:me.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...xe(r)})}};function Ag(e,t){let n=Dr(e),r=Dr(t);if(e===t)return{valid:!0,data:e};if(n===J.object&&r===J.object){let s=Re.objectKeys(t),a=Re.objectKeys(e).filter(o=>s.indexOf(o)!==-1),i={...e,...t};for(let o of a){let c=Ag(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===J.array&&r===J.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let a=0;a<e.length;a++){let i=e[a],o=t[a],c=Ag(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===J.date&&r===J.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var vc=class extends Ee{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(s,a)=>{if(Tg(s)||Tg(a))return fe;let i=Ag(s.value,a.value);return i.valid?((Ig(s)||Ig(a))&&t.dirty(),{status:t.value,value:i.data}):(q(n,{code:R.invalid_intersection_types}),fe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>r(s,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};vc.create=(e,t,n)=>new vc({left:e,right:t,typeName:me.ZodIntersection,...xe(n)});var Ar=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.array)return q(r,{code:R.invalid_type,expected:J.array,received:r.parsedType}),fe;if(r.data.length<this._def.items.length)return q(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),fe;!this._def.rest&&r.data.length>this._def.items.length&&(q(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,i)=>{let o=this._def.items[i]||this._def.rest;return o?o._parse(new Ln(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>Zt.mergeArray(n,a)):Zt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ar.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ar({items:e,typeName:me.ZodTuple,rest:null,...xe(t)})};var NT=class $g extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.object)return q(r,{code:R.invalid_type,expected:J.object,received:r.parsedType}),fe;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in r.data)s.push({key:a._parse(new Ln(r,o,r.path,o)),value:i._parse(new Ln(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Zt.mergeObjectAsync(n,s):Zt.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ee?new $g({keyType:t,valueType:n,typeName:me.ZodRecord,...xe(r)}):new $g({keyType:Ri.create(),valueType:t,typeName:me.ZodRecord,...xe(n)})}},zi=class extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.map)return q(r,{code:R.invalid_type,expected:J.map,received:r.parsedType}),fe;let s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new Ln(r,o,r.path,[u,"key"])),value:a._parse(new Ln(r,c,r.path,[u,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return fe;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return fe;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}}}};zi.create=(e,t,n)=>new zi({valueType:t,keyType:e,typeName:me.ZodMap,...xe(n)});var Ui=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==J.set)return q(r,{code:R.invalid_type,expected:J.set,received:r.parsedType}),fe;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(q(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(q(r,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return fe;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let o=[...r.data.values()].map((c,u)=>a._parse(new Ln(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:ie.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:ie.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Ui.create=(e,t)=>new Ui({valueType:e,minSize:null,maxSize:null,typeName:me.ZodSet,...xe(t)});var id=class e extends Ee{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.function)return q(n,{code:R.invalid_type,expected:J.function,received:n.parsedType}),fe;function r(o,c){return rd({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nd(),ji].filter(u=>!!u),issueData:{code:R.invalid_arguments,argumentsError:c}})}function s(o,c){return rd({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nd(),ji].filter(u=>!!u),issueData:{code:R.invalid_return_type,returnTypeError:c}})}let a={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof As){let o=this;return nn(async function(...c){let u=new ar([]),l=await o._def.args.parseAsync(c,a).catch(p=>{throw u.addIssue(r(c,p)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,a).catch(p=>{throw u.addIssue(s(d,p)),u})})}else{let o=this;return nn(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new ar([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,a);if(!d.success)throw new ar([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ar.create(t).rest(ua.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ar.create([]).rest(ua.create()),returns:n||ua.create(),typeName:me.ZodFunction,...xe(r)})}},Ta=class extends Ee{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ta.create=(e,t)=>new Ta({getter:e,typeName:me.ZodLazy,...xe(t)});var wc=class extends Ee{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),fe}return{status:"valid",value:e.data}}get value(){return this._def.value}};wc.create=(e,t)=>new wc({value:e,typeName:me.ZodLiteral,...xe(t)});function PT(e,t){return new nu({values:e,typeName:me.ZodEnum,...xe(t)})}var nu=class Cg extends Ee{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return q(n,{expected:Re.joinValues(r),received:n.parsedType,code:R.invalid_type}),fe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return q(n,{received:n.data,code:R.invalid_enum_value,options:r}),fe}return nn(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Cg.create(t,{...this._def,...n})}exclude(t,n=this._def){return Cg.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};nu.create=PT;var Ia=class extends Ee{_parse(t){let n=Re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==J.string&&r.parsedType!==J.number){let s=Re.objectValues(n);return q(r,{expected:Re.joinValues(s),received:r.parsedType,code:R.invalid_type}),fe}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=Re.objectValues(n);return q(r,{received:r.data,code:R.invalid_enum_value,options:s}),fe}return nn(t.data)}get enum(){return this._def.values}};Ia.create=(e,t)=>new Ia({values:e,typeName:me.ZodNativeEnum,...xe(t)});var As=class extends Ee{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==J.promise&&n.common.async===!1)return q(n,{code:R.invalid_type,expected:J.promise,received:n.parsedType}),fe;let r=n.parsedType===J.promise?n.data:Promise.resolve(n.data);return nn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};As.create=(e,t)=>new As({type:e,typeName:me.ZodPromise,...xe(t)});var An=class extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===me.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,a={addIssue:i=>{q(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(n.value==="aborted")return fe;let c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?fe:c.status==="dirty"||n.value==="dirty"?sd(c.value):c});{if(n.value==="aborted")return fe;let o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?fe:o.status==="dirty"||n.value==="dirty"?sd(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?fe:(o.status==="dirty"&&n.dirty(),i(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?fe:(o.status==="dirty"&&n.dirty(),i(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!va(i))return fe;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>va(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:n.value,value:o})):fe);Re.assertNever(s)}};An.create=(e,t,n)=>new An({schema:e,typeName:me.ZodEffects,effect:t,...xe(n)});An.createWithPreprocess=(e,t,n)=>new An({schema:t,effect:{type:"preprocess",transform:e},typeName:me.ZodEffects,...xe(n)});var Or=class extends Ee{_parse(e){return this._getType(e)===J.undefined?nn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Or.create=(e,t)=>new Or({innerType:e,typeName:me.ZodOptional,...xe(t)});var $s=class extends Ee{_parse(e){return this._getType(e)===J.null?nn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$s.create=(e,t)=>new $s({innerType:e,typeName:me.ZodNullable,...xe(t)});var bc=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===J.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};bc.create=(e,t)=>new bc({innerType:e,typeName:me.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...xe(t)});var kc=class extends Ee{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gc(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};kc.create=(e,t)=>new kc({innerType:e,typeName:me.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...xe(t)});var Di=class extends Ee{_parse(t){if(this._getType(t)!==J.nan){let n=this._getOrReturnCtx(t);return q(n,{code:R.invalid_type,expected:J.nan,received:n.parsedType}),fe}return{status:"valid",value:t.data}}};Di.create=e=>new Di({typeName:me.ZodNaN,...xe(e)});var BD=Symbol("zod_brand"),xc=class extends Ee{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Oc=class e extends Ee{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?fe:s.status==="dirty"?(n.dirty(),sd(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?fe:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:me.ZodPipeline})}},Sc=class extends Ee{_parse(e){let t=this._def.innerType._parse(e),n=r=>(va(r)&&(r.value=Object.freeze(r.value)),r);return gc(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:me.ZodReadonly,...xe(t)});function Bb(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function P_(e,t={},n){return e?Es.create().superRefine((r,s)=>{let a=e(r);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Bb(t,r),c=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Bb(t,r),o=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:o})}}):Es.create()}var ZD={object:zn.lazycreate},me;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(me||(me={}));var qD=(e,t={message:`Input not instance of ${e.name}`})=>P_(n=>n instanceof e,t),un=Ri.create,Vo=yc.create,VD=Di.create,HD=wa.create,jT=ba.create,WD=ka.create,JD=Mi.create,GD=xa.create,KD=Oa.create,XD=Es.create,YD=ua.create,QD=Gr.create,e3=Li.create,ui=Sa.create,os=zn.create,t3=zn.strictCreate,n3=_c.create,r3=ad.create,s3=vc.create,a3=Ar.create,i3=NT.create,o3=zi.create,c3=Ui.create,u3=id.create,l3=Ta.create,Io=wc.create,d3=nu.create,p3=Ia.create,h3=As.create,Zb=An.create,f3=Or.create,m3=$s.create,g3=An.createWithPreprocess,y3=Oc.create,_3=()=>un().optional(),v3=()=>Vo().optional(),w3=()=>jT().optional(),b3={string:(e=>Ri.create({...e,coerce:!0})),number:(e=>yc.create({...e,coerce:!0})),boolean:(e=>ba.create({...e,coerce:!0})),bigint:(e=>wa.create({...e,coerce:!0})),date:(e=>ka.create({...e,coerce:!0}))},k3=fe,Dt=Object.freeze(Object.defineProperty({__proto__:null,BRAND:BD,DIRTY:sd,EMPTY_PATH:wD,INVALID:fe,NEVER:k3,OK:nn,ParseStatus:Zt,Schema:Ee,ZodAny:Es,ZodArray:Sa,ZodBigInt:wa,ZodBoolean:ba,ZodBranded:xc,ZodCatch:kc,ZodDate:ka,ZodDefault:bc,ZodDiscriminatedUnion:ad,ZodEffects:An,ZodEnum:nu,ZodError:ar,get ZodFirstPartyTypeKind(){return me},ZodFunction:id,ZodIntersection:vc,ZodIssueCode:R,ZodLazy:Ta,ZodLiteral:wc,ZodMap:zi,ZodNaN:Di,ZodNativeEnum:Ia,ZodNever:Gr,ZodNull:Oa,ZodNullable:$s,ZodNumber:yc,ZodObject:zn,ZodOptional:Or,ZodParsedType:J,ZodPipeline:Oc,ZodPromise:As,ZodReadonly:Sc,ZodRecord:NT,ZodSchema:Ee,ZodSet:Ui,ZodString:Ri,ZodSymbol:Mi,ZodTransformer:An,ZodTuple:Ar,ZodType:Ee,ZodUndefined:xa,ZodUnion:_c,ZodUnknown:ua,ZodVoid:Li,addIssueToContext:q,any:XD,array:ui,bigint:HD,boolean:jT,coerce:b3,custom:P_,date:WD,datetimeRegex:CT,defaultErrorMap:ji,discriminatedUnion:r3,effect:Zb,enum:d3,function:u3,getErrorMap:nd,getParsedType:Dr,instanceof:qD,intersection:s3,isAborted:Tg,isAsync:gc,isDirty:Ig,isValid:va,late:ZD,lazy:l3,literal:Io,makeIssue:rd,map:o3,nan:VD,nativeEnum:p3,never:QD,null:KD,nullable:m3,number:Vo,object:os,get objectUtil(){return Sg},oboolean:w3,onumber:v3,optional:f3,ostring:_3,pipeline:y3,preprocess:g3,promise:h3,quotelessJson:_D,record:i3,set:c3,setErrorMap:vD,strictObject:t3,string:un,symbol:JD,transformer:Zb,tuple:a3,undefined:GD,union:n3,unknown:YD,get util(){return Re},void:e3},Symbol.toStringTag,{value:"Module"}));mt.Root({messages:mt({reducer:Ra,default:()=>[]})});var x3={reducer:{fn:Ra},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};os({messages:pD(P_(),x3)});async function O3(e,t,n){if(n===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
267
267
 
268
268
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
269
269
 
@@ -340,22 +340,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
340
340
  ]))`;continue}else if(s[u]==="$"){a+=`($|(?=[\r
341
341
  ]))`;continue}}if(r.s&&s[u]==="."){a+=o?`${s[u]}\r
342
342
  `:`[${s[u]}\r
343
- ]`;continue}a+=s[u],s[u]==="\\"?i=!0:o&&s[u]==="]"?o=!1:!o&&s[u]==="["&&(o=!0)}try{let u=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function OE(e,t){if(t.target==="openApi3"&&e.keyType?._def.typeName===ke.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===ke.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(xE(e.keyType._def,t)).reduce((s,[a,i])=>a==="type"?s:{...s,[a]:i},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===ke.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function zq(e,t){if(t.mapStrategy==="record")return OE(e,t);let n=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},r=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Uq(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),r=Array.from(new Set(n.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function Dq(){return{not:{}}}function Fq(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var mp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Bq(e,t){if(t.target==="openApi3")return W1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in mp&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,a)=>{let i=mp[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];default:return s}},[]);if(r.length===n.length){let s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return W1(e,t)}var W1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Be(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Zq(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"||t.nullableStrategy==="property"?{type:mp[e.innerType._def.typeName],nullable:!0}:{type:[mp[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function qq(e,t){let n={type:"number"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"int":n.type="integer",bE(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?He(n,"minimum",r.value,r.message,t):He(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),He(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?He(n,"maximum",r.value,r.message,t):He(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),He(n,"maximum",r.value,r.message,t));break;case"multipleOf":He(n,"multipleOf",r.value,r.message,t);break}return n}function Vq(e,t){return t.removeAdditionalStrategy==="strict"?e.catchall._def.typeName==="ZodNever"?e.unknownKeys!=="strict":Be(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:e.catchall._def.typeName==="ZodNever"?e.unknownKeys==="passthrough":Be(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function Hq(e,t){let n={type:"object",...Object.entries(e.shape()).reduce((r,[s,a])=>{if(a===void 0||a._def===void 0)return r;let i=[...t.currentPath,"properties",s],o=Be(a._def,{...t,currentPath:i,propertyPath:i});if(o===void 0)return r;if(t.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[s]:o},required:a.isOptional()&&!t.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:Vq(e,t)};return n.required.length||delete n.required,n}var Wq=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return Be(e.innerType._def,{...t,currentPath:t.currentPath});let n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Jq=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);if(t.pipeStrategy==="output")return Be(e.out._def,t);let n=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function Gq(e,t){return Be(e.type._def,t)}function Kq(e,t){let n={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&He(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&He(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Xq(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Be(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Be(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Yq(){return{not:{}}}function Qq(){return{}}var eV=(e,t)=>Be(e.innerType._def,t);function Be(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==wq)return i}if(r&&!n){let i=tV(r,t);if(i!==void 0)return"$ref"in i&&t.seenRefs.add(i.$ref),i}let s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);let a=rV(e,e.typeName,t,n);return a&&sV(e,t,a),s.jsonSchema=a,a}var tV=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":let n=e.path.slice(t.basePath.length+1).join("_");return n!==t.name&&t.nameStrategy==="duplicate-ref"&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join("/")};case"relative":return{$ref:nV(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,s)=>t.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},nV=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},rV=(e,t,n,r)=>{switch(t){case ke.ZodString:return xE(e,n);case ke.ZodNumber:return qq(e,n);case ke.ZodObject:return Hq(e,n);case ke.ZodBigInt:return Tq(e,n);case ke.ZodBoolean:return Iq();case ke.ZodDate:return kE(e,n);case ke.ZodUndefined:return Yq();case ke.ZodNull:return Fq(n);case ke.ZodArray:return Sq(e,n);case ke.ZodUnion:case ke.ZodDiscriminatedUnion:return Bq(e,n);case ke.ZodIntersection:return Rq(e,n);case ke.ZodTuple:return Xq(e,n);case ke.ZodRecord:return OE(e,n);case ke.ZodLiteral:return Mq(e,n);case ke.ZodEnum:return Pq(e);case ke.ZodNativeEnum:return Uq(e);case ke.ZodNullable:return Zq(e,n);case ke.ZodOptional:return Wq(e,n);case ke.ZodMap:return zq(e,n);case ke.ZodSet:return Kq(e,n);case ke.ZodLazy:return Be(e.getter()._def,n);case ke.ZodPromise:return Gq(e,n);case ke.ZodNaN:case ke.ZodNever:return Dq();case ke.ZodEffects:return Nq(e,n,r);case ke.ZodAny:return Oq();case ke.ZodUnknown:return Qq();case ke.ZodDefault:return Cq(e,n);case ke.ZodBranded:return Eq(e,n);case ke.ZodReadonly:return eV(e,n);case ke.ZodCatch:return Aq(e,n);case ke.ZodPipeline:return Jq(e,n);case ke.ZodFunction:case ke.ZodVoid:case ke.ZodSymbol:return;default:return(s=>{})()}},sV=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),aV=(e,t)=>{let n=xq(t),r=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Be(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a);let i=(()=>{if(kq(n.definitions))return;let c={},u=new Set;for(let l=0;l<500;l++){let d=Object.entries(n.definitions).filter(([p])=>!u.has(p));if(d.length===0)break;for(let[p,h]of d)c[p]=Be(sy(h),{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0)??{},u.add(p)}return c})(),o=r===void 0?i?{...s,[n.definitionPath]:i}:s:n.nameStrategy==="duplicate-ref"?{...s,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:s}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function iV(e){if(e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);let t=structuredClone(e);return Rr(t,[],t)}function ay(e){if(typeof e=="boolean")return!1;if(e.type==="null")return!0;for(let t of e.oneOf??[])if(ay(t))return!0;for(let t of e.anyOf??[])if(ay(t))return!0;return!1}function Rr(e,t,n){if(typeof e=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${t.join("/")}`);if(!Js(e))throw new TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join("/")}`);let r=e.$defs;if(Js(r))for(let[d,p]of Object.entries(r))Rr(p,[...t,"$defs",d],n);let s=e.definitions;if(Js(s))for(let[d,p]of Object.entries(s))Rr(p,[...t,"definitions",d],n);e.type==="object"&&!("additionalProperties"in e)&&(e.additionalProperties=!1);let a=e.required??[],i=e.properties;if(Js(i)){for(let[d,p]of Object.entries(i))if(!ay(p)&&!a.includes(d))throw new Error(`Zod field at \`${[...t,"properties",d].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(i),e.properties=Object.fromEntries(Object.entries(i).map(([d,p])=>[d,Rr(p,[...t,"properties",d],n)]))}let o=e.items;Js(o)&&(e.items=Rr(o,[...t,"items"],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((d,p)=>Rr(d,[...t,"anyOf",String(p)],n)));let u=e.allOf;if(Array.isArray(u))if(u.length===1){let d=Rr(u[0],[...t,"allOf","0"],n);Object.assign(e,d),delete e.allOf}else e.allOf=u.map((d,p)=>Rr(d,[...t,"allOf",String(p)],n));e.default===null&&delete e.default;let l=e.$ref;if(l&&cV(e,1)){if(typeof l!="string")throw new TypeError(`Received non-string $ref - ${l}; path=${t.join("/")}`);let d=oV(n,l);if(typeof d=="boolean")throw new Error(`Expected \`$ref: ${l}\` to resolve to an object schema but got boolean`);if(!Js(d))throw new Error(`Expected \`$ref: ${l}\` to resolve to an object but got ${JSON.stringify(d)}`);return Object.assign(e,{...d,...e}),delete e.$ref,Rr(e,t,n)}return e}function oV(e,t){if(!t.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split("/"),r=e;for(let s of n){if(!Js(r))throw new Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let a=r[s];if(a===void 0)throw new Error(`Key ${s} not found while resolving ${t}`);r=a}return r}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cV(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function uV(e,t){return aV(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function lV(e){return iV(s8(e,{target:"draft-7"}))}function dV(e){return"_zod"in e}function pV(e,t,n){return aF({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:dV(e)?lV(e):uV(e,{name:t})}},r=>e.parse(JSON.parse(r)))}var J1=["jsonSchema","functionCalling","jsonMode"];function hV(e,t){if(typeof t<"u"&&!J1.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${J1.join(", ")}`);let n=!e.startsWith("gpt-3")&&!e.startsWith("gpt-4-")&&e!=="gpt-4";if(n&&!t)return"jsonSchema";if(!n&&t==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??"functionCalling"}function fV(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function mV(e,t,n){if(mt(e))return pV(e,t,n);if(nt(e))return fV({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:It(e,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=t}})}},r=>i6(e,JSON.parse(r)));throw new Error("Unsupported schema response format")}function gV(e,t){if(t&&typeof t=="object"&&"images"in t&&Array.isArray(t.images)){let n=t.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:e},...n]}return e}var yV={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function e0(e,t){return typeof e=="string"?{model:e,...t??{}}:e??t}var t0=class extends Pa{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??rr("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??rr("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.3.0")}_getReasoningParams(e){if(!au(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&En(e.json_schema.schema)?mV(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let t=$F({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=PF(n.defaultHeaders),this.client=new be(n)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return ap(e)?qF(e.metadata.customTool):r_(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:jF(e,t)}bindTools(e,t){let n;return t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:e.map(r=>{if(q_(r)||ap(r))return r;if(LF(r))return r.extras.providerToolDefinition;let s=this._convertChatOpenAIToolToCompletionsTool(r,{strict:n});return tu(r)&&r.extras?.defer_loading===!0?{...s,defer_loading:!0}:s}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,n)=>(n&&n.tokenUsage&&(t.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model==="gpt-3.5-turbo-0301"?(n=4,r=-1):(n=3,r=1);let s=await Promise.all(e.map(async a=>{let[i,o]=await Promise.all([this.getNumTokens(a.content),this.getNumTokens(iu(a))]),c=a.name!==void 0?r+await this.getNumTokens(a.name):0,u=i+n+o+c,l=a;if(l._getType()==="function"&&(u-=2),l.additional_kwargs?.function_call&&(u+=3),l?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(d){console.error("Error parsing function arguments",d,JSON.stringify(l.additional_kwargs.function_call)),u+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=u,u}));return t+=3,{totalCount:t,countPerMessage:s}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async t=>t.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([t.message])).countPerMessage[0]:await this.getNumTokens(t.message.content)))).reduce((t,n)=>t+n,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!=="auto"){let s=MF(t);r+=await this.getNumTokens(s),r+=9}return t&&e.find(s=>s._getType()==="system")&&(r-=4),n==="none"?r+=1:typeof n=="object"&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(s){throw Z_(s)}})}get profile(){return yV[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:s,name:a,includeRaw:i}={...t,schema:e};if(t?.strict!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let o=hV(this.model,t?.method);if(o==="jsonMode"){r=og(s);let c=It(s);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...c}}})}else if(o==="jsonSchema"){let c=It(s),u={name:a??"extract",description:Ti(c),schema:En(s)?s:c,strict:t?.strict};if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...c}}}),En(s)||ha(s)){let l=og(s);r=lr.from(async d=>"parsed"in d.additional_kwargs?d.additional_kwargs.parsed:l.invoke(d.content))}else r=new i_}else{let c=a??"extract",u=It(s),l;En(s)||ha(s)?l={name:c,description:u.description,parameters:u}:typeof s.name=="string"&&typeof s.parameters=="object"&&s.parameters!=null?(l=s,c=s.name):(c=s.title??c,l={name:c,description:s.description??"",parameters:s}),n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:l}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...t?.strict!==void 0?{strict:t.strict}:{}}),r=FO(s,c)}return c_(n,r,i)}},SE={providerName:"ChatOpenAI",fromStandardTextBlock(e){return{type:"text",text:e.text}},fromStandardImageBlock(e){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type==="base64")return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type==="url"){let t=Ko({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||"",r;try{r=om(n)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:t.data}}}if(e.source_type==="base64"){let t;try{t=om(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!=="audio"||t.subtype!=="wav"&&t.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type==="url"){let t=Ko({dataUrl:e.url}),n=rp(e);if(!t)throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:n}:{}}}}if(e.source_type==="base64"){let t=rp(e);return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:t}:{}}}}if(e.source_type==="id")return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},_V=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls;switch(e.role){case"assistant":{let s=[],a=[];for(let c of r??[])try{s.push(Dp(c,{returnId:!0}))}catch(u){a.push(Zo(c,u.message))}let i={function_call:e.function_call,tool_calls:r};n!==void 0&&(i.__raw_response=t);let o={model_provider:"openai",model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(i.audio=e.audio),new Ke({content:gV(e.content||"",t.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:t.id})}default:return new Kr(e.content||"",e.role??"unknown")}},vV=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let s=e.role??r,a=e.content??"",i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},n&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});let o={model_provider:"openai",usage:{...t.usage}};if(s==="user")return new qc({content:a,response_metadata:o});if(s==="assistant"){let c=[];if(Array.isArray(e.tool_calls))for(let u of e.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new mn({content:a,tool_call_chunks:c,additional_kwargs:i,id:t.id,response_metadata:o})}else return s==="system"?new ws({content:a,response_metadata:o}):s==="developer"?new ws({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new Zc({content:a,additional_kwargs:i,name:e.name,response_metadata:o}):s==="tool"?new Fc({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new Bc({content:a,role:s,response_metadata:o})},wV=e=>{if(e.type==="image"){if(e.url)return{type:"image_url",image_url:{url:e.url}};if(e.data)return{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type==="audio"&&e.data){let t=jk(()=>{let[,n]=e.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:e.data.toString(),format:t}}}if(e.type==="file"){if(e.data){let t=rp(e);return{type:"file",file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:"file",file:{file_id:e.fileId}}}},bV=({message:e,model:t})=>{let n=iu(e);if(n==="system"&&au(t)&&(n="developer"),n==="developer")return{role:"developer",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="system")return{role:"system",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="assistant")return{role:"assistant",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="tool"&&Mn.isInstance(e))return{role:"tool",tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="function")return{role:"function",name:e.name??"",content:e.contentBlocks.filter(s=>s.type==="text").join("")};function*r(s){for(let a of s){a.type==="text"&&(yield{type:"text",text:a.text});let i=wV(a);i&&(yield i)}}return{role:"user",content:Array.from(r(e.contentBlocks))}},G1=({messages:e,model:t})=>e.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return bV({message:n});let r=iu(n);r==="system"&&au(t)&&(r="developer");let s=typeof n.content=="string"?n.content:n.content.flatMap(i=>Sr(i)?yy(i,SE):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),a={role:r,content:s};return n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call),Ke.isInstance(n)&&n.tool_calls?.length?a.tool_calls=n.tool_calls.map(zO):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Mn.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[a,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:a}),kV=class extends t0{constructor(e,t){super(e0(e,t))}invocationParams(e,t){let n;e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};e?.stream_options!==void 0?r={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}});let s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:n})):void 0,tool_choice:AI(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(s.prediction=e.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),e?.service_tier!==void 0&&(s.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(s.reasoning_effort=a.effort),au(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},s=this.invocationParams(t),a=G1({messages:e,model:this.model});if(s.stream){let i=this._streamResponseChunks(e,t,n),o={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let f=h.generationInfo?.completion??0;o[f]===void 0?o[f]=h:o[f]=o[f].concat(h)}let c=Object.entries(o).sort(([h],[f])=>parseInt(h,10)-parseInt(f,10)).map(([h,f])=>f),{functions:u,function_call:l}=this.invocationParams(t),d=await this._getEstimatedTokenCountFromPrompt(e,u,l),p=await this._getNumTokensFromGenerations(c);return r.input_tokens=d,r.output_tokens=p,r.total_tokens=d+p,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let i=await this.completionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:o,prompt_tokens:c,total_tokens:u,prompt_tokens_details:l,completion_tokens_details:d}=i?.usage??{};o&&(r.output_tokens=(r.output_tokens??0)+o),c&&(r.input_tokens=(r.input_tokens??0)+c),u&&(r.total_tokens=(r.total_tokens??0)+u),(l?.audio_tokens!==null||l?.cached_tokens!==null)&&(r.input_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.cached_tokens!==null&&{cache_read:l?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(r.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let p=[];for(let h of i?.choices??[]){let f={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};f.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},kp(f.message)&&(f.message.usage_metadata=r),f.message=new Ke(Object.fromEntries(Object.entries(f.message).filter(([m])=>!m.startsWith("lc_")))),p.push(f)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(e,t,n){let r=G1({messages:e,model:this.model}),s={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,i=await this.completionWithRetry(s,t),o;for await(let c of i){if(t.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(o=c.usage),!u)continue;let{delta:l}=u;if(!l)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(l,c,a);a=l.role??a;let p={prompt:t.promptIndex??0,completion:u.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={...p};u.finish_reason!=null&&(h.finish_reason=u.finish_reason,h.system_fingerprint=c.system_fingerprint,h.model_name=c.model,h.service_tier=c.service_tier),this.logprobs&&(h.logprobs=u.logprobs);let f=new Wr({message:d,text:d.content,generationInfo:h});yield f,await n?.handleLLMNewToken(f.text??"",p,void 0,void 0,void 0,{chunk:f})}if(o){let c={...o.prompt_tokens_details?.audio_tokens!==null&&{audio:o.prompt_tokens_details?.audio_tokens},...o.prompt_tokens_details?.cached_tokens!==null&&{cache_read:o.prompt_tokens_details?.cached_tokens}},u={...o.completion_tokens_details?.audio_tokens!==null&&{audio:o.completion_tokens_details?.audio_tokens},...o.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},l=new Wr({message:new mn({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield l,await n?.handleLLMNewToken(l.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:l})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(s){throw Z_(s)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return vV({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return _V({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},gp="__openai_function_call_ids__";function TE(e){return e.type==="url_citation"?{type:"citation",source:"url_citation",url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type==="file_citation"?{type:"citation",source:"file_citation",title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type==="file_path"?{type:"citation",source:"file_path",startIndex:e.index,file_id:e.file_id}:{type:"non_standard",value:e}}function xV(e){if(e.type==="url_citation"||e.type==="file_citation"||e.type==="container_file_citation"||e.type==="file_path")return e;if(e.type==="citation"){let t=e;if(t.source==="url_citation")return{type:"url_citation",url:t.url??"",title:t.title??"",start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source==="file_citation")return{type:"file_citation",file_id:t.file_id??"",filename:t.title??"",index:t.startIndex??0};if(t.source==="container_file_citation")return{type:"container_file_citation",file_id:t.file_id??"",filename:t.title??"",container_id:t.container_id??"",start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source==="file_path")return{type:"file_path",file_id:t.file_id??"",index:t.startIndex??0}}return e.type==="non_standard"?e.value:e}var IE=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},EE=e=>{if(e.error){let c=new Error(e.error.message);throw c.name=e.error.code,c}let t,n=[],r=[],s=[],a=e.output.map(c=>{if(c.type==="function_call"&&"parsed_arguments"in c){let u={...c};return delete u.parsed_arguments,u}return c}),i={model_provider:"openai",model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:a,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let c of e.output)if(c.type==="message")t=c.id,n.push(...c.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(o.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(TE)}):u.type==="refusal"?(o.refusal=u.refusal,[]):u));else if(c.type==="function_call"){let u={function:{name:c.name,arguments:c.arguments},id:c.call_id};try{r.push(Dp(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),s.push(Zo(u,d))}o[gp]??={},c.id&&(o[gp][c.call_id]=c.id)}else if(c.type==="reasoning"){o.reasoning=c;let u=c.summary?.map(l=>l.text).filter(Boolean).join("");u&&n.push({type:"reasoning",reasoning:u})}else if(c.type==="custom_tool_call"){let u=UF(c);u?r.push(u):s.push(Zo(c,"Malformed custom tool call"))}else if(c.type==="computer_call"){let u=DF(c);u?r.push(u):s.push(Zo(c,"Malformed computer call"))}else c.type==="image_generation_call"?(c.result&&n.push({type:"image",mimeType:"image/png",data:c.result,id:c.id,metadata:{status:c.status}}),o.tool_outputs??=[],o.tool_outputs.push(c)):(o.tool_outputs??=[],o.tool_outputs.push(c));return new Ke({id:t,content:n,tool_calls:r,invalid_tool_calls:s,usage_metadata:IE(e.usage),additional_kwargs:o,response_metadata:i})},OV=e=>{let t=(e.summary.length>1?e.summary.reduce((n,r)=>{let s=n[n.length-1];return s.index===r.index?s.text+=r.text:n.push(r),n},[{...e.summary[0]}]):e.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...e,summary:t}},SV=e=>{let t=[],n={},r,s=[],a={model_provider:"openai"},i={},o;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[TE(e.annotation)],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")o=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),i[gp]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&e.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),i.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&e.item.type==="image_generation_call")e.item.result&&t.push({type:"image",mimeType:"image/png",data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),i.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(e.item.type))i.tool_outputs=[e.item];else if(e.type==="response.created")a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type==="response.completed"){let c=EE(e.response);r=IE(e.response.usage),e.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(let[u,l]of Object.entries(e.response))u!=="id"&&(u==="output"?a[u]=c.response_metadata.output:a[u]=l)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")i.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){let c=e.item.summary?e.item.summary.map((l,d)=>({...l,index:d})):void 0;i.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}};let u=e.item.summary?.map(l=>l.text).filter(Boolean).join("");u&&t.push({type:"reasoning",reasoning:u})}else if(e.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:"reasoning",reasoning:e.part.text});else if(e.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]},e.delta&&t.push({type:"reasoning",reasoning:e.delta});else return e.type,null;return new Wr({text:t.map(c=>c.text).join(""),message:new mn({id:o,content:t,tool_call_chunks:s,usage_metadata:r,additional_kwargs:i,response_metadata:a}),generationInfo:n})},TV=e=>{let t=Ke.isInstance(e)&&e.response_metadata?.model_provider==="openai";function*n(){let r=da(()=>{try{let g=iu(e);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),s,a=new Set,i=new Set,o=new Map,c=new Map;function*u(){if(!s)return;let g=s.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield s),s=void 0}let l=g=>{s||(s={type:"message",role:r,content:[]}),typeof s.content=="string"?s.content=s.content.length>0?[{type:"input_text",text:s.content},...g]:[...g]:s.content.push(...g)},d=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},p=g=>{let y=da(()=>{let k=g.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(g.fileId)return{type:"input_image",detail:y,file_id:g.fileId};if(g.url)return{type:"input_image",detail:y,image_url:g.url};if(g.data){let k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:y,image_url:`data:${g.mimeType??"image/png"};base64,${k}`}}},h=g=>{if(g.fileId){let y=_1(g);return{type:"input_file",file_id:g.fileId,...y?{filename:y}:{}}}if(g.url){let y=_1(g);return{...y?{filename:y}:{},type:"input_file",file_url:g.url}}if(g.data){let y=rp(g),k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${k}`,...y?{filename:y}:{}}}},f=g=>{let y=da(()=>{if(Array.isArray(g.summary)){let S=g.summary?.map(E=>E?.text).filter(E=>typeof E=="string")??[];if(S.length>0)return S}return g.reasoning?[g.reasoning]:[]}),k=y.length>0?y.map(S=>({type:"summary_text",text:S})):[{type:"summary_text",text:""}],x={type:"reasoning",id:g.id??"",summary:k};return g.reasoning&&(x.content=[{type:"reasoning_text",text:g.reasoning}]),x},m=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:d(g.args)}),v=g=>{let y=d(g.output),k=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:y,...k?{status:k}:{}}};for(let g of e.contentBlocks)if(g.type==="text")l([{type:"input_text",text:g.text}]);else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*u(),yield f(g);else if(g.type==="tool_call"){yield*u();let y=g.id??"";y&&(a.add(y),o.delete(y)),yield m(g)}else if(g.type==="tool_call_chunk"){if(g.id){let y=o.get(g.id)??{name:g.name,args:[]};g.name&&(y.name=g.name),g.args&&y.args.push(g.args),o.set(g.id,y)}}else if(g.type==="server_tool_call"){yield*u();let y=g.id??"";y&&(i.add(y),c.delete(y)),yield m(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let y=c.get(g.id)??{name:g.name,args:[]};g.name&&(y.name=g.name),g.args&&y.args.push(g.args),c.set(g.id,y)}}else if(g.type==="server_tool_call_result")yield*u(),yield v(g);else if(g.type!=="audio")if(g.type==="file"){let y=h(g);y&&l([y])}else if(g.type==="image"){let y=p(g);y&&l([y])}else if(g.type==="video"){let y=h(g);y&&l([y])}else g.type==="text-plain"?g.text&&l([{type:"input_text",text:g.text}]):g.type==="non_standard"&&t&&(yield*u(),yield g.value)}yield*u();for(let[g,y]of o){if(!g||a.has(g))continue;let k=y.args.join("");!y.name&&!k||(yield{type:"function_call",call_id:g,name:y.name??"",arguments:k})}for(let[g,y]of c){if(!g||i.has(g))continue;let k=y.args.join("");!y.name&&!k||(yield{type:"function_call",call_id:g,name:y.name??"",arguments:k})}}return Array.from(n())},K1=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(r=>{let s=r.response_metadata;if(s?.output_version==="v1")return TV(r);let a=r.additional_kwargs,i=iu(r);if(i==="system"&&au(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let o=r;if(a?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"input_image",image_url:o.content};if(Array.isArray(o.content)){let u=o.content.find(p=>p.type==="input_image");if(u)return u;let l=o.content.find(p=>p.type==="computer_screenshot");if(l)return l;let d=o.content.find(p=>p.type==="image_url");if(d)return{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id};if(o.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:o.tool_call_id,output:o.content};let c=Array.isArray(o.content)&&o.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:o.tool_call_id,id:o.id?.startsWith("fc_")?o.id:void 0,output:c?o.content:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(i==="assistant"){if(!t&&s?.output!=null&&Array.isArray(s?.output)&&s?.output.length>0&&s?.output.every(f=>"type"in f))return s?.output;let o=[],c=a?.reasoning,u=!!c?.encrypted_content;if(c&&(!t||u)){let f=OV(c);o.push(f)}let{content:l}=r;a?.refusal&&(typeof l=="string"&&(l=[{type:"output_text",text:l,annotations:[]}]),l=[...l,{type:"refusal",refusal:a.refusal}]),(typeof l=="string"||l.length>0)&&o.push({type:"message",role:"assistant",...r.id&&!t&&r.id.startsWith("msg_")?{id:r.id}:{},content:da(()=>typeof l=="string"?l:l.flatMap(f=>{if(f.type==="text"){let m=f;return{type:"output_text",text:m.text,annotations:(m.annotations??[]).map(xV)}}return f.type==="output_text"||f.type==="refusal"?f:[]}))});let d=a?.[gp];Ke.isInstance(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(f=>BF(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:FF(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...t?{}:{id:d?.[f.id]}})):a?.tool_calls&&o.push(...a.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...t?{}:{id:d?.[f.id]}})));let p=s?.output?.length?s?.output:a.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(p!=null){let f=p?.filter(m=>h.includes(m.type));f.length>0&&o.push(...f)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof r.content=="string")return{type:"message",role:i,content:r.content};let o=[],c=r.content.flatMap(u=>(u.type==="mcp_approval_response"&&o.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Sr(u)?yy(u,SE):u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:da(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:da(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]));return c.length>0&&o.push({type:"message",role:i,content:c}),o}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]}),IV=class extends t0{constructor(e,t){super(e0(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:zF(e?.tool_choice)?e?.tool_choice:(()=>{let s=AI(e?.tool_choice);if(typeof s=="object"&&"type"in s){if(s.type==="function")return{type:"function",name:s.function.name};if(s.type==="allowed_tools")return{type:"allowed_tools",mode:s.allowed_tools.mode,tools:s.allowed_tools.tools};if(s.type==="custom")return{type:"custom",name:s.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let s=this._getResponseFormat(e?.response_format);return s?.type==="json_schema"?s.json_schema.schema!=null?{format:{type:"json_schema",schema:s.json_schema.schema,description:s.json_schema.description,name:s.json_schema.name,strict:s.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:s,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let s=this._streamResponseChunks(e,t,n),a;for await(let i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=a?.concat(i)??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:a?.message?.usage_metadata}}}else{let s=await this.completionWithRetry({input:K1({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:s.output_text,message:EE(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:K1({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let s of r){if(t.signal?.aborted)return;let a=SV(s);a!=null&&(yield a,await n?.handleLLMNewToken(a.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(r){throw Z_(r)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(q_(r))r.type==="image_generation"&&t?.stream&&(r.partial_images=1),n.push(r);else if(ap(r)){let s=r.metadata.customTool;n.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(r_(r)){let s={};for(let[a,i]of Object.entries(r))a!=="type"&&a!=="function"&&(s[a]=i);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...s})}else $I(r)&&n.push(ZF(r));return n}},EV=class AE extends t0{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(t,n){let r=e0(t,n);super(r),this.fields=r,this.useResponsesApi=r?.useResponsesApi??!1,this.responses=r?.responses??new IV(r),this.completions=r?.completions??new kV(r)}_useResponsesApi(t){let n=t?.tools?.some(q_),r=t?.previous_response_id!=null||t?.text!=null||t?.truncation!=null||t?.include!=null||t?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=t?.tools?.some($I)||t?.tools?.some(ap);return this.useResponsesApi||n||r||s||AF(this.model)}getLsParams(t){let n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(t){let n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(t,n,r){return this._useResponsesApi(n)?this.responses._generate(t,n,r):this.completions._generate(t,n,r)}async*_streamResponseChunks(t,n,r){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(n),r);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(n),r)}withConfig(t){let n=new AE(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},AV=Vt({type:$n("screenshot")}),$V=Vt({type:$n("click"),x:Ft(),y:Ft(),button:Q_(["left","right","wheel","back","forward"]).default("left")}),CV=Vt({type:$n("double_click"),x:Ft(),y:Ft(),button:Q_(["left","right","wheel","back","forward"]).default("left")}),NV=Vt({type:$n("drag"),path:ou(Vt({x:Ft(),y:Ft()}))}),PV=Vt({type:$n("keypress"),keys:ou(In())}),jV=Vt({type:$n("move"),x:Ft(),y:Ft()}),RV=Vt({type:$n("scroll"),x:Ft(),y:Ft(),scroll_x:Ft(),scroll_y:Ft()}),MV=Vt({type:$n("type"),text:In()}),LV=Vt({type:$n("wait"),duration:Ft().optional()}),zV=th([AV,$V,CV,NV,PV,jV,RV,MV,LV]);Vt({action:zV});var UV=Vt({type:$n("exec"),command:ou(In()),env:eq(In(),In()).optional(),working_directory:In().optional(),timeout_ms:Ft().optional(),user:In().optional()});th([UV]);Vt({commands:ou(In()).describe("Array of shell commands to execute"),timeout_ms:Ft().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Ft().optional().describe("Optional maximum number of characters to return from each command")});var DV=Vt({type:$n("create_file"),path:In(),diff:In()}),FV=Vt({type:$n("update_file"),path:In(),diff:In()}),BV=Vt({type:$n("delete_file"),path:In()});th([DV,FV,BV]);var $E={advanced:"gpt-5.2",default:"gpt-5-mini"},ZV={default:"text-embedding-ada-002"},Xf=new Map,Gu=null,qV=()=>{let e=Q1.getDefault().helperServices;if(!e?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return e.aiModels.url},VV=async e=>{let t=qV();Xf.size===0&&(Gu||(Gu=(async()=>{try{let r=await fetch(`${t}/models`);if(!r.ok)throw new Error("Failed to fetch AI service discovery data.");(await r.json()).models.forEach(s=>Xf.set(s.name,s))}catch(r){throw Gu=null,r}})()),await Gu);let n=Xf.get(e);if(!n)throw new Error(`Model '${e}' is not available in the discovery service.`);return n.endpoint},HV=async(e="default")=>await VV($E[e]),X1=(e,t)=>t;gt.Root({userInput:gt(),messages:gt({reducer:Ra,default:()=>[]}),pendingIntents:gt({default:()=>[],reducer:X1}),currentIntent:gt({default:()=>"none",reducer:X1})});var Qi=async(e,t)=>{await O3("trace_message",e,t)},WV=e=>async(t,n)=>{let r=new Headers(n?.headers);return r.delete("Authorization"),r.delete("api-key"),e&&e.length>0&&(r.set("X-Esri-Authorization",`Bearer ${e}`),r.set("X-Esri-Request-Source","MapsSDK")),await fetch(t,{...n,headers:r})},JV=async(e="default",t=0)=>{let n=Q1.getDefault(),r=await DE.getCredential(`${n.url}/sharing`),s=$E[e],a=await HV(e);return new EV({modelName:s,apiKey:"dummy-key",...e!=="default"&&{temperature:t},configuration:{baseURL:a,fetch:WV(r.token)}})},GV=(e,t)=>{let n=f_.fromTemplate(e);return Bp.fromMessages([n,...t])},CE=async e=>{let{promptText:t,modelTier:n="default",temperature:r=0,messages:s,inputVariables:a,schema:i}=e,o=GV(t,s??[]),c=(await JV(n,r)).withStructuredOutput(i);return await o.pipe(c).invoke(a??{})},KV=os({id:un().min(1),name:un().min(1),description:un().min(1)});ui(KV);var XV="0.1",yo=1536,YV="openai",QV=ZV.default,e7=`Name: {name}
343
+ ]`;continue}a+=s[u],s[u]==="\\"?i=!0:o&&s[u]==="]"?o=!1:!o&&s[u]==="["&&(o=!0)}try{let u=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function OE(e,t){if(t.target==="openApi3"&&e.keyType?._def.typeName===ke.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===ke.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(xE(e.keyType._def,t)).reduce((s,[a,i])=>a==="type"?s:{...s,[a]:i},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===ke.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function zq(e,t){if(t.mapStrategy==="record")return OE(e,t);let n=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},r=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Uq(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),r=Array.from(new Set(n.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function Dq(){return{not:{}}}function Fq(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var mp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Bq(e,t){if(t.target==="openApi3")return W1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in mp&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,a)=>{let i=mp[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];default:return s}},[]);if(r.length===n.length){let s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return W1(e,t)}var W1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Be(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Zq(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"||t.nullableStrategy==="property"?{type:mp[e.innerType._def.typeName],nullable:!0}:{type:[mp[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function qq(e,t){let n={type:"number"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"int":n.type="integer",bE(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?He(n,"minimum",r.value,r.message,t):He(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),He(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?He(n,"maximum",r.value,r.message,t):He(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),He(n,"maximum",r.value,r.message,t));break;case"multipleOf":He(n,"multipleOf",r.value,r.message,t);break}return n}function Vq(e,t){return t.removeAdditionalStrategy==="strict"?e.catchall._def.typeName==="ZodNever"?e.unknownKeys!=="strict":Be(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:e.catchall._def.typeName==="ZodNever"?e.unknownKeys==="passthrough":Be(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function Hq(e,t){let n={type:"object",...Object.entries(e.shape()).reduce((r,[s,a])=>{if(a===void 0||a._def===void 0)return r;let i=[...t.currentPath,"properties",s],o=Be(a._def,{...t,currentPath:i,propertyPath:i});if(o===void 0)return r;if(t.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[s]:o},required:a.isOptional()&&!t.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:Vq(e,t)};return n.required.length||delete n.required,n}var Wq=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return Be(e.innerType._def,{...t,currentPath:t.currentPath});let n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Jq=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);if(t.pipeStrategy==="output")return Be(e.out._def,t);let n=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function Gq(e,t){return Be(e.type._def,t)}function Kq(e,t){let n={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&He(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&He(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Xq(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Be(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Be(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Yq(){return{not:{}}}function Qq(){return{}}var eV=(e,t)=>Be(e.innerType._def,t);function Be(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==wq)return i}if(r&&!n){let i=tV(r,t);if(i!==void 0)return"$ref"in i&&t.seenRefs.add(i.$ref),i}let s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);let a=rV(e,e.typeName,t,n);return a&&sV(e,t,a),s.jsonSchema=a,a}var tV=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":let n=e.path.slice(t.basePath.length+1).join("_");return n!==t.name&&t.nameStrategy==="duplicate-ref"&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join("/")};case"relative":return{$ref:nV(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,s)=>t.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},nV=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},rV=(e,t,n,r)=>{switch(t){case ke.ZodString:return xE(e,n);case ke.ZodNumber:return qq(e,n);case ke.ZodObject:return Hq(e,n);case ke.ZodBigInt:return Tq(e,n);case ke.ZodBoolean:return Iq();case ke.ZodDate:return kE(e,n);case ke.ZodUndefined:return Yq();case ke.ZodNull:return Fq(n);case ke.ZodArray:return Sq(e,n);case ke.ZodUnion:case ke.ZodDiscriminatedUnion:return Bq(e,n);case ke.ZodIntersection:return Rq(e,n);case ke.ZodTuple:return Xq(e,n);case ke.ZodRecord:return OE(e,n);case ke.ZodLiteral:return Mq(e,n);case ke.ZodEnum:return Pq(e);case ke.ZodNativeEnum:return Uq(e);case ke.ZodNullable:return Zq(e,n);case ke.ZodOptional:return Wq(e,n);case ke.ZodMap:return zq(e,n);case ke.ZodSet:return Kq(e,n);case ke.ZodLazy:return Be(e.getter()._def,n);case ke.ZodPromise:return Gq(e,n);case ke.ZodNaN:case ke.ZodNever:return Dq();case ke.ZodEffects:return Nq(e,n,r);case ke.ZodAny:return Oq();case ke.ZodUnknown:return Qq();case ke.ZodDefault:return Cq(e,n);case ke.ZodBranded:return Eq(e,n);case ke.ZodReadonly:return eV(e,n);case ke.ZodCatch:return Aq(e,n);case ke.ZodPipeline:return Jq(e,n);case ke.ZodFunction:case ke.ZodVoid:case ke.ZodSymbol:return;default:return(s=>{})()}},sV=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),aV=(e,t)=>{let n=xq(t),r=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Be(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a);let i=(()=>{if(kq(n.definitions))return;let c={},u=new Set;for(let l=0;l<500;l++){let d=Object.entries(n.definitions).filter(([p])=>!u.has(p));if(d.length===0)break;for(let[p,h]of d)c[p]=Be(sy(h),{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0)??{},u.add(p)}return c})(),o=r===void 0?i?{...s,[n.definitionPath]:i}:s:n.nameStrategy==="duplicate-ref"?{...s,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:s}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function iV(e){if(e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);let t=structuredClone(e);return Rr(t,[],t)}function ay(e){if(typeof e=="boolean")return!1;if(e.type==="null")return!0;for(let t of e.oneOf??[])if(ay(t))return!0;for(let t of e.anyOf??[])if(ay(t))return!0;return!1}function Rr(e,t,n){if(typeof e=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${t.join("/")}`);if(!Js(e))throw new TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join("/")}`);let r=e.$defs;if(Js(r))for(let[d,p]of Object.entries(r))Rr(p,[...t,"$defs",d],n);let s=e.definitions;if(Js(s))for(let[d,p]of Object.entries(s))Rr(p,[...t,"definitions",d],n);e.type==="object"&&!("additionalProperties"in e)&&(e.additionalProperties=!1);let a=e.required??[],i=e.properties;if(Js(i)){for(let[d,p]of Object.entries(i))if(!ay(p)&&!a.includes(d))throw new Error(`Zod field at \`${[...t,"properties",d].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(i),e.properties=Object.fromEntries(Object.entries(i).map(([d,p])=>[d,Rr(p,[...t,"properties",d],n)]))}let o=e.items;Js(o)&&(e.items=Rr(o,[...t,"items"],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((d,p)=>Rr(d,[...t,"anyOf",String(p)],n)));let u=e.allOf;if(Array.isArray(u))if(u.length===1){let d=Rr(u[0],[...t,"allOf","0"],n);Object.assign(e,d),delete e.allOf}else e.allOf=u.map((d,p)=>Rr(d,[...t,"allOf",String(p)],n));e.default===null&&delete e.default;let l=e.$ref;if(l&&cV(e,1)){if(typeof l!="string")throw new TypeError(`Received non-string $ref - ${l}; path=${t.join("/")}`);let d=oV(n,l);if(typeof d=="boolean")throw new Error(`Expected \`$ref: ${l}\` to resolve to an object schema but got boolean`);if(!Js(d))throw new Error(`Expected \`$ref: ${l}\` to resolve to an object but got ${JSON.stringify(d)}`);return Object.assign(e,{...d,...e}),delete e.$ref,Rr(e,t,n)}return e}function oV(e,t){if(!t.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split("/"),r=e;for(let s of n){if(!Js(r))throw new Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let a=r[s];if(a===void 0)throw new Error(`Key ${s} not found while resolving ${t}`);r=a}return r}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cV(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function uV(e,t){return aV(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function lV(e){return iV(s8(e,{target:"draft-7"}))}function dV(e){return"_zod"in e}function pV(e,t,n){return aF({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:dV(e)?lV(e):uV(e,{name:t})}},r=>e.parse(JSON.parse(r)))}var J1=["jsonSchema","functionCalling","jsonMode"];function hV(e,t){if(typeof t<"u"&&!J1.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${J1.join(", ")}`);let n=!e.startsWith("gpt-3")&&!e.startsWith("gpt-4-")&&e!=="gpt-4";if(n&&!t)return"jsonSchema";if(!n&&t==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??"functionCalling"}function fV(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function mV(e,t,n){if(gt(e))return pV(e,t,n);if(nt(e))return fV({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:It(e,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=t}})}},r=>i6(e,JSON.parse(r)));throw new Error("Unsupported schema response format")}function gV(e,t){if(t&&typeof t=="object"&&"images"in t&&Array.isArray(t.images)){let n=t.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:e},...n]}return e}var yV={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function e0(e,t){return typeof e=="string"?{model:e,...t??{}}:e??t}var t0=class extends Pa{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??rr("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??rr("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.3.0")}_getReasoningParams(e){if(!au(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&En(e.json_schema.schema)?mV(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let t=$F({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=PF(n.defaultHeaders),this.client=new be(n)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return ap(e)?qF(e.metadata.customTool):r_(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:jF(e,t)}bindTools(e,t){let n;return t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:e.map(r=>{if(q_(r)||ap(r))return r;if(LF(r))return r.extras.providerToolDefinition;let s=this._convertChatOpenAIToolToCompletionsTool(r,{strict:n});return tu(r)&&r.extras?.defer_loading===!0?{...s,defer_loading:!0}:s}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,n)=>(n&&n.tokenUsage&&(t.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model==="gpt-3.5-turbo-0301"?(n=4,r=-1):(n=3,r=1);let s=await Promise.all(e.map(async a=>{let[i,o]=await Promise.all([this.getNumTokens(a.content),this.getNumTokens(iu(a))]),c=a.name!==void 0?r+await this.getNumTokens(a.name):0,u=i+n+o+c,l=a;if(l._getType()==="function"&&(u-=2),l.additional_kwargs?.function_call&&(u+=3),l?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(d){console.error("Error parsing function arguments",d,JSON.stringify(l.additional_kwargs.function_call)),u+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=u,u}));return t+=3,{totalCount:t,countPerMessage:s}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async t=>t.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([t.message])).countPerMessage[0]:await this.getNumTokens(t.message.content)))).reduce((t,n)=>t+n,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!=="auto"){let s=MF(t);r+=await this.getNumTokens(s),r+=9}return t&&e.find(s=>s._getType()==="system")&&(r-=4),n==="none"?r+=1:typeof n=="object"&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(s){throw Z_(s)}})}get profile(){return yV[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:s,name:a,includeRaw:i}={...t,schema:e};if(t?.strict!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let o=hV(this.model,t?.method);if(o==="jsonMode"){r=og(s);let c=It(s);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...c}}})}else if(o==="jsonSchema"){let c=It(s),u={name:a??"extract",description:Ti(c),schema:En(s)?s:c,strict:t?.strict};if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...c}}}),En(s)||ha(s)){let l=og(s);r=lr.from(async d=>"parsed"in d.additional_kwargs?d.additional_kwargs.parsed:l.invoke(d.content))}else r=new i_}else{let c=a??"extract",u=It(s),l;En(s)||ha(s)?l={name:c,description:u.description,parameters:u}:typeof s.name=="string"&&typeof s.parameters=="object"&&s.parameters!=null?(l=s,c=s.name):(c=s.title??c,l={name:c,description:s.description??"",parameters:s}),n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:l}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...t?.strict!==void 0?{strict:t.strict}:{}}),r=FO(s,c)}return c_(n,r,i)}},SE={providerName:"ChatOpenAI",fromStandardTextBlock(e){return{type:"text",text:e.text}},fromStandardImageBlock(e){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type==="base64")return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type==="url"){let t=Ko({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||"",r;try{r=om(n)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:t.data}}}if(e.source_type==="base64"){let t;try{t=om(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!=="audio"||t.subtype!=="wav"&&t.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type==="url"){let t=Ko({dataUrl:e.url}),n=rp(e);if(!t)throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:n}:{}}}}if(e.source_type==="base64"){let t=rp(e);return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:t}:{}}}}if(e.source_type==="id")return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},_V=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls;switch(e.role){case"assistant":{let s=[],a=[];for(let c of r??[])try{s.push(Dp(c,{returnId:!0}))}catch(u){a.push(Zo(c,u.message))}let i={function_call:e.function_call,tool_calls:r};n!==void 0&&(i.__raw_response=t);let o={model_provider:"openai",model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(i.audio=e.audio),new Ke({content:gV(e.content||"",t.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:t.id})}default:return new Kr(e.content||"",e.role??"unknown")}},vV=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let s=e.role??r,a=e.content??"",i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},n&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});let o={model_provider:"openai",usage:{...t.usage}};if(s==="user")return new qc({content:a,response_metadata:o});if(s==="assistant"){let c=[];if(Array.isArray(e.tool_calls))for(let u of e.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new mn({content:a,tool_call_chunks:c,additional_kwargs:i,id:t.id,response_metadata:o})}else return s==="system"?new ws({content:a,response_metadata:o}):s==="developer"?new ws({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new Zc({content:a,additional_kwargs:i,name:e.name,response_metadata:o}):s==="tool"?new Fc({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new Bc({content:a,role:s,response_metadata:o})},wV=e=>{if(e.type==="image"){if(e.url)return{type:"image_url",image_url:{url:e.url}};if(e.data)return{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type==="audio"&&e.data){let t=jk(()=>{let[,n]=e.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:e.data.toString(),format:t}}}if(e.type==="file"){if(e.data){let t=rp(e);return{type:"file",file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:"file",file:{file_id:e.fileId}}}},bV=({message:e,model:t})=>{let n=iu(e);if(n==="system"&&au(t)&&(n="developer"),n==="developer")return{role:"developer",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="system")return{role:"system",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="assistant")return{role:"assistant",content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="tool"&&Mn.isInstance(e))return{role:"tool",tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(s=>s.type==="text")};if(n==="function")return{role:"function",name:e.name??"",content:e.contentBlocks.filter(s=>s.type==="text").join("")};function*r(s){for(let a of s){a.type==="text"&&(yield{type:"text",text:a.text});let i=wV(a);i&&(yield i)}}return{role:"user",content:Array.from(r(e.contentBlocks))}},G1=({messages:e,model:t})=>e.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return bV({message:n});let r=iu(n);r==="system"&&au(t)&&(r="developer");let s=typeof n.content=="string"?n.content:n.content.flatMap(i=>Sr(i)?yy(i,SE):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),a={role:r,content:s};return n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call),Ke.isInstance(n)&&n.tool_calls?.length?a.tool_calls=n.tool_calls.map(zO):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Mn.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[a,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:a}),kV=class extends t0{constructor(e,t){super(e0(e,t))}invocationParams(e,t){let n;e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};e?.stream_options!==void 0?r={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}});let s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:n})):void 0,tool_choice:AI(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(s.prediction=e.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),e?.service_tier!==void 0&&(s.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(s.reasoning_effort=a.effort),au(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},s=this.invocationParams(t),a=G1({messages:e,model:this.model});if(s.stream){let i=this._streamResponseChunks(e,t,n),o={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let f=h.generationInfo?.completion??0;o[f]===void 0?o[f]=h:o[f]=o[f].concat(h)}let c=Object.entries(o).sort(([h],[f])=>parseInt(h,10)-parseInt(f,10)).map(([h,f])=>f),{functions:u,function_call:l}=this.invocationParams(t),d=await this._getEstimatedTokenCountFromPrompt(e,u,l),p=await this._getNumTokensFromGenerations(c);return r.input_tokens=d,r.output_tokens=p,r.total_tokens=d+p,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let i=await this.completionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:o,prompt_tokens:c,total_tokens:u,prompt_tokens_details:l,completion_tokens_details:d}=i?.usage??{};o&&(r.output_tokens=(r.output_tokens??0)+o),c&&(r.input_tokens=(r.input_tokens??0)+c),u&&(r.total_tokens=(r.total_tokens??0)+u),(l?.audio_tokens!==null||l?.cached_tokens!==null)&&(r.input_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.cached_tokens!==null&&{cache_read:l?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(r.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let p=[];for(let h of i?.choices??[]){let f={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};f.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},kp(f.message)&&(f.message.usage_metadata=r),f.message=new Ke(Object.fromEntries(Object.entries(f.message).filter(([m])=>!m.startsWith("lc_")))),p.push(f)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(e,t,n){let r=G1({messages:e,model:this.model}),s={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,i=await this.completionWithRetry(s,t),o;for await(let c of i){if(t.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(o=c.usage),!u)continue;let{delta:l}=u;if(!l)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(l,c,a);a=l.role??a;let p={prompt:t.promptIndex??0,completion:u.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={...p};u.finish_reason!=null&&(h.finish_reason=u.finish_reason,h.system_fingerprint=c.system_fingerprint,h.model_name=c.model,h.service_tier=c.service_tier),this.logprobs&&(h.logprobs=u.logprobs);let f=new Wr({message:d,text:d.content,generationInfo:h});yield f,await n?.handleLLMNewToken(f.text??"",p,void 0,void 0,void 0,{chunk:f})}if(o){let c={...o.prompt_tokens_details?.audio_tokens!==null&&{audio:o.prompt_tokens_details?.audio_tokens},...o.prompt_tokens_details?.cached_tokens!==null&&{cache_read:o.prompt_tokens_details?.cached_tokens}},u={...o.completion_tokens_details?.audio_tokens!==null&&{audio:o.completion_tokens_details?.audio_tokens},...o.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},l=new Wr({message:new mn({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield l,await n?.handleLLMNewToken(l.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:l})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(s){throw Z_(s)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return vV({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return _V({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},gp="__openai_function_call_ids__";function TE(e){return e.type==="url_citation"?{type:"citation",source:"url_citation",url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type==="file_citation"?{type:"citation",source:"file_citation",title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type==="file_path"?{type:"citation",source:"file_path",startIndex:e.index,file_id:e.file_id}:{type:"non_standard",value:e}}function xV(e){if(e.type==="url_citation"||e.type==="file_citation"||e.type==="container_file_citation"||e.type==="file_path")return e;if(e.type==="citation"){let t=e;if(t.source==="url_citation")return{type:"url_citation",url:t.url??"",title:t.title??"",start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source==="file_citation")return{type:"file_citation",file_id:t.file_id??"",filename:t.title??"",index:t.startIndex??0};if(t.source==="container_file_citation")return{type:"container_file_citation",file_id:t.file_id??"",filename:t.title??"",container_id:t.container_id??"",start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source==="file_path")return{type:"file_path",file_id:t.file_id??"",index:t.startIndex??0}}return e.type==="non_standard"?e.value:e}var IE=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},EE=e=>{if(e.error){let c=new Error(e.error.message);throw c.name=e.error.code,c}let t,n=[],r=[],s=[],a=e.output.map(c=>{if(c.type==="function_call"&&"parsed_arguments"in c){let u={...c};return delete u.parsed_arguments,u}return c}),i={model_provider:"openai",model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:a,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let c of e.output)if(c.type==="message")t=c.id,n.push(...c.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(o.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(TE)}):u.type==="refusal"?(o.refusal=u.refusal,[]):u));else if(c.type==="function_call"){let u={function:{name:c.name,arguments:c.arguments},id:c.call_id};try{r.push(Dp(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),s.push(Zo(u,d))}o[gp]??={},c.id&&(o[gp][c.call_id]=c.id)}else if(c.type==="reasoning"){o.reasoning=c;let u=c.summary?.map(l=>l.text).filter(Boolean).join("");u&&n.push({type:"reasoning",reasoning:u})}else if(c.type==="custom_tool_call"){let u=UF(c);u?r.push(u):s.push(Zo(c,"Malformed custom tool call"))}else if(c.type==="computer_call"){let u=DF(c);u?r.push(u):s.push(Zo(c,"Malformed computer call"))}else c.type==="image_generation_call"?(c.result&&n.push({type:"image",mimeType:"image/png",data:c.result,id:c.id,metadata:{status:c.status}}),o.tool_outputs??=[],o.tool_outputs.push(c)):(o.tool_outputs??=[],o.tool_outputs.push(c));return new Ke({id:t,content:n,tool_calls:r,invalid_tool_calls:s,usage_metadata:IE(e.usage),additional_kwargs:o,response_metadata:i})},OV=e=>{let t=(e.summary.length>1?e.summary.reduce((n,r)=>{let s=n[n.length-1];return s.index===r.index?s.text+=r.text:n.push(r),n},[{...e.summary[0]}]):e.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...e,summary:t}},SV=e=>{let t=[],n={},r,s=[],a={model_provider:"openai"},i={},o;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[TE(e.annotation)],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")o=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),i[gp]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&e.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),i.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&e.item.type==="image_generation_call")e.item.result&&t.push({type:"image",mimeType:"image/png",data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),i.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(e.item.type))i.tool_outputs=[e.item];else if(e.type==="response.created")a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type==="response.completed"){let c=EE(e.response);r=IE(e.response.usage),e.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(let[u,l]of Object.entries(e.response))u!=="id"&&(u==="output"?a[u]=c.response_metadata.output:a[u]=l)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")i.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){let c=e.item.summary?e.item.summary.map((l,d)=>({...l,index:d})):void 0;i.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}};let u=e.item.summary?.map(l=>l.text).filter(Boolean).join("");u&&t.push({type:"reasoning",reasoning:u})}else if(e.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:"reasoning",reasoning:e.part.text});else if(e.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]},e.delta&&t.push({type:"reasoning",reasoning:e.delta});else return e.type,null;return new Wr({text:t.map(c=>c.text).join(""),message:new mn({id:o,content:t,tool_call_chunks:s,usage_metadata:r,additional_kwargs:i,response_metadata:a}),generationInfo:n})},TV=e=>{let t=Ke.isInstance(e)&&e.response_metadata?.model_provider==="openai";function*n(){let r=da(()=>{try{let g=iu(e);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),s,a=new Set,i=new Set,o=new Map,c=new Map;function*u(){if(!s)return;let g=s.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield s),s=void 0}let l=g=>{s||(s={type:"message",role:r,content:[]}),typeof s.content=="string"?s.content=s.content.length>0?[{type:"input_text",text:s.content},...g]:[...g]:s.content.push(...g)},d=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},p=g=>{let y=da(()=>{let k=g.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(g.fileId)return{type:"input_image",detail:y,file_id:g.fileId};if(g.url)return{type:"input_image",detail:y,image_url:g.url};if(g.data){let k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:y,image_url:`data:${g.mimeType??"image/png"};base64,${k}`}}},h=g=>{if(g.fileId){let y=_1(g);return{type:"input_file",file_id:g.fileId,...y?{filename:y}:{}}}if(g.url){let y=_1(g);return{...y?{filename:y}:{},type:"input_file",file_url:g.url}}if(g.data){let y=rp(g),k=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${k}`,...y?{filename:y}:{}}}},f=g=>{let y=da(()=>{if(Array.isArray(g.summary)){let S=g.summary?.map(E=>E?.text).filter(E=>typeof E=="string")??[];if(S.length>0)return S}return g.reasoning?[g.reasoning]:[]}),k=y.length>0?y.map(S=>({type:"summary_text",text:S})):[{type:"summary_text",text:""}],x={type:"reasoning",id:g.id??"",summary:k};return g.reasoning&&(x.content=[{type:"reasoning_text",text:g.reasoning}]),x},m=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:d(g.args)}),v=g=>{let y=d(g.output),k=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:y,...k?{status:k}:{}}};for(let g of e.contentBlocks)if(g.type==="text")l([{type:"input_text",text:g.text}]);else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*u(),yield f(g);else if(g.type==="tool_call"){yield*u();let y=g.id??"";y&&(a.add(y),o.delete(y)),yield m(g)}else if(g.type==="tool_call_chunk"){if(g.id){let y=o.get(g.id)??{name:g.name,args:[]};g.name&&(y.name=g.name),g.args&&y.args.push(g.args),o.set(g.id,y)}}else if(g.type==="server_tool_call"){yield*u();let y=g.id??"";y&&(i.add(y),c.delete(y)),yield m(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let y=c.get(g.id)??{name:g.name,args:[]};g.name&&(y.name=g.name),g.args&&y.args.push(g.args),c.set(g.id,y)}}else if(g.type==="server_tool_call_result")yield*u(),yield v(g);else if(g.type!=="audio")if(g.type==="file"){let y=h(g);y&&l([y])}else if(g.type==="image"){let y=p(g);y&&l([y])}else if(g.type==="video"){let y=h(g);y&&l([y])}else g.type==="text-plain"?g.text&&l([{type:"input_text",text:g.text}]):g.type==="non_standard"&&t&&(yield*u(),yield g.value)}yield*u();for(let[g,y]of o){if(!g||a.has(g))continue;let k=y.args.join("");!y.name&&!k||(yield{type:"function_call",call_id:g,name:y.name??"",arguments:k})}for(let[g,y]of c){if(!g||i.has(g))continue;let k=y.args.join("");!y.name&&!k||(yield{type:"function_call",call_id:g,name:y.name??"",arguments:k})}}return Array.from(n())},K1=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(r=>{let s=r.response_metadata;if(s?.output_version==="v1")return TV(r);let a=r.additional_kwargs,i=iu(r);if(i==="system"&&au(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let o=r;if(a?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"input_image",image_url:o.content};if(Array.isArray(o.content)){let u=o.content.find(p=>p.type==="input_image");if(u)return u;let l=o.content.find(p=>p.type==="computer_screenshot");if(l)return l;let d=o.content.find(p=>p.type==="image_url");if(d)return{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id};if(o.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:o.tool_call_id,output:o.content};let c=Array.isArray(o.content)&&o.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:o.tool_call_id,id:o.id?.startsWith("fc_")?o.id:void 0,output:c?o.content:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(i==="assistant"){if(!t&&s?.output!=null&&Array.isArray(s?.output)&&s?.output.length>0&&s?.output.every(f=>"type"in f))return s?.output;let o=[],c=a?.reasoning,u=!!c?.encrypted_content;if(c&&(!t||u)){let f=OV(c);o.push(f)}let{content:l}=r;a?.refusal&&(typeof l=="string"&&(l=[{type:"output_text",text:l,annotations:[]}]),l=[...l,{type:"refusal",refusal:a.refusal}]),(typeof l=="string"||l.length>0)&&o.push({type:"message",role:"assistant",...r.id&&!t&&r.id.startsWith("msg_")?{id:r.id}:{},content:da(()=>typeof l=="string"?l:l.flatMap(f=>{if(f.type==="text"){let m=f;return{type:"output_text",text:m.text,annotations:(m.annotations??[]).map(xV)}}return f.type==="output_text"||f.type==="refusal"?f:[]}))});let d=a?.[gp];Ke.isInstance(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(f=>BF(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:FF(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...t?{}:{id:d?.[f.id]}})):a?.tool_calls&&o.push(...a.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...t?{}:{id:d?.[f.id]}})));let p=s?.output?.length?s?.output:a.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(p!=null){let f=p?.filter(m=>h.includes(m.type));f.length>0&&o.push(...f)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof r.content=="string")return{type:"message",role:i,content:r.content};let o=[],c=r.content.flatMap(u=>(u.type==="mcp_approval_response"&&o.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Sr(u)?yy(u,SE):u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:da(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:da(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]));return c.length>0&&o.push({type:"message",role:i,content:c}),o}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]}),IV=class extends t0{constructor(e,t){super(e0(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:zF(e?.tool_choice)?e?.tool_choice:(()=>{let s=AI(e?.tool_choice);if(typeof s=="object"&&"type"in s){if(s.type==="function")return{type:"function",name:s.function.name};if(s.type==="allowed_tools")return{type:"allowed_tools",mode:s.allowed_tools.mode,tools:s.allowed_tools.tools};if(s.type==="custom")return{type:"custom",name:s.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let s=this._getResponseFormat(e?.response_format);return s?.type==="json_schema"?s.json_schema.schema!=null?{format:{type:"json_schema",schema:s.json_schema.schema,description:s.json_schema.description,name:s.json_schema.name,strict:s.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:s,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let s=this._streamResponseChunks(e,t,n),a;for await(let i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=a?.concat(i)??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:a?.message?.usage_metadata}}}else{let s=await this.completionWithRetry({input:K1({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:s.output_text,message:EE(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:K1({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let s of r){if(t.signal?.aborted)return;let a=SV(s);a!=null&&(yield a,await n?.handleLLMNewToken(a.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(r){throw Z_(r)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(q_(r))r.type==="image_generation"&&t?.stream&&(r.partial_images=1),n.push(r);else if(ap(r)){let s=r.metadata.customTool;n.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(r_(r)){let s={};for(let[a,i]of Object.entries(r))a!=="type"&&a!=="function"&&(s[a]=i);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...s})}else $I(r)&&n.push(ZF(r));return n}},EV=class AE extends t0{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(t,n){let r=e0(t,n);super(r),this.fields=r,this.useResponsesApi=r?.useResponsesApi??!1,this.responses=r?.responses??new IV(r),this.completions=r?.completions??new kV(r)}_useResponsesApi(t){let n=t?.tools?.some(q_),r=t?.previous_response_id!=null||t?.text!=null||t?.truncation!=null||t?.include!=null||t?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=t?.tools?.some($I)||t?.tools?.some(ap);return this.useResponsesApi||n||r||s||AF(this.model)}getLsParams(t){let n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(t){let n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(t,n,r){return this._useResponsesApi(n)?this.responses._generate(t,n,r):this.completions._generate(t,n,r)}async*_streamResponseChunks(t,n,r){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(n),r);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(n),r)}withConfig(t){let n=new AE(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},AV=Vt({type:$n("screenshot")}),$V=Vt({type:$n("click"),x:Ft(),y:Ft(),button:Q_(["left","right","wheel","back","forward"]).default("left")}),CV=Vt({type:$n("double_click"),x:Ft(),y:Ft(),button:Q_(["left","right","wheel","back","forward"]).default("left")}),NV=Vt({type:$n("drag"),path:ou(Vt({x:Ft(),y:Ft()}))}),PV=Vt({type:$n("keypress"),keys:ou(In())}),jV=Vt({type:$n("move"),x:Ft(),y:Ft()}),RV=Vt({type:$n("scroll"),x:Ft(),y:Ft(),scroll_x:Ft(),scroll_y:Ft()}),MV=Vt({type:$n("type"),text:In()}),LV=Vt({type:$n("wait"),duration:Ft().optional()}),zV=th([AV,$V,CV,NV,PV,jV,RV,MV,LV]);Vt({action:zV});var UV=Vt({type:$n("exec"),command:ou(In()),env:eq(In(),In()).optional(),working_directory:In().optional(),timeout_ms:Ft().optional(),user:In().optional()});th([UV]);Vt({commands:ou(In()).describe("Array of shell commands to execute"),timeout_ms:Ft().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Ft().optional().describe("Optional maximum number of characters to return from each command")});var DV=Vt({type:$n("create_file"),path:In(),diff:In()}),FV=Vt({type:$n("update_file"),path:In(),diff:In()}),BV=Vt({type:$n("delete_file"),path:In()});th([DV,FV,BV]);var $E={advanced:"gpt-5.2",default:"gpt-5-mini"},ZV={default:"text-embedding-ada-002"},Xf=new Map,Gu=null,qV=()=>{let e=Q1.getDefault().helperServices;if(!e?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return e.aiModels.url},VV=async e=>{let t=qV();Xf.size===0&&(Gu||(Gu=(async()=>{try{let r=await fetch(`${t}/models`);if(!r.ok)throw new Error("Failed to fetch AI service discovery data.");(await r.json()).models.forEach(s=>Xf.set(s.name,s))}catch(r){throw Gu=null,r}})()),await Gu);let n=Xf.get(e);if(!n)throw new Error(`Model '${e}' is not available in the discovery service.`);return n.endpoint},HV=async(e="default")=>await VV($E[e]),X1=(e,t)=>t;mt.Root({userInput:mt(),messages:mt({reducer:Ra,default:()=>[]}),pendingIntents:mt({default:()=>[],reducer:X1}),currentIntent:mt({default:()=>"none",reducer:X1})});var Qi=async(e,t)=>{await O3("trace_message",e,t)},WV=e=>async(t,n)=>{let r=new Headers(n?.headers);return r.delete("Authorization"),r.delete("api-key"),e&&e.length>0&&(r.set("X-Esri-Authorization",`Bearer ${e}`),r.set("X-Esri-Request-Source","MapsSDK")),await fetch(t,{...n,headers:r})},JV=async(e="default",t=0)=>{let n=Q1.getDefault(),r=await DE.getCredential(`${n.url}/sharing`),s=$E[e],a=await HV(e);return new EV({modelName:s,apiKey:"dummy-key",...e!=="default"&&{temperature:t},configuration:{baseURL:a,fetch:WV(r.token)}})},GV=(e,t)=>{let n=f_.fromTemplate(e);return Bp.fromMessages([n,...t])},CE=async e=>{let{promptText:t,modelTier:n="default",temperature:r=0,messages:s,inputVariables:a,schema:i}=e,o=GV(t,s??[]),c=(await JV(n,r)).withStructuredOutput(i);return await o.pipe(c).invoke(a??{})},KV=os({id:un().min(1),name:un().min(1),description:un().min(1)});ui(KV);var XV="0.1",yo=1536,YV="openai",QV=ZV.default,e7=`Name: {name}
344
344
  Title: {title}
345
345
  Description: {description}`,t7=`Name: {name}
346
346
  Alias: {alias}
347
347
  Description: {description}`;os({schemaVersion:Io(XV),modified:Vo().int().nonnegative(),embeddings:os({modelProvider:Io(YV),model:Io(QV),dimensions:Io(yo),templates:os({layer:un().default(e7),field:un().default(t7)})}),layers:ui(os({id:un().min(1),name:un().min(1),title:un().catch(""),description:un().catch(""),vector:ui(Vo()).length(yo,{message:`Layer vector must be exactly ${yo} dimensions`}),fields:ui(os({name:un().min(1),alias:un().catch(""),description:un().catch(""),vector:ui(Vo()).length(yo,{message:`Field vector must be exactly ${yo} dimensions`})}))})).default([])});var n7=Dt.object({name:Dt.string(),description:Dt.string(),valueType:Dt.string(),alias:Dt.string()});Dt.object({fields:Dt.array(n7)});Dt.object({title:Dt.string(),description:Dt.string(),name:Dt.string().nullable()});async function cu(e,t){let n=Object.entries(e).find(([r])=>r.endsWith(`/${t}.md`));if(!n)throw new Error(`Prompt not found: ${t}
348
348
  Available prompts:
349
349
  ${Object.keys(e).join(`
350
- `)}`);return await n[1]()}function r7(e){return e?.configurable?.context?.translations}var NE=(e,t=3)=>{let n=e.map((s,a)=>s instanceof vn?a:-1).filter(s=>s!==-1);if(n.length===0)return[];let r=n.length>t?n[n.length-t]:n[0];return e.slice(r)},PE=Object.assign({"./prompts/solutions_assistant_description.md":()=>import("./DJTOZZZA.js").then(e=>e.default),"./prompts/solutions_assistant_prompts.md":()=>import("./OLD26BNC.js").then(e=>e.default)}),jE=gt.Root({messages:gt({reducer:Ra,default:()=>[]}),outputMessage:gt({reducer:(e="",t)=>typeof t=="string"&&t.trim()?e?`${e}
350
+ `)}`);return await n[1]()}function r7(e){return e?.configurable?.context?.translations}var NE=(e,t=3)=>{let n=e.map((s,a)=>s instanceof vn?a:-1).filter(s=>s!==-1);if(n.length===0)return[];let r=n.length>t?n[n.length-t]:n[0];return e.slice(r)},PE=Object.assign({"./prompts/solutions_assistant_description.md":()=>import("./DJTOZZZA.js").then(e=>e.default),"./prompts/solutions_assistant_prompts.md":()=>import("./OLD26BNC.js").then(e=>e.default)}),jE=mt.Root({messages:mt({reducer:Ra,default:()=>[]}),outputMessage:mt({reducer:(e="",t)=>typeof t=="string"&&t.trim()?e?`${e}
351
351
 
352
- ${t}`:t:e,default:()=>""})}),s7=async(e,t)=>{let n=r7(t);await Qi({text:n?.executingSolutionsAssistantAgent||"Executing Solutions Assistant Agent..."},t);let r=await cu(PE,"solutions_assistant_prompts"),s=Dt.object({reply:Dt.string()}),a=e.messages.slice(-10);return{outputMessage:(await CE({promptText:r,modelTier:"default",temperature:.7,messages:NE(a),schema:s})).reply}},a7=()=>new N_(jE).addNode("assistantLLM",s7).addEdge(wt,"assistantLLM").addEdge("assistantLLM",St),i7=await cu(PE,"solutions_assistant_description"),o7={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:i7,createGraph:a7,workspace:jE},RE=Object.assign({"./prompts/solutions_builder_description.md":()=>import("./7QUV7YG7.js").then(e=>e.default),"./prompts/solutions_builder_prompts.md":()=>import("./TE6O5EAX.js").then(e=>e.default)}),ME=gt.Root({messages:gt({reducer:Ra,default:()=>[]}),outputMessage:gt({reducer:(e="",t)=>typeof t=="string"&&t.trim()?e?`${e}
352
+ ${t}`:t:e,default:()=>""})}),s7=async(e,t)=>{let n=r7(t);await Qi({text:n?.executingSolutionsAssistantAgent||"Executing Solutions Assistant Agent..."},t);let r=await cu(PE,"solutions_assistant_prompts"),s=Dt.object({reply:Dt.string()}),a=e.messages.slice(-10);return{outputMessage:(await CE({promptText:r,modelTier:"default",temperature:.7,messages:NE(a),schema:s})).reply}},a7=()=>new N_(jE).addNode("assistantLLM",s7).addEdge(wt,"assistantLLM").addEdge("assistantLLM",St),i7=await cu(PE,"solutions_assistant_description"),o7={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:i7,createGraph:a7,workspace:jE},RE=Object.assign({"./prompts/solutions_builder_description.md":()=>import("./7QUV7YG7.js").then(e=>e.default),"./prompts/solutions_builder_prompts.md":()=>import("./TE6O5EAX.js").then(e=>e.default)}),ME=mt.Root({messages:mt({reducer:Ra,default:()=>[]}),outputMessage:mt({reducer:(e="",t)=>typeof t=="string"&&t.trim()?e?`${e}
353
353
 
354
- ${t}`:t:e,default:()=>""}),ticket:gt({reducer:(e,t)=>t??null,default:()=>null})}),Y1=await cu(RE,"solutions_builder_prompts"),c7=async(e,t)=>{await Qi({text:"Template: extracting template type and use case..."},t);let n=Dt.object({template:Dt.string()||"",useCase:Dt.string()||""});e.outputMessage&&(Y1=e.outputMessage);let r=await CE({promptText:Y1,messages:NE(e.messages),schema:n}),s=r?.template?.trim(),a=r?.useCase?.trim()||"";return{ticket:{template:s,useCase:a}}},u7=(e,t)=>{let n=e.ticket;if(!n)return e;let{hitlResponse:r}=t.configurable;if(r?.agentId!=="solutionBuilder"||r.id!=="approveTemplateTicket"){console.log(`template: ${n.template}`),console.log(`useCase: ${n.useCase}`),console.log(n);let a;if(n.template&&n.useCase){let i=[`It looks like you would like to build a ${n.template} solution.`,`The use case for this solution is: ${n.useCase}`,"Are you sure you want to proceed?"].join(`
354
+ ${t}`:t:e,default:()=>""}),ticket:mt({reducer:(e,t)=>t??null,default:()=>null})}),Y1=await cu(RE,"solutions_builder_prompts"),c7=async(e,t)=>{await Qi({text:"Template: extracting template type and use case..."},t);let n=Dt.object({template:Dt.string()||"",useCase:Dt.string()||""});e.outputMessage&&(Y1=e.outputMessage);let r=await CE({promptText:Y1,messages:NE(e.messages),schema:n}),s=r?.template?.trim(),a=r?.useCase?.trim()||"";return{ticket:{template:s,useCase:a}}},u7=(e,t)=>{let n=e.ticket;if(!n)return e;let{hitlResponse:r}=t.configurable;if(r?.agentId!=="solutionBuilder"||r.id!=="approveTemplateTicket"){console.log(`template: ${n.template}`),console.log(`useCase: ${n.useCase}`),console.log(n);let a;if(n.template&&n.useCase){let i=[`It looks like you would like to build a ${n.template} solution.`,`The use case for this solution is: ${n.useCase}`,"Are you sure you want to proceed?"].join(`
355
355
  `);a={agentId:Lo.id,id:"approveTemplateTicket",kind:"singleSelection",message:i,metadata:["Yes","No"]}}else if(n.template&&!n.useCase){let i=[`It looks like you would like to build a ${n.template} solution.`,`Next we need to uderstandf the use case for the ${n.template} solution.`,"Please provide more details about the use case."].join(`
356
356
  `);a={agentId:Lo.id,id:"approveTemplateTicket",kind:"textInput",message:i,metadata:[]}}else if(!n.template&&!n.useCase){let i=["Templates provide a starting structure for your solution, including layers, maps, and apps. Choose a template to get started."].join(`
357
357
  `);a={agentId:Lo.id,id:"approveTemplateTicket",kind:"singleSelection",message:i,metadata:["Field inspections","Spatial Data Management","Points of interest"]}}else if(!n.template&&n.useCase){let i=[`We understand that your use case is ${n.useCase}.`,"We alse need to know what template to use.","Templates provide a starting structure for your solution, including layers, maps, and apps. Choose a template to get started."].join(`
358
358
  `);a={agentId:Lo.id,id:"approveTemplateTicket",kind:"singleSelection",message:i,metadata:["Field inspections","Spatial Data Management","Points of interest"]}}throw new ly(a)}console.log(`hitlResponse.payload: ${r.payload}`);let s=r.payload;if(!n.template||!n.useCase){if(s==="No")return{outputMessage:"Okay, I've cancelled solution builder.",ticket:null};if(s==="Field inspections"||s==="Spatial Data Management"||s==="Points of interest")return{outputMessage:`Use ${s} template to create a new solution.`,ticket:{template:s,useCase:n.useCase}}}return e},l7=async(e,t)=>{await Qi({text:"persisting template and use case"},t);let n=e.ticket;if(!n)return{outputMessage:"I couldn't start the solution builder.Please let me know what you would like to do."};try{console.log("sending trace"),await Qi({text:"Template and use case set."},t)}catch(r){throw new Error(`Failed to save Builder request: ${r.message}`)}return{outputMessage:["Thanks, I\u2019ve logged your Builder request:","",`- template: ${n.template}`,`- useCase: ${n.useCase}`].join(`
359
- `)}},d7=()=>new N_(ME).addNode("extractTemplateLLM",c7).addNode("approvalTemplate",u7).addNode("persistTemplate",l7).addEdge(wt,"extractTemplateLLM").addEdge("extractTemplateLLM","approvalTemplate").addConditionalEdges("approvalTemplate",e=>e.ticket?.template===""||e.ticket?.useCase===""?"continue":"done",{done:"persistTemplate",continue:"extractTemplateLLM"}).addEdge("persistTemplate",St),p7=await cu(RE,"solutions_builder_description"),Lo={id:"solutionBuilder",name:"Solution Builder Agent",description:p7,createGraph:d7,workspace:ME},h7=Object.assign({"./prompts/explorer-prompts.md":()=>import("./GV3BOKA2.js").then(e=>e.default),"./prompts/solutions_explorer_description.md":()=>import("./NNOZ6KRO.js").then(e=>e.default)});function f7(e){return e&&e.helperServices.aiAssistantServices?`${e.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}var m7=e=>new Promise(t=>setTimeout(t,e)),LE=gt.Root({messages:gt({reducer:Ra,default:()=>[]}),outputMessage:gt({reducer:(e="",t)=>typeof t=="string"&&t.trim()?e?`${e}
360
-
361
- ${t}`:t:e,default:()=>""}),solutionResponse:gt({reducer:(e,t)=>t??null,default:()=>null}),documentSkillUrl:gt({reducer:(e,t)=>t??null,default:()=>null})}),g7=()=>new N_(LE).addNode("initializeAgent",_7).addNode("askSolutionsQuestions",y7).addEdge(wt,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addConditionalEdges("askSolutionsQuestions",e=>e.solutionResponse?.hasMore===!1?"done":"continue",{done:St,continue:"askSolutionsQuestions"}),y7=async(e,t)=>{t&&(t.recursionLimit=100),e.solutionResponse?.conversationId||await Qi({text:"Calling the documentation assistant"},t);let n={message:e.messages[e.messages.length-1].content,conversationId:t?.configurable?.context?.convoId,context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:"solutions"}}}};e.solutionResponse?.conversationId&&e.solutionResponse.hasMore&&(n={conversationId:e.solutionResponse.conversationId,ackSequenceNumber:e.solutionResponse.ackSequenceNumber,inquiryId:e.solutionResponse.inquiryId}),e.solutionResponse?.conversationId&&e.solutionResponse.hasMore&&await m7(1500);let r=e.documentSkillUrl,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",token:t?.configurable?.context?.token},body:JSON.stringify(n)});if(!s.ok)throw new Error(`HTTP ${s.status} calling ${r}`);let a=await s.json();t&&t.configurable&&(t.configurable.context.convoId=a.conversationId);let i={message:a.message,conversationId:a.conversationId,hasMore:a.hasMore,ackSequenceNumber:a.sequenceNumber,inquiryId:a.inquiryId},o=a.context&&a.context.results?a.context.results[0].reply??"":"";return o!==""&&a.context&&a.context.results&&a.context.results[0].followupQuestions&&t?.configurable?.context?.updateSuggestedPrompts&&t.configurable.context.updateSuggestedPrompts(a.context.results[0].followupQuestions),a.context&&a.context.results&&a.context.results[0].status.currentStatusMessage&&await Qi({text:a.context.results[0].status.currentStatusMessage},t),{outputMessage:o,solutionResponse:i}},_7=async(e,t)=>{let n=null;return e.documentSkillUrl===null&&t?.configurable?.context?.portal&&(n=f7(t.configurable.context.portal)),{documentSkillUrl:n}},v7=await cu(h7,"solutions_explorer_description"),w7={id:"solutionsExplorerAgent",name:"Solutions Explorer Agent",description:v7,createGraph:g7,workspace:LE},b7="https://links.esri.com/solutions/agol-organizational-account",k7="https://links.esri.com/solutions/configure-assistants",iy=class extends d0{constructor(){super(),this.open=!1,this.userFirstName="",this._conversationId=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._translations=f0({name:"arcgis-solutions-assistant",blocking:!0}),this._assistantRef=u0(),this._configContextConsumer=m0({context:g0,subscribe:!0,callback:t=>{t?.userSession&&!this.userFirstName&&this._loadUserFirstName(),t?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=t?.authentication?.PortalSubset?.orgSettings)}}),this.closeAssistant=a0(),this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open}}static{this.properties={open:5,userFirstName:1,_conversationId:16,_orgSettings:16,_suggestedPrompts:16,_translations:16}}static{this.styles=FE}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}loaded(){this._checkURLOpenParameter()}load(){this._configContextConsumer.value?.portalURL&&(UE.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(t){this._loadUserFirstName()}willUpdate(t){this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return co`<calcite-notice open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??p0} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return co`<calcite-notice open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${v0(this._translations.noPermissionMessage.replace("{{orgUrl}}",b7).replace("{{configAI}}",k7))}</div></calcite-notice>`}render(){let t=this._suggestedPrompts.length>0?this._suggestedPrompts:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length===0&&(t=[...t],t.push("I want to build my own solution."),t.push("Tell me more about the ArcGIS Solutions assistant."),t.push("I want to build my own solution.")),co`<calcite-dialog class="chat-panel" .open=${this.open} .heading=${this._translations.solutionAssistantTitle} placement=bottom-start @calciteDialogClose=${()=>{this.closeAssistant.emit(!0),this.open=!1}}>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?co`<calcite-button appearance=transparent class="icon-color-background" id=newChatButton icon-end=speech-bubble-plus kind=neutral label="New conversation" @click=${()=>{this._conversationId=void 0,this._suggestedPrompts=[],this._assistantRef.value?.clearChatHistory()}} scale=l slot=header-actions-end></calcite-button><calcite-tooltip placement=bottom reference-element=newChatButton><span>${this._translations.tooltips.newConversation}</span></calcite-tooltip><arcgis-assistant reference-element copy-enabled feedback-enabled heading description .suggestedPrompts=${t} @arcgisSubmit=${n=>{console.log("arcgis submit: ",n.detail);let r=Date.now(),s=_0(r),a=n.detail||"Unknown";this._telemetry?.logEvent({category:y0.ASSISTANT,action:"Chat",dimensions:[a],metrics:[s]})}} @arcgisFeedback=${n=>{n.detail}} ${l0(this._assistantRef)}><arcgis-assistant-agent .agent=${w7} .context=${{token:this._configContextConsumer.value?.userSession?.token,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,updateSuggestedPrompts:n=>{this._suggestedPrompts=n}}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${o7} .context=${{translations:this._translations}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Lo}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="width-100"><div class="disclaimer-div padding-top-10" slot=footer><calcite-icon icon=information scale=s></calcite-icon>${this._translations.disclaimerMessage}<a href=https://links.esri.com/solutions/security-concern target=_blank>${this._translations.reportConcern}</a></div></div>`:this._renderNoPermission():this._renderNoSign()}</calcite-dialog>`}async _loadUserFirstName(){try{let t=await this._configContextConsumer.value?.userSession?.getUser();if(t?.fullName){let n=t.fullName.split(" ")[0];this.userFirstName=n}}catch{}}};h0("arcgis-solutions-assistant",iy);return iy},"config","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)
359
+ `)}},d7=()=>new N_(ME).addNode("extractTemplateLLM",c7).addNode("approvalTemplate",u7).addNode("persistTemplate",l7).addEdge(wt,"extractTemplateLLM").addEdge("extractTemplateLLM","approvalTemplate").addConditionalEdges("approvalTemplate",e=>e.ticket?.template===""||e.ticket?.useCase===""?"continue":"done",{done:"persistTemplate",continue:"extractTemplateLLM"}).addEdge("persistTemplate",St),p7=await cu(RE,"solutions_builder_description"),Lo={id:"solutionBuilder",name:"Solution Builder Agent",description:p7,createGraph:d7,workspace:ME},h7=Object.assign({"./prompts/explorer-prompts.md":()=>import("./GV3BOKA2.js").then(e=>e.default),"./prompts/solutions_explorer_description.md":()=>import("./NNOZ6KRO.js").then(e=>e.default)});function f7(e,t){if(t.startsWith(e))return t.slice(e.length);let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return t.slice(n)}function m7(e){return e&&e.helperServices.aiAssistantServices?`${e.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}var g7=e=>new Promise(t=>setTimeout(t,e)),LE=mt.Root({messages:mt({reducer:Ra,default:()=>[]}),outputMessage:mt({default:()=>"",reducer:(e,t)=>typeof t!="string"||t.length===0?e:e+t}),_lastFullOutput:mt({default:()=>"",reducer:(e,t)=>typeof t!="string"?e:t}),solutionResponse:mt({reducer:(e,t)=>t??null,default:()=>null}),documentSkillUrl:mt({reducer:(e,t)=>t??null,default:()=>null})}),y7=()=>new N_(LE).addNode("initializeAgent",v7).addNode("askSolutionsQuestions",_7).addEdge(wt,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addConditionalEdges("askSolutionsQuestions",e=>e.solutionResponse?.hasMore===!1?"done":"continue",{done:St,continue:"askSolutionsQuestions"}),_7=async(e,t)=>{t&&(t.recursionLimit=100),e.solutionResponse?.conversationId||await Qi({text:"Calling the documentation assistant"},t);let n={message:e.messages[e.messages.length-1].content,conversationId:t?.configurable?.context?.convoId,context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:"solutions"}}}};e.solutionResponse?.conversationId&&e.solutionResponse.hasMore&&(n={conversationId:e.solutionResponse.conversationId,ackSequenceNumber:e.solutionResponse.ackSequenceNumber,inquiryId:e.solutionResponse.inquiryId}),e.solutionResponse?.conversationId&&e.solutionResponse.hasMore&&await g7(1500);let r=e.documentSkillUrl,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",token:t?.configurable?.context?.token},body:JSON.stringify(n)});if(!s.ok)throw new Error(`HTTP ${s.status} calling ${r}`);let a=await s.json();t&&t.configurable&&(t.configurable.context.convoId=a.conversationId);let i={message:a.message,conversationId:a.conversationId,hasMore:a.hasMore,ackSequenceNumber:a.sequenceNumber,inquiryId:a.inquiryId},o=a.context&&a.context.results?a.context.results[0].reply??"":"";o!==""&&a.context&&a.context.results&&a.context.results[0].followupQuestions&&t?.configurable?.context?.updateSuggestedPrompts&&t.configurable.context.updateSuggestedPrompts(a.context.results[0].followupQuestions);let c=e._lastFullOutput??"",u=o,l=f7(c,u);return a.context&&a.context.results&&a.context.results[0].status.currentStatusMessage&&await Qi({text:a.context.results[0].status.currentStatusMessage},t),{outputMessage:l,_lastFullOutput:u,solutionResponse:i}},v7=async(e,t)=>{let n=null;return e.documentSkillUrl===null&&t?.configurable?.context?.portal&&(n=m7(t.configurable.context.portal)),{documentSkillUrl:n}},w7=await cu(h7,"solutions_explorer_description"),b7={id:"solutionsExplorerAgent",name:"Solutions Explorer Agent",description:w7,createGraph:y7,workspace:LE},k7="https://links.esri.com/solutions/agol-organizational-account",x7="https://links.esri.com/solutions/configure-assistants",iy=class extends d0{constructor(){super(),this.open=!1,this.userFirstName="",this._conversationId=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._translations=f0({name:"arcgis-solutions-assistant",blocking:!0}),this._assistantRef=u0(),this._configContextConsumer=m0({context:g0,subscribe:!0,callback:t=>{t?.userSession&&!this.userFirstName&&this._loadUserFirstName(),t?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=t?.authentication?.PortalSubset?.orgSettings)}}),this.closeAssistant=a0(),this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open}}static{this.properties={open:5,userFirstName:1,_conversationId:16,_orgSettings:16,_suggestedPrompts:16,_translations:16}}static{this.styles=FE}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}loaded(){this._checkURLOpenParameter()}load(){this._configContextConsumer.value?.portalURL&&(UE.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(t){this._loadUserFirstName()}willUpdate(t){this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return co`<calcite-notice open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??p0} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return co`<calcite-notice open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${v0(this._translations.noPermissionMessage.replace("{{orgUrl}}",k7).replace("{{configAI}}",x7))}</div></calcite-notice>`}render(){let t=this._suggestedPrompts.length>0?this._suggestedPrompts:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length===0&&(t=[...t],t.push("I want to build my own solution."),t.push("Tell me more about the ArcGIS Solutions assistant."),t.push("I want to build my own solution.")),co`<calcite-dialog class="chat-panel" .open=${this.open} .heading=${this._translations.solutionAssistantTitle} placement=bottom-start @calciteDialogClose=${()=>{this.closeAssistant.emit(!0),this.open=!1}}>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?co`<calcite-button appearance=transparent class="icon-color-background" id=newChatButton icon-end=speech-bubble-plus kind=neutral label="New conversation" @click=${()=>{this._conversationId=void 0,this._suggestedPrompts=[],this._assistantRef.value?.clearChatHistory()}} scale=l slot=header-actions-end></calcite-button><calcite-tooltip placement=bottom reference-element=newChatButton><span>${this._translations.tooltips.newConversation}</span></calcite-tooltip><arcgis-assistant reference-element copy-enabled feedback-enabled heading description .suggestedPrompts=${t} @arcgisSubmit=${n=>{console.log("arcgis submit: ",n.detail);let r=Date.now(),s=_0(r),a=n.detail||"Unknown";this._telemetry?.logEvent({category:y0.ASSISTANT,action:"Chat",dimensions:[a],metrics:[s]})}} @arcgisFeedback=${n=>{n.detail}} ${l0(this._assistantRef)}><arcgis-assistant-agent .agent=${b7} .context=${{token:this._configContextConsumer.value?.userSession?.token,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,updateSuggestedPrompts:n=>{this._suggestedPrompts=n}}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${o7} .context=${{translations:this._translations}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Lo}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="width-100"><div class="disclaimer-div padding-top-10" slot=footer><calcite-icon icon=information scale=s></calcite-icon>${this._translations.disclaimerMessage}<a href=https://links.esri.com/solutions/security-concern target=_blank>${this._translations.reportConcern}</a></div></div>`:this._renderNoPermission():this._renderNoSign()}</calcite-dialog>`}async _loadUserFirstName(){try{let t=await this._configContextConsumer.value?.userSession?.getUser();if(t?.fullName){let n=t.fullName.split(" ")[0];this.userFirstName=n}}catch{}}};h0("arcgis-solutions-assistant",iy);return iy},"config","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)