@arcgis/portal-components 6.0.0-next.41 → 6.0.0-next.43

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.
Files changed (37) hide show
  1. package/dist/cdn/{ONRTCGLU.js → 24JMI26O.js} +1 -1
  2. package/dist/cdn/55C6QNU6.js +63 -0
  3. package/dist/cdn/7LTDWHLV.js +16 -0
  4. package/dist/cdn/BCCFB3DG.js +18 -0
  5. package/dist/cdn/{RX64JXHI.js → EP2IQ53W.js} +29 -29
  6. package/dist/cdn/{BX7Q3V2Y.js → FIYYZIGB.js} +2 -2
  7. package/dist/cdn/HFPMMGTC.js +2 -0
  8. package/dist/cdn/HLERJBHM.js +119 -0
  9. package/dist/cdn/JVMGFTLZ.js +106 -0
  10. package/dist/cdn/KPGUIUD7.js +2 -0
  11. package/dist/cdn/{3HZI6MKD.js → QBJZCFZW.js} +1 -1
  12. package/dist/cdn/SCIZKRKA.js +93 -0
  13. package/dist/cdn/UK7WZMZ4.js +3 -0
  14. package/dist/cdn/{Y7ZCEONL.js → YZZQ3Y6G.js} +1 -1
  15. package/dist/cdn/index.js +1 -1
  16. package/dist/chunks/contextUsage.js +25 -16
  17. package/dist/components/arcgis-portal-ai-assistant/customElement.js +243 -247
  18. package/dist/components/arcgis-portal-ai-assistant-diagnostics/contextUsage.d.ts +8 -0
  19. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.d.ts +3 -2
  20. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.js +194 -30
  21. package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.js +5 -2
  22. package/dist/components/arcgis-portal-navigation/index.js +5 -5
  23. package/dist/docs/api.json +1 -1
  24. package/dist/docs/docs.json +1 -1
  25. package/dist/docs/vscode.html-custom-data.json +1 -1
  26. package/dist/docs/web-types.json +1 -1
  27. package/package.json +8 -8
  28. package/dist/cdn/5ZHNRQOW.js +0 -2
  29. package/dist/cdn/7VPB6Q55.js +0 -63
  30. package/dist/cdn/DU2R3VC4.js +0 -2
  31. package/dist/cdn/ITRJGXFV.js +0 -93
  32. package/dist/cdn/KWL2D56D.js +0 -3
  33. package/dist/cdn/L3YOPSRB.js +0 -135
  34. package/dist/cdn/N47MW5HI.js +0 -9
  35. package/dist/cdn/QAXFE5DD.js +0 -2
  36. package/dist/cdn/R6KJVAX3.js +0 -99
  37. package/dist/cdn/XYHIVGUK.js +0 -2
@@ -0,0 +1,106 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{$ as Si,Aa as Fi,Ba as zi,C as li,Ca as De,D as br,Da as tn,E as di,Ea as Bi,F as $a,Fa as Zi,Ga as rn,H as fi,Ha as Bt,I as wr,Ia as Zt,J as pi,Ja as Ui,K as xr,Ka as Vi,L as zt,La as Wi,M as Hr,Ma as Et,N as mi,Na as Dn,O as Pn,Oa as Ln,P as Rn,Pa as Gi,Q as hi,Qa as Ji,R as gi,Ra as Ut,S as Mn,Sa as qi,T as yi,Ta as Hi,U as _i,V as vi,W as bi,X as wi,Xa as jn,Y as xi,Ya as et,Z as ki,_ as Ti,_a as Ce,a as M,aa as Ei,ab as he,ba as Ai,bb as Vt,c as oi,ca as Oi,cb as q,da as Ci,db as Y,ea as Ii,eb as ke,f as ci,fa as Oe,g as qr,ga as kr,ha as Ni,ia as Pi,ka as $n,la as St,ma as Kr,n as Cn,na as Ri,oa as Mi,pa as $i,q as _r,qa as Je,ra as Tr,s as In,sa as Di,t as ui,ta as pe,ua as Yr,v as yu,va as Xr,wa as Li,x as Nn,xa as ji,ya as Qr,z as vr,za as en}from"./EP2IQ53W.js";import{A as za,a as tt,b as Da,c as Fn,d as La,e as Ki,f as Yi,g as ja,j as Te,k as Xi,l as Qi,m as Fa}from"./55C6QNU6.js";import{a as hu,b as gu,c as ii}from"./5PV2GUZW.js";var Wc=hu(Ta=>{"use strict";Ta.byteLength=mf;Ta.toByteArray=gf;Ta.fromByteArray=vf;var ut=[],Ue=[],pf=typeof Uint8Array<"u"?Uint8Array:Array,qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(mr=0,Uc=qs.length;mr<Uc;++mr)ut[mr]=qs[mr],Ue[qs.charCodeAt(mr)]=mr;var mr,Uc;Ue[45]=62;Ue[95]=63;function Vc(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function mf(e){var t=Vc(e),r=t[0],n=t[1];return(r+n)*3/4-n}function hf(e,t,r){return(t+r)*3/4-r}function gf(e){var t,r=Vc(e),n=r[0],a=r[1],s=new pf(hf(e,n,a)),i=0,o=a>0?n-4:n,c;for(c=0;c<o;c+=4)t=Ue[e.charCodeAt(c)]<<18|Ue[e.charCodeAt(c+1)]<<12|Ue[e.charCodeAt(c+2)]<<6|Ue[e.charCodeAt(c+3)],s[i++]=t>>16&255,s[i++]=t>>8&255,s[i++]=t&255;return a===2&&(t=Ue[e.charCodeAt(c)]<<2|Ue[e.charCodeAt(c+1)]>>4,s[i++]=t&255),a===1&&(t=Ue[e.charCodeAt(c)]<<10|Ue[e.charCodeAt(c+1)]<<4|Ue[e.charCodeAt(c+2)]>>2,s[i++]=t>>8&255,s[i++]=t&255),s}function yf(e){return ut[e>>18&63]+ut[e>>12&63]+ut[e>>6&63]+ut[e&63]}function _f(e,t,r){for(var n,a=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),a.push(yf(n));return a.join("")}function vf(e){for(var t,r=e.length,n=r%3,a=[],s=16383,i=0,o=r-n;i<o;i+=s)a.push(_f(e,i,i+s>o?o:i+s));return n===1?(t=e[r-1],a.push(ut[t>>2]+ut[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],a.push(ut[t>>10]+ut[t>>4&63]+ut[t<<2&63]+"=")),a.join("")}});var _u=Object.prototype.hasOwnProperty;function Bn(e,t){return _u.call(e,t)}function Zn(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)Bn(e,r)&&t.push(r);return t}function Ie(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Un(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function Wt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function to(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function zn(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(zn(e[r]))return!0}else if(typeof e=="object"){let r=Zn(e),n=r.length;for(var t=0;t<n;t++)if(zn(e[r[t]]))return!0}}return!1}function eo(e,t){let r=[e];for(let n in t){let a=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
3
+ `)}var ro=class extends Error{name;index;operation;tree;constructor(e,t,r,n,a){super(eo(e,{name:t,index:r,operation:n,tree:a})),this.name=t,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=eo(e,{name:t,index:r,operation:n,tree:a})}};var no=M({JsonPatchError:()=>se,_areEquals:()=>Er,applyOperation:()=>At,applyPatch:()=>pt,applyReducer:()=>ao,deepClone:()=>vu,getValueByPointer:()=>nn,validate:()=>Ba,validator:()=>an});var se=ro,vu=Ie,Sr={add:function(e,t,r){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:r}},remove:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=nn(r,this.path);n&&(n=Ie(n));let a=At(r,{op:"remove",path:this.from}).removed;return At(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=nn(r,this.from);return At(r,{op:"add",path:this.path,value:Ie(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Er(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},bu={add:function(e,t,r){return Un(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:Sr.move,copy:Sr.copy,test:Sr.test,_get:Sr._get};function nn(e,t){if(t=="")return e;var r={op:"_get",path:t};return At(e,r),r.value}function At(e,t,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):an(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=nn(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=Er(e,t.value),i.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,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(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{n||(e=Ie(e));let i=(t.path||"").split("/"),o=e,c=1,u=i.length,f,p,g;for(typeof r=="function"?g=r:g=an;;){if(p=i[c],p&&p.indexOf("~")!=-1&&(p=to(p)),a&&(p=="__proto__"||p=="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(r&&f===void 0&&(o[p]===void 0?f=i.slice(0,c).join("/"):c==u-1&&(f=t.path),f!==void 0&&g(t,0,e,f)),c++,Array.isArray(o)){if(p==="-")p=o.length;else{if(r&&!Un(p))throw new se("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",s,t,e);Un(p)&&(p=~~p)}if(c>=u){if(r&&t.op==="add"&&p>o.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);let h=bu[t.op].call(t,o,p,e);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return h}}else if(c>=u){let h=Sr[t.op].call(t,o,p,e);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return h}if(o=o[p],r&&c<u&&(!o||typeof o!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function pt(e,t,r,n=!0,a=!0){if(r&&!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=Ie(e));let s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=At(e,t[i],r,!0,a,i),e=s[i].newDocument;return s.newDocument=e,s}function ao(e,t,r){let n=At(e,t);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function an(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(Sr[e.op]){if(typeof e.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&zn(e.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var a=e.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var i=Ba([{op:"_get",path:e.from,value:void 0}],r);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function Ba(e,t,r){try{if(!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)pt(Ie(t),Ie(e),r||!0);else{r=r||an;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(a){if(a instanceof se)return a;throw a}}function Er(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),a,s,i;if(r&&n){if(s=e.length,s!=t.length)return!1;for(a=s;a--!==0;)if(!Er(e[a],t[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(a=s;a--!==0;)if(!t.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!Er(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function so(e,t,r,n,a){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Zn(t),i=Zn(e),o=!1,c=i.length-1;c>=0;c--){var u=i[c],f=e[u];if(Bn(t,u)&&!(t[u]===void 0&&f!==void 0&&Array.isArray(t)===!1)){var p=t[u];typeof f=="object"&&f!=null&&typeof p=="object"&&p!=null&&Array.isArray(f)===Array.isArray(p)?so(f,p,r,n+"/"+Wt(u),a):f!==p&&(a&&r.push({op:"test",path:n+"/"+Wt(u),value:Ie(f)}),r.push({op:"replace",path:n+"/"+Wt(u),value:Ie(p)}))}else Array.isArray(e)===Array.isArray(t)?(a&&r.push({op:"test",path:n+"/"+Wt(u),value:Ie(f)}),r.push({op:"remove",path:n+"/"+Wt(u)}),o=!0):(a&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var u=s[c];!Bn(e,u)&&t[u]!==void 0&&r.push({op:"add",path:n+"/"+Wt(u),value:Ie(t[u])})}}}function Gt(e,t,r=!1){var n=[];return so(e,t,n,"",r),n}({...no});async function Ne(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(Ot(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&a(Ot(t))})]).finally(()=>t.removeEventListener("abort",r))}function Ot(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var gp=M({AsyncGeneratorWithSetup:()=>Ct,IterableReadableStream:()=>be,atee:()=>Vn,concat:()=>Pe,pipeGeneratorWithSetup:()=>Ua}),be=class Za extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new Za({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new Za({async pull(r){let{value:n,done:a}=await t.next();a&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function Vn(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){let s=await e.next();for(let i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function Pe(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,a]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=Pe(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Ct=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{Ce.runWithConfig(ke(e.config),async()=>{this.firstResult=this.signal?Ne(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ce.runWithConfig(ke(this.config),this.signal?async()=>Ne(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Ua(e,t,r,n,...a){let s=new Ct({generator:t,startSetup:r,signal:n}),i=await s.setup;return{output:e(s,i,...a),setup:i}}var Sp=M({LogStreamCallbackHandler:()=>Gn,RunLog:()=>Wn,RunLogPatch:()=>rt,isLogStreamHandler:()=>Wa}),rt=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=pt({},t);return new Wn({ops:t,state:r[r.length-1].newDocument})}},Wn=class Va extends rt{state;constructor(t){super(t),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=pt(this.state,t.ops);return new Va({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=pt({},t.ops);return new Va({ops:t.ops,state:r[r.length-1].newDocument})}},Wa=e=>e.name==="log_stream_tracer";async function io(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:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function oo(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function wu(e){return e!==void 0&&e.message!==void 0}var Gn=class extends vr{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=be.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??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let n=this.keyMapByRunId[e];n&&await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new rt({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 r={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"&&(r.inputs=await io(e,this._schemaFormat)),await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await io(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await oo(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new rt({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new rt({ops:[{op:"replace",path:"/final_output",value:await oo(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n=this.keyMapByRunId[e.id];if(n===void 0)return;let a=e.inputs.messages!==void 0,s;a?wu(r?.chunk)?s=r?.chunk:s=new pe({id:`run-${e.id}`,content:t}):s=t;let i=new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}};var Ip=M({ChatGenerationChunk:()=>Jn,GenerationChunk:()=>mt,RUN_KEY:()=>Jt}),Jt="__run",mt=class co{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new co({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Jn=class uo extends mt{message;constructor(t){super(t),this.message=t.message}concat(t){return new uo({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function qn({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var lo=e=>e.name==="event_stream_tracer",fo=class extends vr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;writerClosed=!1;name="event_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.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=be.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new mt({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);try{let o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(let c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(let i of t)yield i}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=qn(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);let a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){let n=this.runInfoMap.get(e.id),a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new pe({content:t,id:`run-${e.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new mt({text:t}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations,a;if(t.runType==="chat_model"){for(let s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=qn(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},n.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,n.inputs=e.inputs.input):(a.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(a.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=qn(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=qn(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>this.close())}close(){this.writerClosed||(this.writerClosed=!0,this.writer.close())}};var xu=Object.prototype.toString,ku=e=>xu.call(e)==="[object Error]",Tu=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 po(e){if(!(e&&ku(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:t,stack:r}=e;return t==="Load failed"?r===void 0||"__sentry_captured__"in e:t.startsWith("error sending request for url")?!0:Tu.has(t)}function Su(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 Hn(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var Eu=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 Au(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,a=Math.round(n*t.minTimeout*t.factor**(r-1));return a=Math.min(a,t.maxTimeout),a}function mo(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Ou({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:a}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof Eu)throw s.originalError;let i=Number.isFinite(a.retries)?Math.max(0,a.retries-r):a.retries,o=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:i,retriesConsumed:r});if(await a.onFailedAttempt(c),mo(n,o)<=0)throw s;let u=await a.shouldConsumeRetry(c),f=mo(n,o);if(f<=0||i<=0)throw s;if(s instanceof TypeError&&!po(s)){if(u)throw s;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw s;if(!u)return a.signal?.throwIfAborted(),!1;let p=Au(r,a),g=typeof s.retryAfterMs=="number"&&s.retryAfterMs>=0?s.retryAfterMs:void 0;g!==void 0&&(p=Math.max(p,g));let h=Math.min(p,f);return h>0&&await new Promise((m,v)=>{let b=()=>{clearTimeout(x),a.signal?.removeEventListener("abort",b),v(a.signal.reason)},x=setTimeout(()=>{a.signal?.removeEventListener("abort",b),m()},h);a.unref&&x.unref?.(),a.signal?.addEventListener("abort",b,{once:!0})}),a.signal?.throwIfAborted(),!0}async function sn(e,t={}){if(t={...t},Su(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,Hn("factor",t.factor,{min:0,allowInfinity:!1}),Hn("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Hn("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Hn("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,a=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await Ou({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Kn=ii(yu(),1),Gp=M({AsyncCaller:()=>ht,classifyRateLimitError:()=>bo,parseRetryAfterMs:()=>vo}),Cu=[400,401,402,403,404,405,406,407,409,413],Iu=6e4,Nu=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],Pu=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function go(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0}function yo(e){if(!(typeof e!="object"||e===null)){if("status"in e&&typeof e.status=="number")return e.status;if("statusCode"in e&&typeof e.statusCode=="number")return e.statusCode}}function Ja(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:void 0}function _o(e){if(!(typeof e!="object"||e===null))return"code"in e&&typeof e.code=="string"?e.code:"error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0}function Ru(e){if(e?.headers)return typeof e.headers.get=="function"?e.headers.get("retry-after"):e.headers["retry-after"]??e.headers["Retry-After"];if(e?.response?.headers)return typeof e.response.headers.get=="function"?e.response.headers.get("retry-after"):e.response.headers["retry-after"]??e.response.headers["Retry-After"]}function Mu(e){if(e==null)return;let t=Pu.exec(e);if(!t)return;let r=Number(t[1]),n=t[2]?.toLowerCase();if(!(Number.isNaN(r)||!n))return n==="ms"||n.startsWith("millisecond")?r:n==="m"||n.startsWith("min")?r*6e4:n==="h"||n.startsWith("hr")||n.startsWith("hour")?r*36e5:r*1e3}function ho(e,t){if(e instanceof Error)return e;let r=new Error(t);return typeof e=="object"&&e!==null&&Object.assign(r,e),r}function Ga(e,t){if(typeof e!="object"||e===null)return;let r=e;r.rateLimitType=t.action,r.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(r.retryAfterMs=t.retryAfterMs)}function vo(e){if(e==null)return;let t=e.trim();if(!t)return;let r=Number(t);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=Date.parse(t);if(!Number.isNaN(n)){let a=n-Date.now();return a>0?a:0}}function bo(e){if((go(e)??yo(e))!==429)return;if(_o(e)==="insufficient_quota")return{action:"stop",reason:"insufficient_quota"};let t=Ja(e);if(t&&Nu.some(n=>n.test(t)))return{action:"stop",reason:"quota_message"};let r=vo(Ru(e))??Mu(t);return r!==void 0?r<=Iu?{action:"wait",retryAfterMs:r,reason:"retry_after_hint"}:{action:"capacity",retryAfterMs:r,reason:"retry_after_too_large"}:{action:"capacity",reason:"headerless_429"}}var $u=e=>{if(typeof e!="object"||e===null)return;if(di(e)===!1)throw e;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")throw br(e,!1);if("code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t=go(e)??yo(e);if(t&&Cu.includes(+t))throw br(e,!1);if(_o(e)==="insufficient_quota"){let n=ho(e,Ja(e)??"Insufficient quota");throw n.name="InsufficientQuotaError",Ga(n,{action:"stop",reason:"insufficient_quota"}),br(n,!1)}let r=bo(e);if(r){if(r.action==="wait"){Ga(e,r),br(e,!0);return}let n=ho(e,Ja(e)??"Rate limit exceeded");throw n.name==="Error"&&(n.name=r.action==="stop"?"RateLimitQuotaExhaustedError":"RateLimitCapacityError"),Ga(n,r),br(n,r.action!=="stop")}},ht=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??$u;let t="default"in Kn.default?Kn.default.default:Kn.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.callWithRetries(this.maxRetries,e,t)}callWithRetries(e,t,r){return this.queue.add(()=>sn(()=>t(...r).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>this.onFailedAttempt?.(n),retries:e,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){let n=e.maxRetries??this.maxRetries;if(e.signal){let a;return Promise.race([this.callWithRetries(n,t,r),new Promise((s,i)=>{a=()=>{i(Ot(e.signal))},e.signal?.addEventListener("abort",a,{once:!0})})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.callWithRetries(n,t,r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var qa=class extends vr{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function on(e){return e?e.lc_runnable:!1}var wo=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 r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}},xo=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function Ha(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var Du=["*","_","`"],Lu={"#":"#35;","[":"#91;","]":"#93;","(":"#40;",")":"#41;","{":"#123;","}":"#125;",'"':"#quot;","<":"#60;",">":"#62;","|":"#124;"};function ju(e){return e.replace(/[#[\](){}"<>|]/g,t=>Lu[t])}function ko(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Fu(e){if(ko(e))return String(e);if(Array.isArray(e)&&e.every(ko))return e.join(",")}function zu(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
4
+ `;return t}function To(e,t,r){let{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{},u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
5
+ graph TD;
6
+ `:`graph TD;
7
+ `;if(i){let m="default",v={[m]:"{0}({1})"};n!==void 0&&(v[n]="{0}([{1}]):::first"),a!==void 0&&(v[a]="{0}([{1}]):::last");for(let[b,x]of Object.entries(e)){let I=x.name.split(":").pop()??"",S=Du.some(ae=>I.startsWith(ae)&&I.endsWith(ae))?`<p>${I}</p>`:I,L=Object.entries(x.metadata??{}).flatMap(([ae,_e])=>{let y=Fu(_e);return y===void 0?[]:[ju(`${ae} = ${y}`)]});L.length&&(S+=`<hr/><small><em>${L.join(`
8
+ `)}</em></small>`);let W=(v[b]??v[m]).replace("{0}",Ha(b)).replace("{1}",S);u+=` ${W}
9
+ `}}let f={};for(let m of t){let v=m.source.split(":"),b=m.target.split(":"),x=v.filter((I,S)=>I===b[S]).join(":");f[x]||(f[x]=[]),f[x].push(m)}let p=new Set;function g(m){return[...m].sort((v,b)=>v.split(":").length-b.split(":").length)}function h(m,v){let b=m.length===1&&m[0].source===m[0].target;if(v&&!b){let I=v.split(":").pop();if(p.has(v))throw new Error(`Found duplicate subgraph '${I}' at '${v} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);p.add(v),u+=` subgraph ${I}
10
+ `}let x=g(Object.keys(f).filter(I=>I.startsWith(`${v}:`)&&I!==v&&I.split(":").length===v.split(":").length+1));for(let I of x)h(f[I],I);for(let I of m){let{source:S,target:L,data:W,conditional:ae}=I,_e="";if(W!==void 0){let y=W,Ve=y.split(" ");Ve.length>c&&(y=Array.from({length:Math.ceil(Ve.length/c)},(dt,ee)=>Ve.slice(ee*c,(ee+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),_e=ae?` -. &nbsp;${y}&nbsp; .-> `:` -- &nbsp;${y}&nbsp; --> `}else _e=ae?" -.-> ":" --> ";u+=` ${Ha(S)}${_e}${Ha(L)};
11
+ `}v&&!b&&(u+=` end
12
+ `)}h(f[""]??[],"");for(let m in f)!m.includes(":")&&m!==""&&h(f[m],m);return i&&(u+=zu(s??{})),u}async function So(e,t){let r=t?.backgroundColor??"white",n=t?.imageType??"png",a=xo(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
13
+ `));return await i.blob()}function te(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function ce(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function Eo(e){return te(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ce(e)}function Se(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(te(e)||ce(e))}function Ka(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 Ya(e){return te(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 Ao(e){return!!(Ka(e)||Ya(e))}async function Qn(e,t){if(te(e))try{return{success:!0,data:await La(e,t)}}catch(r){return{success:!1,error:r}}if(ce(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function It(e,t){if(te(e))return await La(e,t);if(ce(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Oo(e,t){if(te(e))try{return{success:!0,data:Fn(e,t)}}catch(r){return{success:!1,error:r}}if(ce(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Co(e,t){if(te(e))return Fn(e,t);if(ce(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Or(e){if(te(e))return Te.get(e)?.description;if(ce(e)||"description"in e&&typeof e.description=="string")return e.description}function Io(e){if(!Se(e))return!1;if(ce(e)){let t=e._def;if(t.typeName==="ZodObject"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(te(e)){let t=e._zod.def;if(t.type==="object"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Cr(e){return Se(e)?ce(e)?e._def.typeName==="ZodString":te(e)?e._zod.def.type==="string":!1:!1}function cn(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 Le(e){return te(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 un(e){return te(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 Xa(e){return te(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 Qa(e){return te(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 No(e){return!!(cn(e)||Le(e))}function Yn(e){if(ce(e))return e.shape;if(te(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Po(e,t){if(ce(e))return e.extend(t);if(te(e))return Da.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ro(e){if(ce(e))return e.partial();if(te(e))return Da.partial(ja,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ar(e,t=!1){if(cn(e))return e.strict();if(Le(e)){let r=e._zod.def.shape;if(t)for(let[s,i]of Object.entries(e._zod.def.shape)){if(Le(i))r[s]=Ar(i,t);else if(un(i)){let c=i._zod.def.element;Le(c)&&(c=Ar(c,t)),r[s]=tt(i,{...i._zod.def,element:c})}else r[s]=i;let o=Te.get(i);o&&Te.add(r[s],o)}let n=tt(e,{...e._zod.def,shape:r,catchall:Qi(Yi)}),a=Te.get(e);return a&&Te.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Xn(e,t=!1){if(cn(e))return e.passthrough();if(Le(e)){let r=e._zod.def.shape;if(t)for(let[s,i]of Object.entries(e._zod.def.shape)){if(Le(i))r[s]=Xn(i,t);else if(un(i)){let c=i._zod.def.element;Le(c)&&(c=Xn(c,t)),r[s]=tt(i,{...i._zod.def,element:c})}else r[s]=i;let o=Te.get(i);o&&Te.add(r[s],o)}let n=tt(e,{...e._zod.def,shape:r,catchall:Xi(Ki)}),a=Te.get(e);return a&&Te.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Mo(e){if(ce(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(te(e))try{let t=Fn(e,void 0);return()=>t}catch{return}}function Bu(e){return ce(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Zu(e){return te(e)&&e._zod.def.type==="pipe"}function qt(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(ce(e))return Bu(e)?qt(e._def.schema,t,r):e;if(te(e)){let a=e;if(Zu(e)&&(a=qt(e._zod.def.in,t,r)),t){if(Le(a)){let i={};for(let[o,c]of Object.entries(a._zod.def.shape))i[o]=qt(c,t,r);a=tt(a,{...a._zod.def,shape:i})}else if(un(a)){let i=qt(a._zod.def.element,t,r);a=tt(a,{...a._zod.def,element:i})}else if(Xa(a)){let i=qt(a._zod.def.innerType,t,r);a=tt(a,{...a._zod.def,innerType:i})}else if(Qa(a)){let i=qt(a._zod.def.innerType,t,r);a=tt(a,{...a._zod.def,innerType:i})}}let s=Te.get(e);return s&&Te.add(a,s),r.set(e,a),a}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ea(e,t=!1){return qt(e,t,new WeakMap)}function $o(e,t){if(ce(e)){let r=Yn(e),n={};for(let[a,s]of Object.entries(r))t(a,s)?n[a]=s.optional():n[a]=s;return e.extend(n)}if(te(e)){let r=Yn(e),n={...e._zod.def.shape};for(let[i,o]of Object.entries(r))t(i,o)&&(n[i]=new ja({type:"optional",innerType:o}));let a=tt(e,{...e._zod.def,shape:n}),s=Te.get(e);return s&&Te.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ta(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var ts=Symbol("Let zodToJsonSchema decide on which parser to use"),es={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"},rs=e=>typeof e=="string"?{...es,name:e}:{...es,...e};var ln=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function ne(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?ln(t,e.currentPath):t.join("/")}}function ra(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function H(e,t,r,n,a){e[t]=r,ra(e,t,n,a)}var we={};gu(we,{BRAND:()=>ml,DIRTY:()=>Ht,EMPTY_PATH:()=>Gu,INVALID:()=>D,NEVER:()=>Xl,OK:()=>ge,ParseStatus:()=>me,Schema:()=>V,ZodAny:()=>Rt,ZodArray:()=>vt,ZodBigInt:()=>Yt,ZodBoolean:()=>Xt,ZodBranded:()=>fn,ZodCatch:()=>ur,ZodDate:()=>Qt,ZodDefault:()=>cr,ZodDiscriminatedUnion:()=>sa,ZodEffects:()=>ze,ZodEnum:()=>ir,ZodError:()=>Ee,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>oa,ZodIntersection:()=>nr,ZodIssueCode:()=>k,ZodLazy:()=>ar,ZodLiteral:()=>sr,ZodMap:()=>$r,ZodNaN:()=>Lr,ZodNativeEnum:()=>or,ZodNever:()=>qe,ZodNull:()=>tr,ZodNullable:()=>st,ZodNumber:()=>Kt,ZodObject:()=>Ae,ZodOptional:()=>je,ZodParsedType:()=>O,ZodPipeline:()=>pn,ZodPromise:()=>Mt,ZodReadonly:()=>lr,ZodRecord:()=>ia,ZodSchema:()=>V,ZodSet:()=>Dr,ZodString:()=>Pt,ZodSymbol:()=>Rr,ZodTransformer:()=>ze,ZodTuple:()=>at,ZodType:()=>V,ZodUndefined:()=>er,ZodUnion:()=>rr,ZodUnknown:()=>_t,ZodVoid:()=>Mr,addIssueToContext:()=>E,any:()=>kl,array:()=>Al,bigint:()=>_l,boolean:()=>Go,coerce:()=>Yl,custom:()=>Uo,date:()=>vl,datetimeRegex:()=>Bo,defaultErrorMap:()=>gt,discriminatedUnion:()=>Nl,effect:()=>Ul,enum:()=>zl,function:()=>Ll,getErrorMap:()=>Ir,getParsedType:()=>nt,instanceof:()=>gl,intersection:()=>Pl,isAborted:()=>na,isAsync:()=>Nr,isDirty:()=>aa,isValid:()=>Nt,late:()=>hl,lazy:()=>jl,literal:()=>Fl,makeIssue:()=>dn,map:()=>$l,nan:()=>yl,nativeEnum:()=>Bl,never:()=>Sl,null:()=>xl,nullable:()=>Wl,number:()=>Wo,object:()=>Ol,objectUtil:()=>ns,oboolean:()=>Kl,onumber:()=>Hl,optional:()=>Vl,ostring:()=>ql,pipeline:()=>Jl,preprocess:()=>Gl,promise:()=>Zl,quotelessJson:()=>Uu,record:()=>Ml,set:()=>Dl,setErrorMap:()=>Wu,strictObject:()=>Cl,string:()=>Vo,symbol:()=>bl,transformer:()=>Ul,tuple:()=>Rl,undefined:()=>wl,union:()=>Il,unknown:()=>Tl,util:()=>J,void:()=>El});var J;(function(e){e.assertEqual=a=>{};function t(a){}e.assertIs=t;function r(a){throw new Error}e.assertNever=r,e.arrayToEnum=a=>{let s={};for(let i of a)s[i]=i;return s},e.getValidEnumValues=a=>{let s=e.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of s)i[o]=a[o];return e.objectValues(i)},e.objectValues=a=>e.objectKeys(a).map(function(s){return a[s]}),e.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let s=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},e.find=(a,s)=>{for(let i of a)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(J||(J={}));var ns;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(ns||(ns={}));var O=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nt=e=>{switch(typeof e){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(e)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(e)?O.array:e===null?O.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?O.promise:typeof Map<"u"&&e instanceof Map?O.map:typeof Set<"u"&&e instanceof Set?O.set:typeof Date<"u"&&e instanceof Date?O.date:O.object;default:return O.unknown}};var k=J.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"]),Uu=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ee=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},n={_errors:[]},a=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c],f=c===i.path.length-1;if(u==="_errors"){f&&o._errors.push(r(i)),c++;continue}Object.prototype.hasOwnProperty.call(o,u)||(u==="__proto__"?Object.defineProperty(o,u,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):o[u]={_errors:[]}),o=o[u],f&&o._errors.push(r(i)),c++}}};return a(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let a of this.issues)if(a.path.length>0){let s=a.path[0];r[s]=r[s]||[],r[s].push(t(a))}else n.push(t(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ee.create=e=>new Ee(e);var Vu=(e,t)=>{let r;switch(e.code){case k.invalid_type:e.received===O.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,J.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(e.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(e.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(e.options)}, received '${e.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:J.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case k.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case k.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=t.defaultError,J.assertNever(e)}return{message:r}},gt=Vu;var Do=gt;function Wu(e){Do=e}function Ir(){return Do}var dn=e=>{let{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:t,defaultError:o}).message;return{...a,path:s,message:o}},Gu=[];function E(e,t){let r=Ir(),n=dn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===gt?void 0:gt].filter(a=>!!a)});e.common.issues.push(n)}var me=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let a of r){if(a.status==="aborted")return D;a.status==="dirty"&&t.dirty(),n.push(a.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let a of r){let s=await a.key,i=await a.value;n.push({key:s,value:i})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let a of r){let{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return D;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}},D=Object.freeze({status:"aborted"}),Ht=e=>({status:"dirty",value:e}),ge=e=>({status:"valid",value:e}),na=e=>e.status==="aborted",aa=e=>e.status==="dirty",Nt=e=>e.status==="valid",Nr=e=>typeof Promise<"u"&&e instanceof Promise;var R;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(R||(R={}));var Fe=class{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a}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}},Lo=(e,t)=>{if(Nt(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 r=new Ee(e.common.issues);return this._error=r,this._error}}};function Z(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(i,o)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}var V=class{get description(){return this._def.description}_getType(t){return nt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new me,ctx:{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Nr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)},a=this._parseSync({data:t,path:n.path,parent:n});return Lo(n,a)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Nt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Nt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)},a=this._parse({data:t,path:n.path,parent:n}),s=await(Nr(a)?a:Promise.resolve(a));return Lo(n,s)}refine(t,r){let n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{let i=t(a),o=()=>s.addIssue({code:k.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,a)=>t(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(t){return new ze({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return je.create(this,this._def)}nullable(){return st.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vt.create(this)}promise(){return Mt.create(this,this._def)}or(t){return rr.create([this,t],this._def)}and(t){return nr.create(this,t,this._def)}transform(t){return new ze({...Z(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new cr({...Z(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new fn({typeName:T.ZodBranded,type:this,...Z(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new ur({...Z(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return pn.create(this,t)}readonly(){return lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ju=/^c[^\s-]{8,}$/i,qu=/^[0-9a-z]+$/,Hu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ku=/^[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,Yu=/^[a-z0-9_-]{21}$/i,Xu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qu=/^[-+]?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)?)??$/,el=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tl="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",as,rl=/^(?:(?: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])$/,nl=/^(?:(?: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])$/,al=/^(([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]))$/,sl=/^(([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])$/,il=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ol=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fo="((\\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])))",cl=new RegExp(`^${Fo}$`);function zo(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function ul(e){return new RegExp(`^${zo(e)}$`)}function Bo(e){let t=`${Fo}T${zo(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function ll(e,t){return!!((t==="v4"||!t)&&rl.test(e)||(t==="v6"||!t)&&al.test(e))}function dl(e,t){if(!Xu.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function fl(e,t){return!!((t==="v4"||!t)&&nl.test(e)||(t==="v6"||!t)&&sl.test(e))}var Pt=class e extends V{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==O.string){let s=this._getOrReturnCtx(t);return E(s,{code:k.invalid_type,expected:O.string,received:s.parsedType}),D}let n=new me,a;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:k.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&&(a=this._getOrReturnCtx(t,a),E(a,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,o=t.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(t,a),i?E(a,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&E(a,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")el.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")as||(as=new RegExp(tl,"u")),as.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ku.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Yu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Ju.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")qu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Hu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),E(a,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"regex",code:k.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)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.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)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Bo(s).test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?cl.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?ul(s).test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Qu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ll(t.data,s.version)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?dl(t.data,s.alg)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?fl(t.data,s.version)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?il.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ol.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):J.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(a=>t.test(a),{validation:r,code:k.invalid_string,...R.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...R.errToObj(t)})}url(t){return this._addCheck({kind:"url",...R.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...R.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...R.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...R.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...R.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...R.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...R.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...R.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...R.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...R.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...R.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...R.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...R.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...R.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...R.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...R.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...R.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...R.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...R.errToObj(r)})}nonempty(t){return this.min(1,R.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Pt.create=e=>new Pt({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...Z(e)});function pl(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(e.toFixed(a).replace(".","")),i=Number.parseInt(t.toFixed(a).replace(".",""));return s%i/10**a}var Kt=class e extends V{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)!==O.number){let s=this._getOrReturnCtx(t);return E(s,{code:k.invalid_type,expected:O.number,received:s.parsedType}),D}let n,a=new me;for(let s of this._def.checks)s.kind==="int"?J.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?pl(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:k.not_finite,message:s.message}),a.dirty()):J.assertNever(s);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,R.toString(r))}gt(t,r){return this.setLimit("min",t,!1,R.toString(r))}lte(t,r){return this.setLimit("max",t,!0,R.toString(r))}lt(t,r){return this.setLimit("max",t,!1,R.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:R.toString(a)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:R.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:R.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&J.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Kt.create=e=>new Kt({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...Z(e)});var Yt=class e extends V{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)!==O.bigint)return this._getInvalidInput(t);let n,a=new me;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),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):J.assertNever(s);return{status:a.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return E(r,{code:k.invalid_type,expected:O.bigint,received:r.parsedType}),D}gte(t,r){return this.setLimit("min",t,!0,R.toString(r))}gt(t,r){return this.setLimit("min",t,!1,R.toString(r))}lte(t,r){return this.setLimit("max",t,!0,R.toString(r))}lt(t,r){return this.setLimit("max",t,!1,R.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:R.toString(a)}]})}_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:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Yt.create=e=>new Yt({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...Z(e)});var Xt=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==O.boolean){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.boolean,received:n.parsedType}),D}return ge(t.data)}};Xt.create=e=>new Xt({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...Z(e)});var Qt=class e extends V{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==O.date){let s=this._getOrReturnCtx(t);return E(s,{code:k.invalid_type,expected:O.date,received:s.parsedType}),D}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:k.invalid_date}),D}let n=new me,a;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):J.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,r){return this._addCheck({kind:"min",value:t.getTime(),message:R.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:R.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Qt.create=e=>new Qt({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...Z(e)});var Rr=class extends V{_parse(t){if(this._getType(t)!==O.symbol){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.symbol,received:n.parsedType}),D}return ge(t.data)}};Rr.create=e=>new Rr({typeName:T.ZodSymbol,...Z(e)});var er=class extends V{_parse(t){if(this._getType(t)!==O.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.undefined,received:n.parsedType}),D}return ge(t.data)}};er.create=e=>new er({typeName:T.ZodUndefined,...Z(e)});var tr=class extends V{_parse(t){if(this._getType(t)!==O.null){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.null,received:n.parsedType}),D}return ge(t.data)}};tr.create=e=>new tr({typeName:T.ZodNull,...Z(e)});var Rt=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return ge(t.data)}};Rt.create=e=>new Rt({typeName:T.ZodAny,...Z(e)});var _t=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ge(t.data)}};_t.create=e=>new _t({typeName:T.ZodUnknown,...Z(e)});var qe=class extends V{_parse(t){let r=this._getOrReturnCtx(t);return E(r,{code:k.invalid_type,expected:O.never,received:r.parsedType}),D}};qe.create=e=>new qe({typeName:T.ZodNever,...Z(e)});var Mr=class extends V{_parse(t){if(this._getType(t)!==O.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.void,received:n.parsedType}),D}return ge(t.data)}};Mr.create=e=>new Mr({typeName:T.ZodVoid,...Z(e)});var vt=class e extends V{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==O.array)return E(r,{code:k.invalid_type,expected:O.array,received:r.parsedType}),D;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&(E(r,{code:i?k.too_big:k.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(E(r,{code:k.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(E(r,{code:k.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new Fe(r,i,r.path,o)))).then(i=>me.mergeArray(n,i));let s=[...r.data].map((i,o)=>a.type._parseSync(new Fe(r,i,r.path,o)));return me.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:R.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:R.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:R.toString(r)}})}nonempty(t){return this.min(1,t)}};vt.create=(e,t)=>new vt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...Z(t)});function Pr(e){if(e instanceof Ae){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=je.create(Pr(n))}return new Ae({...e._def,shape:()=>t})}else return e instanceof vt?new vt({...e._def,type:Pr(e.element)}):e instanceof je?je.create(Pr(e.unwrap())):e instanceof st?st.create(Pr(e.unwrap())):e instanceof at?at.create(e.items.map(t=>Pr(t))):e}var Ae=class e extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=J.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==O.object){let u=this._getOrReturnCtx(t);return E(u,{code:k.invalid_type,expected:O.object,received:u.parsedType}),D}let{status:n,ctx:a}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof qe&&this._def.unknownKeys==="strip"))for(let u in a.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let f=s[u],p=a.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new Fe(a,p,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof qe){let u=this._def.unknownKeys;if(u==="passthrough")for(let f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:a.data[f]}});else if(u==="strict")o.length>0&&(E(a,{code:k.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let f of o){let p=a.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new Fe(a,p,a.path,f)),alwaysSet:f in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let u=[];for(let f of c){let p=await f.key,g=await f.value;u.push({key:p,value:g,alwaysSet:f.alwaysSet})}return u}).then(u=>me.mergeObjectSync(n,u)):me.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return R.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:R.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of J.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of J.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Pr(this)}partial(t){let r={};for(let n of J.objectKeys(this.shape)){let a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of J.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof je;)s=s._def.innerType;r[n]=s}return new e({...this._def,shape:()=>r})}keyof(){return Zo(J.objectKeys(this.shape))}};Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:qe.create(),typeName:T.ZodObject,...Z(t)});Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:qe.create(),typeName:T.ZodObject,...Z(t)});Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:qe.create(),typeName:T.ZodObject,...Z(t)});var rr=class extends V{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function a(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(o=>new Ee(o.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(c=>new Ee(c));return E(r,{code:k.invalid_union,unionErrors:o}),D}}get options(){return this._def.options}};rr.create=(e,t)=>new rr({options:e,typeName:T.ZodUnion,...Z(t)});var yt=e=>e instanceof ar?yt(e.schema):e instanceof ze?yt(e.innerType()):e instanceof sr?[e.value]:e instanceof ir?e.options:e instanceof or?J.objectValues(e.enum):e instanceof cr?yt(e._def.innerType):e instanceof er?[void 0]:e instanceof tr?[null]:e instanceof je?[void 0,...yt(e.unwrap())]:e instanceof st?[null,...yt(e.unwrap())]:e instanceof fn||e instanceof lr?yt(e.unwrap()):e instanceof ur?yt(e._def.innerType):[],sa=class e extends V{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.object)return E(r,{code:k.invalid_type,expected:O.object,received:r.parsedType}),D;let n=this.discriminator,a=r.data[n],s=this.optionsMap.get(a);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let a=new Map;for(let s of r){let i=yt(s.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(a.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);a.set(o,s)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:a,...Z(n)})}};function ss(e,t){let r=nt(e),n=nt(t);if(e===t)return{valid:!0,data:e};if(r===O.object&&n===O.object){let a=J.objectKeys(t),s=J.objectKeys(e).filter(o=>a.indexOf(o)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(let o of s){if(o==="__proto__")continue;let c=ss(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===O.array&&n===O.array){if(e.length!==t.length)return{valid:!1};let a=[];for(let s=0;s<e.length;s++){let i=e[s],o=t[s],c=ss(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===O.date&&n===O.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nr=class extends V{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=(s,i)=>{if(na(s)||na(i))return D;let o=ss(s.value,i.value);return o.valid?((aa(s)||aa(i))&&r.dirty(),{status:r.value,value:o.data}):(E(n,{code:k.invalid_intersection_types}),D)};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,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};nr.create=(e,t,r)=>new nr({left:e,right:t,typeName:T.ZodIntersection,...Z(r)});var at=class e extends V{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.array)return E(n,{code:k.invalid_type,expected:O.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new Fe(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>me.mergeArray(r,i)):me.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};at.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new at({items:e,typeName:T.ZodTuple,rest:null,...Z(t)})};var ia=class e extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.object)return E(n,{code:k.invalid_type,expected:O.object,received:n.parsedType}),D;let a=[],s=this._def.keyType,i=this._def.valueType;for(let o in n.data)a.push({key:s._parse(new Fe(n,o,n.path,o)),value:i._parse(new Fe(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?me.mergeObjectAsync(r,a):me.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof V?new e({keyType:t,valueType:r,typeName:T.ZodRecord,...Z(n)}):new e({keyType:Pt.create(),valueType:t,typeName:T.ZodRecord,...Z(r)})}},$r=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.map)return E(n,{code:k.invalid_type,expected:O.map,received:n.parsedType}),D;let a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new Fe(n,o,n.path,[u,"key"])),value:s._parse(new Fe(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return D;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return D;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}}}};$r.create=(e,t,r)=>new $r({valueType:t,keyType:e,typeName:T.ZodMap,...Z(r)});var Dr=class e extends V{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.set)return E(n,{code:k.invalid_type,expected:O.set,received:n.parsedType}),D;let a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(E(n,{code:k.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(E(n,{code:k.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let f of c){if(f.status==="aborted")return D;f.status==="dirty"&&r.dirty(),u.add(f.value)}return{status:r.value,value:u}}let o=[...n.data.values()].map((c,u)=>s._parse(new Fe(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,r){return new e({...this._def,minSize:{value:t,message:R.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:R.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Dr.create=(e,t)=>new Dr({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...Z(t)});var oa=class e extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.function)return E(r,{code:k.invalid_type,expected:O.function,received:r.parsedType}),D;function n(o,c){return dn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ir(),gt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function a(o,c){return dn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ir(),gt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Mt){let o=this;return ge(async function(...c){let u=new Ee([]),f=await o._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),p=await Reflect.apply(i,this,f);return await o._def.returns._def.type.parseAsync(p,s).catch(h=>{throw u.addIssue(a(p,h)),u})})}else{let o=this;return ge(function(...c){let u=o._def.args.safeParse(c,s);if(!u.success)throw new Ee([n(c,u.error)]);let f=Reflect.apply(i,this,u.data),p=o._def.returns.safeParse(f,s);if(!p.success)throw new Ee([a(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:at.create(t).rest(_t.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,r,n){return new e({args:t||at.create([]).rest(_t.create()),returns:r||_t.create(),typeName:T.ZodFunction,...Z(n)})}},ar=class extends V{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ar.create=(e,t)=>new ar({getter:e,typeName:T.ZodLazy,...Z(t)});var sr=class extends V{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};sr.create=(e,t)=>new sr({value:e,typeName:T.ZodLiteral,...Z(t)});function Zo(e,t){return new ir({values:e,typeName:T.ZodEnum,...Z(t)})}var ir=class e extends V{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{expected:J.joinValues(n),received:r.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),D}return ge(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};ir.create=Zo;var or=class extends V{_parse(t){let r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==O.string&&n.parsedType!==O.number){let a=J.objectValues(r);return E(n,{expected:J.joinValues(a),received:n.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let a=J.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:a}),D}return ge(t.data)}get enum(){return this._def.values}};or.create=(e,t)=>new or({values:e,typeName:T.ZodNativeEnum,...Z(t)});var Mt=class extends V{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:O.promise,received:r.parsedType}),D;let n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return ge(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Mt.create=(e,t)=>new Mt({type:e,typeName:T.ZodPromise,...Z(t)});var ze=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){let i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Ht(c.value):r.value==="dirty"?Ht(c.value):c});{if(r.value==="aborted")return D;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?Ht(o.value):r.value==="dirty"?Ht(o.value):o}}if(a.type==="refinement"){let i=o=>{let c=a.refinement(o,s);if(n.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(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Nt(i))return D;let o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Nt(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):D);J.assertNever(a)}};ze.create=(e,t,r)=>new ze({schema:e,typeName:T.ZodEffects,effect:t,...Z(r)});ze.createWithPreprocess=(e,t,r)=>new ze({schema:t,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...Z(r)});var je=class extends V{_parse(t){return this._getType(t)===O.undefined?ge(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};je.create=(e,t)=>new je({innerType:e,typeName:T.ZodOptional,...Z(t)});var st=class extends V{_parse(t){return this._getType(t)===O.null?ge(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};st.create=(e,t)=>new st({innerType:e,typeName:T.ZodNullable,...Z(t)});var cr=class extends V{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};cr.create=(e,t)=>new cr({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Z(t)});var ur=class extends V{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Nr(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ee(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Ee(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ur.create=(e,t)=>new ur({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Z(t)});var Lr=class extends V{_parse(t){if(this._getType(t)!==O.nan){let n=this._getOrReturnCtx(t);return E(n,{code:k.invalid_type,expected:O.nan,received:n.parsedType}),D}return{status:"valid",value:t.data}}};Lr.create=e=>new Lr({typeName:T.ZodNaN,...Z(e)});var ml=Symbol("zod_brand"),fn=class extends V{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},pn=class e extends V{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),Ht(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:T.ZodPipeline})}},lr=class extends V{_parse(t){let r=this._def.innerType._parse(t),n=a=>(Nt(a)&&(a.value=Object.freeze(a.value)),a);return Nr(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}};lr.create=(e,t)=>new lr({innerType:e,typeName:T.ZodReadonly,...Z(t)});function jo(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Uo(e,t={},r){return e?Rt.create().superRefine((n,a)=>{let s=e(n);if(s instanceof Promise)return s.then(i=>{if(!i){let o=jo(t,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){let i=jo(t,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):Rt.create()}var hl={object:Ae.lazycreate},T;(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"})(T||(T={}));var gl=(e,t={message:`Input not instance of ${e.name}`})=>Uo(r=>r instanceof e,t),Vo=Pt.create,Wo=Kt.create,yl=Lr.create,_l=Yt.create,Go=Xt.create,vl=Qt.create,bl=Rr.create,wl=er.create,xl=tr.create,kl=Rt.create,Tl=_t.create,Sl=qe.create,El=Mr.create,Al=vt.create,Ol=Ae.create,Cl=Ae.strictCreate,Il=rr.create,Nl=sa.create,Pl=nr.create,Rl=at.create,Ml=ia.create,$l=$r.create,Dl=Dr.create,Ll=oa.create,jl=ar.create,Fl=sr.create,zl=ir.create,Bl=or.create,Zl=Mt.create,Ul=ze.create,Vl=je.create,Wl=st.create,Gl=ze.createWithPreprocess,Jl=pn.create,ql=()=>Vo().optional(),Hl=()=>Wo().optional(),Kl=()=>Go().optional(),Yl={string:(e=>Pt.create({...e,coerce:!0})),number:(e=>Kt.create({...e,coerce:!0})),boolean:(e=>Xt.create({...e,coerce:!0})),bigint:(e=>Yt.create({...e,coerce:!0})),date:(e=>Qt.create({...e,coerce:!0}))};var Xl=D;function is(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(r.items=j(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&H(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&H(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(r,"minItems",e.exactLength.value,e.exactLength.message,t),H(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function os(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,t):H(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,t):H(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,t));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,t)}return r}function cs(){return{type:"boolean"}}function mn(e,t){return j(e.type._def,t)}var us=(e,t)=>j(e.innerType._def,t);function ca(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>ca(e,t,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ql(e,t)}}var Ql=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":H(r,"minimum",n.value,n.message,t);break;case"max":H(r,"maximum",n.value,n.message,t)}return r};function ls(e,t){return{...j(e.innerType._def,t),default:e.defaultValue()}}function ds(e,t){return t.effectStrategy==="input"?j(e.schema._def,t):ne(t)}function fs(e){return{type:"string",enum:Array.from(e.values)}}var ed=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function ps(e,t){let r=[j(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),j(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,a=[];return r.forEach(s=>{if(ed(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function ms(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var hs,Be={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:()=>(hs===void 0&&(hs=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hs),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 hn(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":He(r,"email",n.message,t);break;case"format:idn-email":He(r,"idn-email",n.message,t);break;case"pattern:zod":xe(r,Be.email,n.message,t)}break;case"url":He(r,"uri",n.message,t);break;case"uuid":He(r,"uuid",n.message,t);break;case"regex":xe(r,n.regex,n.message,t);break;case"cuid":xe(r,Be.cuid,n.message,t);break;case"cuid2":xe(r,Be.cuid2,n.message,t);break;case"startsWith":xe(r,RegExp(`^${gs(n.value,t)}`),n.message,t);break;case"endsWith":xe(r,RegExp(`${gs(n.value,t)}$`),n.message,t);break;case"datetime":He(r,"date-time",n.message,t);break;case"date":He(r,"date",n.message,t);break;case"time":He(r,"time",n.message,t);break;case"duration":He(r,"duration",n.message,t);break;case"length":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":xe(r,RegExp(gs(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&He(r,"ipv4",n.message,t),n.version!=="v4"&&He(r,"ipv6",n.message,t);break;case"base64url":xe(r,Be.base64url,n.message,t);break;case"jwt":xe(r,Be.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&xe(r,Be.ipv4Cidr,n.message,t),n.version!=="v4"&&xe(r,Be.ipv6Cidr,n.message,t);break;case"emoji":xe(r,Be.emoji(),n.message,t);break;case"ulid":xe(r,Be.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":He(r,"binary",n.message,t);break;case"contentEncoding:base64":H(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":xe(r,Be.base64,n.message,t)}break;case"nanoid":xe(r,Be.nanoid,n.message,t)}return r}function gs(e,t){return t.patternStrategy==="escape"?rd(e):e}var td=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rd(e){let t="";for(let r=0;r<e.length;r++)td.has(e[r])||(t+="\\"),t+=e[r];return t}function He(e,t,r,n){e.format||e.anyOf?.some(a=>a.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.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,...r&&n.errorMessages&&{errorMessage:{format:r}}})):H(e,"format",t,r,n)}function xe(e,t,r,n){e.pattern||e.allOf?.some(a=>a.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.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:Jo(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):H(e,"pattern",Jo(t,n),r,n)}function Jo(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
14
+ ]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
15
+ ]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
16
+ `:`[${n[c]}\r
17
+ ]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{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`),e.source}return a}function gn(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===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,a)=>({...n,[a]:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??ne(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:n,...a}=hn(e.keyType._def,t);return{...r,propertyNames:a}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...a}=mn(e.keyType._def,t);return{...r,propertyNames:a}}}return r}function ys(e,t){return t.mapStrategy==="record"?gn(e,t):{type:"array",maxItems:125,items:{type:"array",items:[j(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ne(t),j(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ne(t)],minItems:2,maxItems:2}}}function _s(e){let t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),n=Array.from(new Set(r.map(a=>typeof a)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:r}}function vs(e){return e.target==="openAi"?void 0:{not:ne({...e,currentPath:[...e.currentPath,"not"]})}}function bs(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var jr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ws(e,t){if(t.target==="openApi3")return qo(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in jr&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((a,s)=>{let i=jr[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((a,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;default:return a}},[]);if(n.length===r.length){let a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return qo(e,t)}var qo=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,a)=>j(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function xs(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:jr[e.innerType._def.typeName],nullable:!0}:{type:[jr[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=j(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ks(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",ra(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,t):H(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,t):H(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,t));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,t)}return r}function Ts(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},a=[],s=e.shape();for(let o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let u=ad(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let f=j(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});f!==void 0&&(n.properties[o]=f,u||a.push(o))}a.length&&(n.required=a);let i=nd(e,t);return i!==void 0&&(n.additionalProperties=i),n}function nd(e,t){if(e.catchall._def.typeName!=="ZodNever")return j(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 ad(e){try{return e.isOptional()}catch{return!0}}var Ss=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return j(e.innerType._def,t);let r=j(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ne(t)},r]}:ne(t)};var Es=(e,t)=>{if(t.pipeStrategy==="input")return j(e.in._def,t);if(t.pipeStrategy==="output")return j(e.out._def,t);let r=j(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,j(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(n=>n!==void 0)}};function As(e,t){return j(e.type._def,t)}function Os(e,t){let r={type:"array",uniqueItems:!0,items:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&H(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&H(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function Cs(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>j(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>j(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Is(e){return{not:ne(e)}}function Ns(e){return ne(e)}var Ps=(e,t)=>j(e.innerType._def,t);var Rs=(e,t,r)=>{switch(t){case T.ZodString:return hn(e,r);case T.ZodNumber:return ks(e,r);case T.ZodObject:return Ts(e,r);case T.ZodBigInt:return os(e,r);case T.ZodBoolean:return cs();case T.ZodDate:return ca(e,r);case T.ZodUndefined:return Is(r);case T.ZodNull:return bs(r);case T.ZodArray:return is(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return ws(e,r);case T.ZodIntersection:return ps(e,r);case T.ZodTuple:return Cs(e,r);case T.ZodRecord:return gn(e,r);case T.ZodLiteral:return ms(e,r);case T.ZodEnum:return fs(e);case T.ZodNativeEnum:return _s(e);case T.ZodNullable:return xs(e,r);case T.ZodOptional:return Ss(e,r);case T.ZodMap:return ys(e,r);case T.ZodSet:return Os(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return As(e,r);case T.ZodNaN:case T.ZodNever:return vs(r);case T.ZodEffects:return ds(e,r);case T.ZodAny:return ne(r);case T.ZodUnknown:return Ns(r);case T.ZodDefault:return ls(e,r);case T.ZodBranded:return mn(e,r);case T.ZodReadonly:return Ps(e,r);case T.ZodCatch:return us(e,r);case T.ZodPipeline:return Es(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(t)}};function j(e,t,r=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,r);if(o!==ts)return o}if(n&&!r){let o=sd(n,t);if(o!==void 0)return o}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let s=Rs(e,e.typeName,t),i=typeof s=="function"?j(s(),t):s;if(i&&id(e,t,i),t.postProcess){let o=t.postProcess(i,e,t);return a.jsonSchema=i,o}return a.jsonSchema=i,i}var sd=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ln(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ne(t)):t.$refStrategy==="seen"?ne(t):void 0}},id=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var Ms=e=>{let t=rs(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var $s=(e,t)=>{let r=Ms(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,f])=>({...c,[u]:j(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ne(r)}),{}):void 0,a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=j(e._def,a===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,a]},!1)??ne(r),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let o=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var by=M({isSerializableSchema:()=>dr,isStandardJsonSchema:()=>ua,isStandardSchema:()=>Ho});function Ho(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 ua(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 dr(e){return Ho(e)&&ua(e)}function it(e,t){let r=typeof e;if(r!==typeof t)return!1;let n=Array.isArray(e),a=Array.isArray(t);if(n!==a)return!1;if(n){let s=e.length;if(s!==t.length)return!1;for(let i=0;i<s;i++)if(!it(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(let c of s)if(!Object.prototype.hasOwnProperty.call(t,c)||!it(e[c],t[c]))return!1;return!0}return e===t}function Re(e){return encodeURI(od(e)).replace(/#/g,"%23")}function od(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var cd=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,ud=/^%[0-9A-Fa-f]{2}$/,ld=/^[A-Za-z0-9._~-]$/;function dd(e){let t="";for(let r=0;r<e.length;){let n=e[r],a=e.slice(r,r+3);if(n==="%"&&ud.test(a)){let i=String.fromCharCode(parseInt(a.slice(1),16));t+=ld.test(i)?i:a.toUpperCase(),r+=3;continue}let s=String.fromCodePoint(e.codePointAt(r));t+=cd.test(s)?s:encodeURIComponent(s),r+=s.length}return t}function la(e,t){let r=new URL(e,t.href);return r.hash=r.hash?dd(r.hash.slice(1)):"",r}var fd={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},pd={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},md={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!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},hd=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 Ke(e,t=Object.create(null),r=hd,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=la(s,r);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?r=i:Ke(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0&&t[a]!==e)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let s=la(e.$ref,r);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=la(e.$recursiveRef,r);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=la("#"+e.$anchor,r);t[s.href]=e}for(let s in e){if(md[s])continue;let i=`${n}/${Re(s)}`,o=e[s];if(Array.isArray(o)){if(fd[s]){let c=o.length;for(let u=0;u<c;u++)Ke(o[u],t,r,`${i}/${u}`)}}else if(pd[s])for(let c in o)Ke(o[c],t,r,`${i}/${Re(c)}`);else Ke(o,t,r,i)}return t}var gd=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yd=[0,31,28,31,30,31,30,31,31,30,31,30,31],_d=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,Ko=/^(?=.{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,vd=/^(?:[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,bd=/^(?:(?:[^\x00-\x20\x7f"<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,wd=/^(?:(?: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,xd=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,kd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Td=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Sd=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Ed=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Ad=e=>{let t=e.match(Ed);if(!t)return!1;let r=t[1],n=t[2];if(!r||!n||r.length>64||n.length>253||r[0]!=='"'&&(r[0]==="."||r.endsWith(".")||r.includes("..")))return!1;if(n.startsWith("[")&&n.endsWith("]")){let a=n.slice(1,-1);return/^ipv6:/i.test(a)?Xo.test(a.slice(5)):Yo.test(a)}return Ko.test(n)},Yo=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xo=/^((([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,Od=e=>/^P(?:\d+W|(?:(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function ot(e){return e.test.bind(e)}var Ds={date:Qo,time:ec.bind(void 0,!0),"date-time":Nd,duration:Od,uri:Md,"uri-reference":ot(vd),"uri-template":ot(bd),url:ot(wd),email:Ad,hostname:ot(Ko),ipv4:ot(Yo),ipv6:ot(Xo),regex:Dd,uuid:ot(xd),"json-pointer":ot(kd),"json-pointer-uri-fragment":ot(Td),"relative-json-pointer":ot(Sd)};function Cd(e){return e%4===0&&(e%100!==0||e%400===0)}function Qo(e){let t=e.match(gd);if(!t)return!1;let r=t[1],n=t[2],a=t[3];if(!r||!n||!a)return!1;let s=+r,i=+n,o=+a,c=i==2&&Cd(s)?29:yd[i];return i>=1&&i<=12&&o>=1&&c!==void 0&&o<=c}function ec(e,t){let r=t.match(_d);if(!r)return!1;let n=r[1],a=r[2],s=r[3];if(!n||!a||!s)return!1;let i=+n,o=+a,c=+s,u=r[5],f=r[6],p=+(r[7]??0),g=+(r[8]??0);if(i>23||o>59||c>60||p>23||g>59||e&&u===void 0)return!1;if(c<60)return!0;let h=f==="+"?1:f==="-"?-1:0;return(i*60+o-h*(p*60+g)+1440)%1440===1439}var Id=/t|\s/i;function Nd(e){let[t,r,n]=e.split(Id);return t!==void 0&&r!==void 0&&n===void 0&&Qo(t)&&ec(!0,r)}var Pd=/\/|:/,Rd=/^(?:[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 Md(e){return Pd.test(e)&&Rd.test(e)}var $d=/[^\\]\\Z/;function Dd(e){if($d.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function tc(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}function fr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function rc(e){let t=Math.abs(e).toString().split("e"),r=t[0],n=t[1]??"0",a=r.indexOf("."),s=a===-1?0:r.length-a-1;return[BigInt(r.replace(".","")),Number(n)-s]}function Ld(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[r,n]=rc(e),[a,s]=rc(t),i=n-s;return i>=0?r*10n**BigInt(i)%a===0n:r%(a*10n**BigInt(-i))===0n}function re(e,t,r="2019-09",n=Ke(t),a=!0,s=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,f;switch(u){case"boolean":case"number":case"string":f=u;break;case"object":e===null?f="null":Array.isArray(e)?f="array":f="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:p,$recursiveRef:g,$recursiveAnchor:h,type:m,const:v,enum:b,required:x,not:I,anyOf:S,allOf:L,oneOf:W,if:ae,then:_e,else:y,format:Ve,properties:dt,patternProperties:ee,additionalProperties:kt,unevaluatedProperties:Ur,minProperties:Tt,maxProperties:hr,propertyNames:K,dependentRequired:Vr,dependentSchemas:gr,dependencies:jt,prefixItems:We,items:ft,additionalItems:Wr,unevaluatedItems:Gr,contains:Jr,minContains:Ge,maxContains:d,minItems:l,maxItems:w,uniqueItems:_,minimum:G,maximum:X,exclusiveMinimum:le,exclusiveMaximum:ie,multipleOf:ve,minLength:$e,maxLength:oe,pattern:Qe,__absolute_ref__:yr,__absolute_recursive_ref__:On}=t,A=[];if(h===!0&&s===null&&(s=t),g==="#"){let B=s===null?n[On]:s,$=`${o}/$recursiveRef`,U=re(e,s===null?t:s,r,n,a,B,i,$,c);U.valid||A.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...U.errors)}if(p!==void 0){let $=n[yr||p];if($===void 0){let C=`Unresolved $ref "${p}".`;throw yr&&yr!==p&&(C+=` Absolute URI "${yr}".`),C+=`
18
+ Known schemas:
19
+ - ${Object.keys(n).join(`
20
+ - `)}`,new Error(C)}let U=`${o}/$ref`,P=re(e,$,r,n,a,s,i,U,c);if(P.valid||A.push({instanceLocation:i,keyword:"$ref",keywordLocation:U,error:"A subschema had errors."},...P.errors),r==="4"||r==="7")return{valid:A.length===0,errors:A}}if(Array.isArray(m)){let B=m.length,$=!1;for(let U=0;U<B;U++)if(f===m[U]||m[U]==="integer"&&f==="number"&&e%1===0&&e===e){$=!0;break}$||A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(f!=="number"||e%1||e!==e)&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m}".`}):m!==void 0&&f!==m&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m}".`});if(v!==void 0&&(f==="object"||f==="array"?it(e,v)||A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),b!==void 0&&(f==="object"||f==="array"?b.some(B=>it(e,B))||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(B=>e===B)||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),I!==void 0){let B=`${o}/not`;re(e,I,r,n,a,s,i,B).valid&&A.push({instanceLocation:i,keyword:"not",keywordLocation:B,error:'Instance matched "not" schema.'})}let Ft=[];if(S!==void 0){let B=`${o}/anyOf`,$=A.length,U=!1;for(let[P,C]of S.entries()){let z=Object.create(c),F=re(e,C,r,n,a,h===!0?s:null,i,`${B}/${P}`,z);A.push(...F.errors),U=U||F.valid,F.valid&&Ft.push(z)}U?A.length=$:A.splice($,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:B,error:"Instance does not match any subschemas."})}if(L!==void 0){let B=`${o}/allOf`,$=A.length,U=!0;for(let[P,C]of L.entries()){let z=Object.create(c),F=re(e,C,r,n,a,h===!0?s:null,i,`${B}/${P}`,z);A.push(...F.errors),U=U&&F.valid,F.valid&&Ft.push(z)}U?A.length=$:A.splice($,0,{instanceLocation:i,keyword:"allOf",keywordLocation:B,error:"Instance does not match every subschema."})}if(W!==void 0){let B=`${o}/oneOf`,$=A.length,U=W.filter((P,C)=>{let z=Object.create(c),F=re(e,P,r,n,a,h===!0?s:null,i,`${B}/${C}`,z);return A.push(...F.errors),F.valid&&Ft.push(z),F.valid}).length;U===1?A.length=$:A.splice($,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:B,error:`Instance does not match exactly one subschema (${U} matches).`})}if((f==="object"||f==="array")&&Object.assign(c,...Ft),ae!==void 0){let B=`${o}/if`,$=Object.create(null);if(re(e,ae,r,n,a,s,i,B,$).valid){if(Object.assign(c,$),_e!==void 0){let P=re(e,_e,r,n,a,s,i,`${o}/then`,c);P.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:B,error:'Instance does not match "then" schema.'},...P.errors)}}else if(y!==void 0){let P=re(e,y,r,n,a,s,i,`${o}/else`,c);P.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:B,error:'Instance does not match "else" schema.'},...P.errors)}}if(f==="object"){if(x!==void 0)for(let P of x)fr(e,P)||A.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${P}".`});let B=Object.keys(e);if(Tt!==void 0&&B.length<Tt&&A.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${Tt} properties.`}),hr!==void 0&&B.length>hr&&A.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${hr} properties.`}),K!==void 0){let P=`${o}/propertyNames`;for(let C in e){let z=`${i}/${Re(C)}`,F=re(C,K,r,n,a,s,z,P);F.valid||A.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:P,error:`Property name "${C}" does not match schema.`},...F.errors)}}if(Vr!==void 0){let P=`${o}/dependantRequired`;for(let C in Vr)if(fr(e,C)){let z=Vr[C];for(let F of z)fr(e,F)||A.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:P,error:`Instance has "${C}" but does not have "${F}".`})}}if(gr!==void 0)for(let[P,C]of Object.entries(gr)){let z=`${o}/dependentSchemas`;if(fr(e,P)){let F=re(e,C,r,n,a,s,i,`${z}/${Re(P)}`,c);F.valid||A.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:z,error:`Instance has "${P}" but does not match dependant schema.`},...F.errors)}}if(jt!==void 0){let P=`${o}/dependencies`;for(let C in jt)if(fr(e,C)){let z=jt[C];if(Array.isArray(z))for(let F of z)fr(e,F)||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:P,error:`Instance has "${C}" but does not have "${F}".`});else{let F=re(e,z,r,n,a,s,i,`${P}/${Re(C)}`);F.valid||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:P,error:`Instance has "${C}" but does not match dependant schema.`},...F.errors)}}}let $=Object.create(null),U=!1;if(dt!==void 0){let P=`${o}/properties`;for(let[C,z]of Object.entries(dt)){if(!fr(e,C))continue;let F=`${i}/${Re(C)}`,fe=re(e[C],z,r,n,a,s,F,`${P}/${Re(C)}`);if($[C]=!0,fe.valid)c[C]=!0;else if(U=a,A.push({instanceLocation:i,keyword:"properties",keywordLocation:P,error:`Property "${C}" does not match schema.`},...fe.errors),U)break}}if(!U&&ee!==void 0){let P=`${o}/patternProperties`;for(let[C,z]of Object.entries(ee)){let F=new RegExp(C,"u");for(let fe in e){if(!F.test(fe))continue;let ai=`${i}/${Re(fe)}`,si=re(e[fe],z,r,n,a,s,ai,`${P}/${Re(C)}`);$[fe]=!0,si.valid?c[fe]=!0:(U=a,A.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:P,error:`Property "${fe}" matches pattern "${C}" but does not match associated schema.`},...si.errors))}}}if(!U&&kt!==void 0){let P=`${o}/additionalProperties`;for(let C in e){if($[C])continue;let z=`${i}/${Re(C)}`,F=re(e[C],kt,r,n,a,s,z,P);F.valid?c[C]=!0:(U=a,A.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:P,error:`Property "${C}" does not match additional properties schema.`},...F.errors))}}else if(!U&&Ur!==void 0){let P=`${o}/unevaluatedProperties`;for(let C in e)if(!c[C]){let z=`${i}/${Re(C)}`,F=re(e[C],Ur,r,n,a,s,z,P);F.valid?c[C]=!0:A.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:P,error:`Property "${C}" does not match unevaluated properties schema.`},...F.errors)}}}else if(f==="array"){w!==void 0&&e.length>w&&A.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${w}).`}),l!==void 0&&e.length<l&&A.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${l}).`});let B=e.length,$=0,U=!1;if(We!==void 0){let P=`${o}/prefixItems`,C=Math.min(We.length,B);for(;$<C;$++){let z=re(e[$],We[$],r,n,a,s,`${i}/${$}`,`${P}/${$}`);if(c[$]=!0,!z.valid&&(U=a,A.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:P,error:"Items did not match schema."},...z.errors),U))break}}if(ft!==void 0){let P=`${o}/items`;if(Array.isArray(ft)){let C=Math.min(ft.length,B);for(;$<C;$++){let z=re(e[$],ft[$],r,n,a,s,`${i}/${$}`,`${P}/${$}`);if(c[$]=!0,!z.valid&&(U=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:P,error:"Items did not match schema."},...z.errors),U))break}}else for(;$<B;$++){let C=re(e[$],ft,r,n,a,s,`${i}/${$}`,P);if(c[$]=!0,!C.valid&&(U=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:P,error:"Items did not match schema."},...C.errors),U))break}if(!U&&Wr!==void 0){let C=`${o}/additionalItems`;for(;$<B;$++){let z=re(e[$],Wr,r,n,a,s,`${i}/${$}`,C);c[$]=!0,z.valid||(U=a,A.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:C,error:"Items did not match additional items schema."},...z.errors))}}}if(Jr!==void 0)if(B===0&&Ge===void 0)A.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ge!==void 0&&B<Ge)A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${B}) than minContains (${Ge}).`});else{let P=`${o}/contains`,C=A.length,z=0;for(let F=0;F<B;F++){let fe=re(e[F],Jr,r,n,a,s,`${i}/${F}`,P);fe.valid?(c[F]=!0,z++):A.push(...fe.errors)}z>=(Ge||0)&&(A.length=C),Ge===void 0&&z===0?A.splice(C,0,{instanceLocation:i,keyword:"contains",keywordLocation:P,error:"Array does not contain item matching schema."}):Ge!==void 0&&z<Ge?A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Ge} items matching schema. Only ${z} items were found.`}):d!==void 0&&z>d&&A.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${d} items matching schema. ${z} items were found.`})}if(!U&&Gr!==void 0){let P=`${o}/unevaluatedItems`;for($;$<B;$++){if(c[$])continue;let C=re(e[$],Gr,r,n,a,s,`${i}/${$}`,P);c[$]=!0,C.valid||A.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:P,error:"Items did not match unevaluated items schema."},...C.errors)}}if(_)for(let P=0;P<B;P++){let C=e[P],z=typeof C=="object"&&C!==null;for(let F=0;F<B;F++){if(P===F)continue;let fe=e[F];(C===fe||z&&(typeof fe=="object"&&fe!==null)&&it(C,fe))&&(A.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${P} and ${F}.`}),P=Number.MAX_SAFE_INTEGER,F=Number.MAX_SAFE_INTEGER)}}}else if(f==="number")r==="4"?(G!==void 0&&(le===!0&&e<=G||e<G)&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${le?"or equal to ":""} ${G}.`}),X!==void 0&&(ie===!0&&e>=X||e>X)&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${ie?"or equal to ":""} ${X}.`})):(G!==void 0&&e<G&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${G}.`}),X!==void 0&&e>X&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${X}.`}),le!==void 0&&e<=le&&A.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${le}.`}),ie!==void 0&&e>=ie&&A.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ie}.`})),ve!==void 0&&(Ld(e,ve)||A.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${ve}.`}));else if(f==="string"){let B=$e===void 0&&oe===void 0?0:tc(e);$e!==void 0&&B<$e&&A.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${B} < ${$e}).`}),oe!==void 0&&B>oe&&A.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${B} > ${oe}).`}),Qe!==void 0&&!new RegExp(Qe,"u").test(e)&&A.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),Ve!==void 0&&Ds[Ve]&&!Ds[Ve](e)&&A.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${Ve}".`})}return{valid:A.length===0,errors:A}}var da=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Ke(t)}validate(t){return re(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Ke(t,this.lookup)}};var Vy=M({Validator:()=>da,deepCompareStrict:()=>it,toJsonSchema:()=>ct,validatesOnlyStrings:()=>Fr}),nc=new WeakMap;function ct(e,t){let r=!t&&e!=null&&typeof e=="object";if(r){let a=nc.get(e);if(a)return a}let n;if(ua(e)&&!te(e))n=e["~standard"].jsonSchema.input({target:"draft-07"});else if(te(e)){let a=ea(e,!0);if(Le(a)){let s=Ar(a,!0);n=Fa(s,t)}else n=Fa(e,t)}else ce(e)?n=$s(e):n=e;return r&&n!=null&&typeof n=="object"&&nc.set(e,n),n}function Fr(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=>Fr(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(r=>Fr(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,r=Ke(e);return r[t]?Fr(r[t]):!1}return!1}var Yy=M({Graph:()=>fa});function jd(e,t){if(e!==void 0&&!qr(e))return e;if(on(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function Fd(e){return on(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...ct(e.data.schema),title:e.data.name}}}var fa=class ic{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=qr(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...Fd(r),...r.metadata!=null?{metadata:r.metadata}:{}})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let a=r??oi(),s={id:a,data:t,name:jd(r,t),metadata:n};return this.nodes[a]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,a){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let s={source:t.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return ac(this)}lastNode(){return sc(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(c=>c.id).every(qr)&&(n="");let a=c=>n?`${n}:${c}`:c;Object.entries(t.nodes).forEach(([c,u])=>{this.nodes[a(c)]={...u,id:a(c)}});let s=t.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...s];let i=t.firstNode(),o=t.lastNode();return[i?{id:a(i.id),data:i.data}:void 0,o?{id:a(o.id),data:o.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&ac(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&sc(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(t).forEach(a=>{r.set(a,(r.get(a)||0)+1)});let n=a=>{let s=t[a];return qr(a)&&r.get(s)===1?s:a};return new ic({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return To(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(t){let r=this.drawMermaid(t);return So(r,{backgroundColor:t?.backgroundColor})}};function ac(e,t=[]){let r=new Set(e.edges.filter(a=>!t.includes(a.source)).map(a=>a.target)),n=[];for(let a of Object.values(e.nodes))!t.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function sc(e,t=[]){let r=new Set(e.edges.filter(a=>!t.includes(a.target)).map(a=>a.source)),n=[];for(let a of Object.values(e.nodes))!t.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function oc(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let a of e)n.enqueue(t.encode(`event: data
21
+ data: ${JSON.stringify(a)}
22
+
23
+ `));n.enqueue(t.encode(`event: end
24
+
25
+ `)),n.close()}});return be.fromReadableStream(r)}function Ls(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}var cc=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function pa(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function js(e){return e!=null&&typeof e=="object"&&typeof e.next=="function"}async function uc(e,t){try{let r=await e.next();for(;!r.done;)await t?.(r.value),r=await e.next();return r.value}finally{await e.return?.(void 0)}}function*Fs(e,t){for(;;){let{value:r,done:n}=Ce.runWithConfig(ke(e),t.next.bind(t),!0);if(n)break;yield r}}async function*ma(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:a}=await Ce.runWithConfig(ke(e),r.next.bind(t),!0);if(a)break;yield n}}function ue(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var Q=class extends Cn{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new ga({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new $t({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new zs({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(q);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:t},(n,a)=>q(a===0?e:r))}return Array.from({length:t},()=>q(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new ht({maxConcurrency:a,onFailedAttempt:o=>{throw o}}),i=e.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=q(t),n=new Ct({generator:this._streamIterator(e,r),config:r});return await n.setup,be.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=q(e):t=q({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),ue(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let s;try{let i=e.call(this,t,n,a);s=await Ne(i,n.signal)}catch(i){throw await a?.handleChainError(i),i}return await a?.handleChainEnd(ue(s,"output")),s}async _batchWithConfig(e,t,r,n){let a=this._getOptionsList(r??{},t.length),s=await Promise.all(a.map(he)),i=await Promise.all(s.map(async(c,u)=>{let f=await c?.handleChainStart(this.toJSON(),ue(t[u],"input"),a[u].runId,a[u].runType,void 0,void 0,a[u].runName??this.getName());return delete a[u].runId,f})),o;try{let c=e.call(this,t,a,i,n);o=await Ne(c,a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(ue(o,"output")))),o}_concatOutputChunks(e,t){return Pe(e,t)}async*_transformStreamWithConfig(e,t,r){let n,a=!0,s,i=!0,o=q(r),c=await he(o),u=this;async function*f(){for await(let g of e){if(a)if(n===void 0)n=g;else try{n=u._concatOutputChunks(n,g)}catch{n=void 0,a=!1}yield g}}let p;try{let g=await Ua(t.bind(this),f(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName(),void 0,{lc_defers_inputs:!0}),o.signal,o);delete o.runId,p=g.setup;let h=p?.handlers.find(lo),m=g.output;h!==void 0&&p!==void 0&&(m=h.tapOutputIterable(p.runId,m));let v=p?.handlers.find(Wa);v!==void 0&&p!==void 0&&(m=v.tapOutputIterable(p.runId,m));for await(let b of m)if(yield b,i)if(s===void 0)s=b;else try{s=this._concatOutputChunks(s,b)}catch{s=void 0,i=!1}}catch(g){throw await p?.handleChainError(g,void 0,void 0,void 0,{inputs:ue(n,"input")}),g}await p?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:ue(n,"input")})}getGraph(e){let t=new fa,r=t.addNode({name:`${this.getName()}Input`,schema:we.any()}),n=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:we.any()});return t.addEdge(r,n),t.addEdge(n,a),t}pipe(e){return new zr({first:this,last:Me(e)})}pick(e){return this.pipe(new Bs(e))}assign(e){return this.pipe(new _n(new Dt({steps:e})))}async*transform(e,t){let r;for await(let n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,q(t))}async*streamLog(e,t,r){let n=new Gn({...r,autoClose:!1,_schemaFormat:"original"}),a=q(t);yield*this._streamLog(e,n,a)}async*_streamLog(e,t,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let o=n.copy();o.addHandler(t,!0),r.callbacks=o}let a=this.stream(e,r);async function s(){try{let o=await a;for await(let c of o){let u=new rt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(u)}}finally{await t.writer.close()}}let i=s();try{for await(let o of t)yield o}finally{await i}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?oc(n):be.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){let n=new fo({...r,autoClose:!1}),a=q(t),s=a.runId??ci();a.runId=s;let i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{let h=i.copy();h.addHandler(n,!0),a.callbacks=h}let o=new AbortController,c=this;async function u(){let h;try{if(a.signal)if("any"in AbortSignal)h=AbortSignal.any([o.signal,a.signal]);else{let b=new AbortController;a.signal.addEventListener("abort",()=>b.abort(),{once:!0}),o.signal.addEventListener("abort",()=>b.abort(),{once:!0}),h=b.signal}else h=o.signal;let m=await c.stream(e,{...a,signal:h}),v=n.tapOutputIterable(s,m);for await(let b of v)if(o.signal.aborted)break}catch(m){throw n.close(),m}finally{await n.finish()}}let f=u();f.catch(()=>{});let p=!1,g;try{for await(let h of n){if(!p){h.data.input=e,p=!0,g=h.run_id,yield h;continue}h.run_id===g&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await f.catch(h=>{if(h!==o.signal.reason)throw h})}}async*_streamEventsV1(e,t,r){let n,a=!1,s=q(t),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new Gn({...r,autoClose:!1,_schemaFormat:"streaming_events"}),f=new wo({...r}),p=this._streamLog(e,u,s);for await(let h of p){if(n?n=n.concat(h):n=Wn.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;let x={...n.state},I={run_id:x.id,event:`on_${x.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};f.includeEvent(I,x.type)&&(yield I)}let m=h.ops.filter(x=>x.path.startsWith("/logs/")).map(x=>x.path.split("/")[2]),v=[...new Set(m)];for(let x of v){let I,S={},L=n.state.logs[x];if(L.end_time===void 0?L.streamed_output.length>0?I="stream":I="start":I="end",I==="start")L.inputs!==void 0&&(S.input=L.inputs);else if(I==="end")L.inputs!==void 0&&(S.input=L.inputs),S.output=L.final_output;else if(I==="stream"){let W=L.streamed_output.length;if(W!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${W} instead. Encountered in: "${L.name}"`);S={chunk:L.streamed_output[0]},L.streamed_output=[]}yield{event:`on_${L.type}_${I}`,name:L.name,run_id:L.id,tags:L.tags,metadata:L.metadata,data:S}}let{state:b}=n;if(b.streamed_output.length>0){let x=b.streamed_output.length;if(x!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${x} instead. Encountered in: "${b.name}"`);let I={chunk:b.streamed_output[0]};b.streamed_output=[];let S={event:`on_${b.type}_stream`,run_id:b.id,tags:i,metadata:o,name:c,data:I};f.includeEvent(S,b.type)&&(yield S)}}let g=n?.state;if(g!==void 0){let h={event:`on_${g.type}_end`,name:c,run_id:g.id,tags:i,metadata:o,data:{output:g.final_output}};f.includeEvent(h,g.type)&&(yield h)}}static isRunnable(e){return on(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new $t({bound:this,config:{},configFactories:[n=>({callbacks:[new qa({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return Zd(this,e)}},$t=class lc extends Q{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=Vt(this.config,...t);return Vt(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new ga({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){let a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(q(s),this.kwargs))):await this._mergeConfig(q(r),this.kwargs);return this.bound.batch(t,a,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(q(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(q(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(q(r),this.kwargs))}streamEvents(t,r,n){let a=this,s=async function*(){yield*a.bound.streamEvents(t,{...await a._mergeConfig(q(r),a.kwargs),version:r.version},n)};return be.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&Q.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new lc({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new qa({config:a,onStart:t,onEnd:r,onError:n})]})]})}},dc=class fc extends Q{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,Y(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new fc({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},ga=class extends $t{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let n=e>1?`retry:attempt:${e}`:void 0;return Y(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return sn(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){let a={};try{await sn(async s=>{let i=e.map((p,g)=>g).filter(p=>a[p.toString()]===void 0||a[p.toString()]instanceof Error),o=i.map(p=>e[p]),c=i.map(p=>this._patchConfigForRetry(s,t?.[p],r?.[p])),u=await super.batch(o,c,{...n,returnExceptions:!0}),f;for(let p=0;p<u.length;p+=1){let g=u[p],h=i[p];g instanceof Error&&f===void 0&&(f=g,f.input=o[p]),a[h.toString()]=g}if(f)throw f;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},zr=class yn extends Q{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;_tracePolicy;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){let{tracePolicy:r,...n}=t;super(n),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags,this._tracePolicy=r}get _runExtra(){return this._tracePolicy?{[Hi]:this._tracePolicy}:void 0}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),ue(t,"input"),n.runId,void 0,void 0,void 0,n?.runName,void 0,this._runExtra);delete n.runId;let s=t,i;try{let o=[this.first,...this.middle];for(let c=0;c<o.length;c+=1){let u=o[c].invoke(s,Y(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));s=await Ne(u,n.signal)}if(n.signal?.aborted)throw Ot(n.signal);i=await this.last.invoke(s,Y(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(ue(i,"output")),i}async batch(t,r,n){let a=this._getOptionsList(r??{},t.length),s=await Promise.all(a.map(he)),i=await Promise.all(s.map(async(c,u)=>{let f=await c?.handleChainStart(this.toJSON(),ue(t[u],"input"),a[u].runId,void 0,void 0,void 0,a[u].runName,void 0,this._runExtra);return delete a[u].runId,f})),o=t;try{for(let c=0;c<this.steps.length;c+=1){let u=this.steps[c].batch(o,i.map((f,p)=>{let g=f?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Y(a[p],{callbacks:g})}),n);o=await Ne(u,a[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map((c,u)=>c?.handleChainEnd(ue(o[u],"output")))),o}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){let n=await he(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),ue(t,"input"),a,void 0,void 0,void 0,s?.runName,void 0,this._runExtra),o=[this.first,...this.middle,this.last],c=!0,u;async function*f(){yield t}try{let p=o[0].transform(f(),Y(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let g=1;g<o.length;g+=1)p=await o[g].transform(p,Y(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${g+1}`)}));for await(let g of p)if(r?.signal?.throwIfAborted(),yield g,c)if(u===void 0)u=g;else try{u=this._concatOutputChunks(u,g)}catch{u=void 0,c=!1}}catch(p){throw await i?.handleChainError(p),p}await i?.handleChainEnd(ue(u,"output"))}getGraph(t){let r=new fa,n=null;return this.steps.forEach((a,s)=>{let i=a.getGraph(t);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);let o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(t){return yn.isRunnableSequence(t)?new yn({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new yn({first:this.first,middle:[...this.middle,this.last],last:Me(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&Q.isRunnable(t)}static from([t,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new yn({...a,first:Me(t),middle:r.slice(0,-1).map(Me),last:Me(r[r.length-1])})}},Dt=class pc extends Q{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=Me(n)}static from(t){return new pc({steps:t})}async invoke(t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let s={};try{let i=Object.entries(this.steps).map(async([o,c])=>{s[o]=await c.invoke(t,Y(n,{callbacks:a?.getChild(`map:key:${o}`)}))});await Ne(Promise.all(i),n.signal)}catch(i){throw await a?.handleChainError(i),i}return await a?.handleChainEnd(s),s}async*_transform(t,r,n){let a={...this.steps},s=Vn(t,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],u)=>{let f=c.transform(s[u],Y(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,f.next().then(p=>({key:o,gen:f,result:p}))]}));for(;i.size;){let o=Promise.race(i.values()),{key:c,result:u,gen:f}=await Ne(o,n?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,f.next().then(p=>({key:c,gen:f,result:p}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let a=q(r),s=new Ct({generator:this.transform(n(),a),config:a});return await s.setup,be.fromAsyncGenerator(s)}},zd=class mc extends Q{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Nn(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),a=await he(n),s=this.func(Y(n,{callbacks:a}),t);return Ne(s,n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),a=await this.invoke(t,r);if(pa(a)){for await(let s of a)n?.signal?.throwIfAborted(),yield s;return}if(cc(a)){for(;;){n?.signal?.throwIfAborted();let s=a.next();if(s.done)break;yield s.value}return}yield a}static from(t){return new mc({func:t})}};function Bd(e){if(Nn(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ze=class hc extends Q{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Nn(t.func))return zd.from(t.func);super(t),Bd(t.func),this.func=t.func}static from(t){return new hc({func:t})}async _invoke(t,r,n){return new Promise((a,s)=>{let i=Y(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});Ce.runWithConfig(ke(i),async()=>{try{let o=await this.func(t,{...i});if(o&&Q.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(pa(o)){let c;for await(let u of ma(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Ls(o)){let c;for(let u of Fs(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}a(o)}catch(o){s(o)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let a;for await(let o of t)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}let s=Y(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),i=await new Promise((o,c)=>{Ce.runWithConfig(ke(s),async()=>{try{o(await this.func(a,{...s,config:s}))}catch(u){c(u)}})});if(i&&Q.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let o=await i.stream(a,s);for await(let c of o)yield c}else if(pa(i))for await(let o of ma(s,i))n?.signal?.throwIfAborted(),yield o;else if(Ls(i))for(let o of Fs(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let a=q(r),s=new Ct({generator:this.transform(n(),a),config:a});return await s.setup,be.fromAsyncGenerator(s)}},gc=class extends Dt{},zs=class extends Q{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let r=q(t),n=await he(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ue(e,"input"),a,void 0,void 0,void 0,s?.runName),o=Y(s,{callbacks:i?.getChild()});return await Ce.runWithConfig(o,async()=>{let c;for(let u of this.runnables()){r?.signal?.throwIfAborted();try{let f=await u.invoke(e,o);return await i?.handleChainEnd(ue(f,"output")),f}catch(f){c===void 0&&(c=f)}}throw c===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(c),c)})}async*_streamIterator(e,t){let r=q(t),n=await he(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ue(e,"input"),a,void 0,void 0,void 0,s?.runName),o,c;for(let f of this.runnables()){r?.signal?.throwIfAborted();let p=Y(s,{callbacks:i?.getChild()});try{let g=await f.stream(e,p);c=ma(p,g);break}catch(g){o===void 0&&(o=g)}}if(c===void 0){let f=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(f),f}let u;try{for await(let f of c){yield f;try{u=u===void 0?u:this._concatOutputChunks(u,f)}catch{u=void 0}}}catch(f){throw await i?.handleChainError(f),f}await i?.handleChainEnd(ue(u,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),a=await Promise.all(n.map(o=>he(o))),s=await Promise.all(a.map(async(o,c)=>{let u=await o?.handleChainStart(this.toJSON(),ue(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u})),i;for(let o of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await o.batch(e,s.map((u,f)=>Y(n[f],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,f)=>u?.handleChainEnd(ue(c[f],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function Me(e){if(typeof e=="function")return new Ze({func:e});if(Q.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=Me(n);return new Dt({steps:t})}else throw new Error(`Expected a Runnable, function or object.
26
+ Instead got an unsupported type.`)}var _n=class extends Q{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof Dt&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){let n=this.mapper.getStepsKeys(),[a,s]=Vn(e),i=this.mapper.transform(s,Y(r,{callbacks:t?.getChild()})),o=i.next();for await(let c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([f])=>!n.includes(f)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(let c of i)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=q(t),a=new Ct({generator:this.transform(r(),n),config:n});return await a.setup,be.fromAsyncGenerator(a)}},Bs=class extends Q{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=q(t),a=new Ct({generator:this.transform(r(),n),config:n});return await a.setup,be.fromAsyncGenerator(a)}},ha=class extends $t{name;description;schema;constructor(e){let t=zr.from([Ze.from(async r=>{let n;if(wr(r))try{n=await It(this.schema,r.args)}catch{throw new xr("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function Zd(e,t){let r=t.name??e.getName(),n=t.description??Or(t.schema);return Cr(t.schema)?new ha({name:r,description:n,schema:we.object({input:we.string()}).transform(a=>a.input),bound:e}):new ha({name:r,description:n,schema:t.schema,bound:e})}var ya=(e,t)=>{let r=[...new Set(t?.map(a=>{if(typeof a=="string")return a;let s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=e.getType();return r.some(a=>a===n)};function wc(e,t){return Array.isArray(e)?yc(e,t):Ze.from(r=>yc(r,e))}function yc(e,t={}){let{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=t,c=[];for(let u of e)if(!(n&&u.name&&n.includes(u.name))){{if(s&&ya(u,s))continue;if(o&&u.id&&o.includes(u.id))continue}a||i||r?(r&&u.name&&r.some(f=>f===u.name)||a&&ya(u,a)||i&&u.id&&i.some(f=>f===u.id))&&c.push(u):c.push(u)}return c}function xc(e){return Array.isArray(e)?_c(e):Ze.from(_c)}function _c(e){if(!e.length)return[];let t=[];for(let r of e){let n=r,a=t.pop();if(!a)t.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())t.push(a,n);else{let s=Ut(a),i=Ut(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
27
+ ${i.content}`),t.push(Vd(o))}}return t}function kc(e,t){if(Array.isArray(e)){let r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return vc(r,t)}else{let r=e;return Ze.from(n=>vc(n,r)).withConfig({runName:"trim_messages"})}}async function vc(e,t){let{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=t;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let f;"getNumTokens"in n?f=async g=>(await Promise.all(g.map(h=>n.getNumTokens(h.content)))).reduce((h,m)=>h+m,0):f=async g=>n(g);let p=Us;if(u&&("splitText"in u?p=u.splitText.bind(u):p=async g=>u(g)),a==="first")return Tc(e,{maxTokens:r,tokenCounter:f,textSplitter:p,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return Ud(e,{maxTokens:r,tokenCounter:f,textSplitter:p,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function Tc(e,t){let{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=t,o=[...e],c=0;for(let u=0;u<o.length;u+=1)if(await n(u>0?o.slice(0,-u):o)<=r){c=o.length-u;break}if(c<o.length&&s){let u=!1;if(Array.isArray(o[c].content)){let f=o[c];if(typeof f.content=="string")throw new Error("Expected content to be an array.");let p=f.content.length,g=s==="last"?[...f.content].reverse():f.content;for(let h=1;h<=p;h+=1){let m=s==="first"?g.slice(0,h):g.slice(-h),v=Object.fromEntries(Object.entries(f).filter(([I])=>I!=="type"&&!I.startsWith("lc_"))),b=Zs(f.getType(),{...v,content:m}),x=[...o.slice(0,c),b];if(await n(x)<=r)o=x,c+=1,u=!0;else break}u&&s==="last"&&(f.content=[...g].reverse())}if(!u){let f=o[c],p;if(Array.isArray(f.content)&&f.content.some(g=>typeof g=="string"||g.type==="text")?p=f.content.find(g=>g.type==="text"&&g.text)?.text:typeof f.content=="string"&&(p=f.content),p){let g=await a(p),h=g.length;s==="last"&&g.reverse();for(let m=0;m<h-1;m+=1)if(g.pop(),f.content=g.join(""),await n([...o.slice(0,c),f])<=r){s==="last"&&(f.content=[...g].reverse().join("")),o=[...o.slice(0,c),f],c+=1;break}}}}if(i){let u=Array.isArray(i)?i:[i];for(;c>0&&!ya(o[c-1],u);)c-=1}return o.slice(0,c)}async function Ud(e,t){let{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=t,o=e.map(f=>{let p=Object.fromEntries(Object.entries(f).filter(([g])=>g!=="type"&&!g.startsWith("lc_")));return Zs(f.getType(),p,kr(f))});if(a){let f=Array.isArray(a)?a:[a];for(;o.length>0&&!ya(o[o.length-1],f);)o=o.slice(0,-1)}let c=n&&o[0]?.getType()==="system",u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await Tc(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}var bc={human:{message:De,messageChunk:tn},ai:{message:Je,messageChunk:pe},system:{message:Bt,messageChunk:Zt},developer:{message:Bt,messageChunk:Zt},tool:{message:St,messageChunk:Kr},function:{message:Qr,messageChunk:en},generic:{message:Yr,messageChunk:Xr},remove:{message:rn,messageChunk:rn}};function Zs(e,t,r){let n,a;switch(e){case"human":r?n=new tn(t):a=new De(t);break;case"ai":if(r){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new pe(s)}else a=new Je(t);break;case"system":r?n=new Zt(t):a=new Bt(t);break;case"developer":r?n=new Zt({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):a=new Bt({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?n=new Kr(t):a=new St(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new en(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");a=new Qr(t)}break;case"generic":if("role"in t)r?n=new Xr(t):a=new Yr(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${e}`)}function Vd(e){let t=e.getType(),r,n=Object.fromEntries(Object.entries(e).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(t in bc&&(r=Zs(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(bc)}`);return r}function Us(e){let t=e.split(`
28
+ `);return Promise.resolve([...t.slice(0,-1).map(r=>`${r}
29
+ `),t[t.length-1]])}function Sc(e,t){let{lc_data:r,...n}=e.additional_kwargs??{},a={...n,lc_source:t.source};t.data!==void 0&&(a.lc_data={...t.data});let{lc_kwargs:s,lc_serializable:i,lc_namespace:o,type:c,...u}=e;return new De({...u,additional_kwargs:a})}function Ec(e){let t=e.additional_kwargs?.lc_source;if(typeof t!="string")return;let r=e.additional_kwargs?.lc_data;return typeof r=="object"&&r!==null&&!Array.isArray(r)?{source:t,data:{...r}}:{source:t}}var Ac=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Oc=["image","video","audio","text-plain","file"];var Cc=["text","reasoning","refusal",...Ac,...Oc];var mv=M({AIMessage:()=>Je,AIMessageChunk:()=>pe,BaseMessage:()=>ki,BaseMessageChunk:()=>Ci,ChatMessage:()=>Yr,ChatMessageChunk:()=>Xr,DEFAULT_MERGE_IGNORE_KEYS:()=>Si,FunctionMessage:()=>Qr,FunctionMessageChunk:()=>en,HumanMessage:()=>De,HumanMessageChunk:()=>tn,KNOWN_BLOCK_TYPES:()=>Cc,RemoveMessage:()=>rn,SystemMessage:()=>Bt,SystemMessageChunk:()=>Zt,ToolMessage:()=>St,ToolMessageChunk:()=>Kr,_isMessageFieldWithRole:()=>Ii,_mergeDicts:()=>Ei,_mergeLists:()=>Ai,_mergeObj:()=>Oi,_mergeStatus:()=>xi,addNotificationMetadata:()=>Sc,coerceMessageLikeToMessage:()=>Et,collapseToolCallChunks:()=>qi,convertToChunk:()=>Ut,convertToOpenAIImageBlock:()=>Mn,convertToProviderContentBlock:()=>vi,defaultTextSplitter:()=>Us,defaultToolCallParser:()=>Ri,filterMessages:()=>wc,getBufferString:()=>Dn,getNotificationMetadata:()=>Ec,iife:()=>Wi,isAIMessage:()=>Tr,isAIMessageChunk:()=>Di,isBase64ContentBlock:()=>Rn,isBaseMessage:()=>Oe,isBaseMessageChunk:()=>kr,isChatMessage:()=>Li,isChatMessageChunk:()=>ji,isDataContentBlock:()=>mi,isDirectToolOutput:()=>$n,isFunctionMessage:()=>Fi,isFunctionMessageChunk:()=>zi,isHumanMessage:()=>Bi,isHumanMessageChunk:()=>Zi,isIDContentBlock:()=>gi,isMessage:()=>bi,isOpenAIToolCallArray:()=>Ti,isPlainTextContentBlock:()=>hi,isSystemMessage:()=>Ui,isSystemMessageChunk:()=>Vi,isToolMessage:()=>Mi,isToolMessageChunk:()=>$i,isURLContentBlock:()=>Pn,mapChatMessagesToStoredMessages:()=>Ji,mapStoredMessageToChatMessage:()=>Ln,mapStoredMessagesToChatMessages:()=>Gi,mergeContent:()=>wi,mergeMessageRuns:()=>xc,mergeResponseMetadata:()=>Ni,mergeUsageMetadata:()=>Pi,parseBase64DataUrl:()=>_i,parseMimeType:()=>yi,trimMessages:()=>kc});var _v=M({ChatModelStream:()=>va,ReasoningContentStream:()=>Rc,TextContentStream:()=>Nc,ToolCallsStream:()=>Pc,UsageMetadataStream:()=>Mc}),Wd=class{events=[];finished=!1;waiters=[];error=null;push(e){this.events.push(e);let t=this.waiters.splice(0);for(let r of t)r()}finish(){this.finished=!0;let e=this.waiters.splice(0);for(let t of e)t()}setError(e){this.error=e,this.finished=!0;let t=this.waiters.splice(0);for(let r of t)r()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let e=0;for(;;){for(;e<this.events.length;)yield this.events[e],e++;if(this.finished){if(this.error)throw this.error;return}await new Promise(t=>{if(e<this.events.length||this.finished){t();return}this.waiters.push(t)})}}};function Gd(e,t){switch(t.type){case"text-delta":return e.type==="text"?{...e,text:(e.text??"")+t.text}:e;case"reasoning-delta":return e.type==="thinking"?{...e,thinking:(e.thinking??"")+t.reasoning}:e.type==="reasoning"?{...e,reasoning:(e.reasoning??"")+t.reasoning}:e;case"data-delta":return{...e,data:(e.data??"")+t.data};case"tool-call-delta":return e.type==="tool_call_chunk"||e.type==="server_tool_call_chunk"?{...e,args:(e.args??"")+t.args}:e;case"block-delta":return{...e,...t.fields};default:return e}}function vn(e){if(e.event!=="content-block-delta")return;if("delta"in e&&e.delta)return e.delta;let t=e.content;if(t==null||typeof t!="object")return;let r=t;if(r.type==="text"&&typeof r.text=="string")return{type:"text-delta",text:r.text};if(r.type==="reasoning"&&typeof r.reasoning=="string")return{type:"reasoning-delta",reasoning:r.reasoning};if(r.type==="thinking"&&typeof r.thinking=="string")return{type:"reasoning-delta",reasoning:r.thinking};if(typeof r.data=="string")return{type:"data-delta",data:r.data,encoding:"base64"};if(typeof r.type=="string")return{type:"block-delta",fields:{...r,type:r.type}}}function Ic(e){if(e==null||typeof e!="object")return;let t=e;if(t.type==="reasoning"&&typeof t.reasoning=="string")return t.reasoning;if(t.type==="thinking"&&typeof t.thinking=="string")return t.thinking}function _a(e){if(e==null||typeof e!="object")return!1;let t=e.type;return t==="reasoning"||t==="thinking"}function Br(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function Jd(e){if(e!=null&&typeof e=="object"&&!Array.isArray(e))return e;if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function qd(e){let t=e;if(e.type==="tool_call"||e.type!=="tool_call_chunk"&&e.type!=="tool_use"&&e.type!=="input_json_delta")return e;let r=typeof t.name=="string"?t.name:void 0;if(r==null)return e;let n=t.args??t.input;return{...t,type:"tool_call",name:r,args:Jd(n)}}var Nc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t="";for await(let r of e.iterate()){let n=vn(r);n?.type==="text-delta"&&(t+=n.text,yield t)}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate()){let n=vn(r);n?.type==="text-delta"&&(yield n.text)}}return t()}then(e,t){return(async()=>{let r="";for await(let n of this)r+=n;return r})().then(e,t)}},Pc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=[];for await(let r of e.iterate())r.event==="content-block-finish"&&r.content.type==="tool_call"&&(t.push(r.content),yield[...t])}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate())r.event==="content-block-finish"&&r.content.type==="tool_call"&&(yield r.content)}return t()}then(e,t){return(async()=>{let r=[];for await(let n of this)r.push(n);return r})().then(e,t)}},Rc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t="",r=!1;for await(let n of e.iterate())if(n.event==="content-block-start"){if(!_a(n.content)){if(r)return;continue}r=!0;let a=Ic(n.content);if(a==null||a.length===0)continue;t+=a,yield t}else if(n.event==="content-block-delta"){let a=vn(n);if(a?.type!=="reasoning-delta")continue;r=!0;let s=a.reasoning;if(s==null||s.length===0)continue;t+=s,yield t}else{if(n.event==="content-block-finish"&&_a(n.content))return;if(n.event==="message-finish")return}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){let r=!1;for await(let n of e.iterate())if(n.event==="content-block-start"){if(!_a(n.content)){if(r)return;continue}r=!0;let a=Ic(n.content);a!=null&&a.length>0&&(yield a)}else if(n.event==="content-block-delta"){let a=vn(n);if(a?.type!=="reasoning-delta")continue;r=!0;let s=a.reasoning;s!=null&&s.length>0&&(yield s)}else{if(n.event==="content-block-finish"&&_a(n.content))return;if(n.event==="message-finish")return}}return t()}then(e,t){return(async()=>{let r="";for await(let n of this)r+=n;return r})().then(e,t)}},Mc=class{_buffer;constructor(e){this._buffer=e}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate())if(r.event==="usage"){let n=Br(r.usage);n&&(yield n)}else if(r.event==="message-start"&&r.usage){let n=Br(r.usage);n&&(yield n)}else if(r.event==="message-finish"&&r.usage){let n=Br(r.usage);n&&(yield n)}}return t()}then(e,t){return(async()=>{let r;for await(let n of this)r=n;return r})().then(e,t)}},va=class{_buffer;constructor(e){this._buffer=new Wd,this._consume(e)}async _consume(e){try{for await(let t of e)this._buffer.push(t);this._buffer.finish()}catch(t){this._buffer.setError(t instanceof Error?t:new Error(String(t)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new Nc(this._buffer)}get toolCalls(){return new Pc(this._buffer)}get reasoning(){return new Rc(this._buffer)}get usage(){return new Mc(this._buffer)}get output(){return this._assembleMessage()}then(e,t){return this._assembleMessage().then(e,t)}async _assembleMessage(){let e=[],t,r,n={},a;for await(let i of this._buffer.iterate())switch(i.event){case"message-start":t=i.id??t,i.usage&&(r=Br(i.usage));break;case"content-block-start":e[i.index]=i.content;break;case"content-block-delta":{let o=e[i.index],c=vn(i);o&&c&&(e[i.index]=Gd(o,c));break}case"content-block-finish":e[i.index]=i.content;break;case"usage":r=Br(i.usage);break;case"message-finish":a=i.reason,i.usage&&(r=Br(i.usage)),i.responseMetadata&&(n={...n,...i.responseMetadata})}let s=e.filter(i=>i!=null).map(qd);return new Je({id:t,content:s,usage_metadata:r,response_metadata:{...n,...a?{finish_reason:a}:{},output_version:"v1"}})}};var pr=class extends Q{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let r=q(t);return this.func&&await this.func(e,r),this._callWithConfig(n=>Promise.resolve(n),e,r)}async*transform(e,t){let r=q(t),n,a=!0;for await(let s of this._transformStreamWithConfig(e,i=>i,r))if(yield s,a)if(n===void 0)n=s;else try{n=Pe(n,s)}catch{n=void 0,a=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(e){return new _n(new Dt({steps:e}))}};var $c=class extends Q{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:r,input:n}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(n,q(t))}async batch(e,t,r){let n=e.map(f=>f.key),a=e.map(f=>f.input);if(n.find(f=>this.runnables[f]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");let s=n.map(f=>this.runnables[f]),i=this._getOptionsList(t??{},e.length),o=i[0]?.maxConcurrency??r?.maxConcurrency,c=o&&o>0?o:e.length,u=[];for(let f=0;f<a.length;f+=c){let p=a.slice(f,f+c).map((h,m)=>s[m].invoke(h,i[m])),g=await Promise.all(p);u.push(g)}return u.flat()}async stream(e,t){let{key:r,input:n}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.stream(n,t)}};var Dc=class extends Q{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");let t=e.slice(0,-1).map(([n,a])=>[Me(n),Me(a)]),r=Me(e[e.length-1]);return new this({branches:t,default:r})}async _invoke(e,t,r){let n;for(let a=0;a<this.branches.length;a+=1){let[s,i]=this.branches[a];if(await s.invoke(e,Y(t,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await i.invoke(e,Y(t,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(e,Y(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let r=await(await he(t))?.handleChainStart(this.toJSON(),ue(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName),n,a=!0,s;try{for(let i=0;i<this.branches.length;i+=1){let[o,c]=this.branches[i];if(await o.invoke(e,Y(t,{callbacks:r?.getChild(`condition:${i+1}`)}))){s=await c.stream(e,Y(t,{callbacks:r?.getChild(`branch:${i+1}`)}));for await(let u of s)if(yield u,a)if(n===void 0)n=u;else try{n=Pe(n,u)}catch{n=void 0,a=!1}break}}if(s===void 0){s=await this.default.stream(e,Y(t,{callbacks:r?.getChild("branch:default")}));for await(let i of s)if(yield i,a)if(n===void 0)n=i;else try{n=Pe(n,i)}catch{n=void 0,a=!1}}}catch(i){throw await r?.handleChainError(i),i}await r?.handleChainEnd(n??{})}};var Lc=class extends $t{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Ze.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"}),r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=pr.assign({[r]:t}).withConfig({runName:"insertHistory"}));let n=t.pipe(e.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=e.config??{};super({...e,config:a,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!Oe(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new De(t)];if(Array.isArray(t))return t;if(Oe(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
30
+ Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!Oe(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new Je(t)];if(Array.isArray(t))return t;if(Oe(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let r=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,t){let r=t.configurable?.messageHistory,n;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?n=e.inputs[0]:n=e.inputs;let a=this._getInputMessages(n);if(this.historyMessagesKey===void 0){let o=await r.getMessages();a=a.slice(o.length)}let s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let i=this._getOutputMessages(s);await r.addMessages([...a,...i])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let n={[this.inputMessagesKey??"input"]:"foo"};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
31
+ eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}let{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}};var a0=M({RouterRunnable:()=>$c,Runnable:()=>Q,RunnableAssign:()=>_n,RunnableBinding:()=>$t,RunnableBranch:()=>Dc,RunnableEach:()=>dc,RunnableLambda:()=>Ze,RunnableMap:()=>Dt,RunnableParallel:()=>gc,RunnablePassthrough:()=>pr,RunnablePick:()=>Bs,RunnableRetry:()=>ga,RunnableSequence:()=>zr,RunnableToolLike:()=>ha,RunnableWithFallbacks:()=>zs,RunnableWithMessageHistory:()=>Lc,_coerceToRunnable:()=>Me,ensureConfig:()=>q,getCallbackManagerForConfig:()=>he,mergeConfigs:()=>Vt,patchConfig:()=>Y,pickRunnableConfigKeys:()=>ke,raceWithSignal:()=>Ne});var c0=M({extendInteropZodObject:()=>Po,getInteropZodDefaultGetter:()=>Mo,getInteropZodObjectShape:()=>Yn,getSchemaDescription:()=>Or,interopParse:()=>Co,interopParseAsync:()=>It,interopSafeParse:()=>Oo,interopSafeParseAsync:()=>Qn,interopZodObjectMakeFieldsOptional:()=>$o,interopZodObjectPartial:()=>Ro,interopZodObjectPassthrough:()=>Xn,interopZodObjectStrict:()=>Ar,interopZodTransformInputSchema:()=>ea,isInteropZodError:()=>ta,isInteropZodLiteral:()=>Ao,isInteropZodObject:()=>No,isInteropZodSchema:()=>Se,isShapelessZodSchema:()=>Io,isSimpleStringZodSchema:()=>Cr,isZodArrayV4:()=>un,isZodLiteralV3:()=>Ka,isZodLiteralV4:()=>Ya,isZodNullableV4:()=>Qa,isZodObjectV3:()=>cn,isZodObjectV4:()=>Le,isZodOptionalV4:()=>Xa,isZodSchema:()=>Eo,isZodSchemaV3:()=>ce,isZodSchemaV4:()=>te});var f0=M({convertChunksToEvents:()=>Vs,finalizeContentBlock:()=>ba}),Hd={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},Kd={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"};function jc(e){let t=0;for(let r of e.keys())r>=t&&(t=r+1);return t}function Fc(e){let t=e.additional_kwargs;return t!=null&&typeof t=="object"?t:{}}function Yd(e){let t=Fc(e).tool_outputs;if(!Array.isArray(t))return[];let r=[];for(let n of t){if(n==null||typeof n!="object")continue;let a=n;if(a.type!=="image_generation_call")continue;let s=typeof a.result=="string"?a.result:void 0,i=typeof a.url=="string"?a.url:void 0;if(s==null&&i==null)continue;let o=typeof a.output_format=="string"?a.output_format.toLowerCase():void 0,c=(o!=null?Kd[o]:void 0)??"image/png";r.push({type:"image",...typeof a.id=="string"?{id:a.id}:{},...i!=null?{url:i}:{},...s!=null?{data:s}:{},mimeType:c})}return r}function Xd(e){let t=Fc(e).audio;if(t==null||typeof t!="object")return;let r=t,n=typeof r.data=="string"?r.data:void 0,a=typeof r.url=="string"?r.url:void 0,s=typeof r.transcript=="string"?r.transcript:void 0;if(n==null&&a==null&&s==null)return;let i=typeof r.mime_type=="string"?r.mime_type:typeof r.mimeType=="string"?r.mimeType:void 0,o=typeof r.format=="string"?r.format.toLowerCase():void 0,c=i??(o!=null?Hd[o]:void 0)??(n!=null?"audio/wav":"audio/pcm");return{...typeof r.id=="string"?{id:r.id}:{},...n!=null?{data:n}:{},...a!=null?{url:a}:{},...s!=null?{transcript:s}:{},mimeType:c}}async function*Vs(e,t){let r=new Map,n=!1,a,s,i=new Set;for await(let o of e){t?.signal?.throwIfAborted();let c=o.message,u=!1;if(!n){n=!0;let g={event:"message-start",id:c.id??void 0};pe.isInstance(c)&&c.usage_metadata&&(g.usage=c.usage_metadata,a={...c.usage_metadata},u=!0),yield g}let f=c.content;if(typeof f=="string"){if(f!==""){if(!r.has(0)){let m={type:"text",text:""};r.set(0,{type:"text",accumulated:m}),yield{event:"content-block-start",index:0,content:m}}let h=r.get(0);h.accumulated={...h.accumulated,text:(h.accumulated.text??"")+f},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:f}}}}else if(Array.isArray(f))for(let g of f){let h=typeof g.index=="number"?g.index:r.size;if(!r.has(h))r.set(h,{type:g.type,accumulated:{...g}}),yield{event:"content-block-start",index:h,content:{...g}};else{let m=r.get(h),v=ef(g);m.accumulated=Qd(m.accumulated,v),yield{event:"content-block-delta",index:h,delta:v}}}if(pe.isInstance(c)&&c.tool_call_chunks&&c.tool_call_chunks.length>0)for(let g of c.tool_call_chunks){let h=typeof g.index=="number"?g.index:r.size;if(!r.has(h)){let v={type:"tool_call_chunk",id:g.id,name:g.name,args:"",index:h};r.set(h,{type:"tool_call_chunk",accumulated:{...v}}),yield{event:"content-block-start",index:h,content:v}}let m=r.get(h).accumulated;g.id!=null&&(m.id=g.id),g.name!=null&&(m.name=g.name),g.args&&(m.args=(m.args??"")+g.args,yield{event:"content-block-delta",index:h,delta:{type:"tool-call-delta",args:g.args}})}let p=Xd(c);if(p!=null){if(s==null){let h=jc(r);s={index:h,id:p.id,mimeType:p.mimeType,transcript:""};let m={type:"audio",...p.id!=null?{id:p.id}:{},...p.url!=null?{url:p.url}:{},data:"",mimeType:p.mimeType};r.set(h,{type:"audio",accumulated:m}),yield{event:"content-block-start",index:h,content:m}}let g=r.get(s.index);if(g!=null){let h=g.accumulated;p.id!=null&&s.id==null&&(s.id=p.id,h.id=p.id),p.transcript!=null&&(s.transcript+=p.transcript,h.transcript=s.transcript,yield{event:"content-block-delta",index:s.index,delta:{type:"block-delta",fields:{type:"audio",transcript:s.transcript}}}),p.data!=null&&p.data.length>0&&(h.data=(h.data??"")+p.data,yield{event:"content-block-delta",index:s.index,delta:{type:"data-delta",data:p.data,encoding:"base64"}})}}for(let g of Yd(c)){let h=g,m=h.id??h.url??(h.data!=null?`${h.data.length}:${h.data.slice(0,32)}`:void 0);if(m!=null&&i.has(m))continue;m!=null&&i.add(m);let v=jc(r);r.set(v,{type:"image",accumulated:g}),yield{event:"content-block-start",index:v,content:g}}if(!u&&pe.isInstance(c)&&c.usage_metadata){let g=c.usage_metadata;a?a={input_tokens:a.input_tokens+g.input_tokens,output_tokens:a.output_tokens+g.output_tokens,total_tokens:a.total_tokens+g.total_tokens}:a={...g},yield{event:"usage",usage:{...a}}}}for(let[o,c]of r)yield{event:"content-block-finish",index:o,content:ba(c.accumulated)};yield{event:"message-finish",reason:"stop",...a?{usage:a}:{}}}function Qd(e,t){switch(t.type){case"text-delta":return e.type==="text"?{...e,text:(e.text??"")+t.text}:e;case"reasoning-delta":return e.type==="thinking"?{...e,thinking:(e.thinking??"")+t.reasoning}:e.type==="reasoning"?{...e,reasoning:(e.reasoning??"")+t.reasoning}:e;case"data-delta":return{...e,data:(e.data??"")+t.data};case"block-delta":return{...e,...t.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function ef(e){if(e.type==="text")return{type:"text-delta",text:e.text};if(e.type==="reasoning")return{type:"reasoning-delta",reasoning:e.reasoning};if(e.type==="thinking"&&typeof e.thinking=="string")return{type:"reasoning-delta",reasoning:e.thinking};if(typeof e.data=="string")return{type:"data-delta",data:e.data,encoding:"base64"};if(typeof e.type=="string")return{type:"block-delta",fields:{...e}};throw new Error(`Unsupported content block delta: ${JSON.stringify(e)}`)}function ba(e){if(e.type==="tool_call_chunk"){let t=e,r;try{r=JSON.parse(t.args??"{}")}catch{return{type:"invalid_tool_call",id:t.id,name:t.name,args:t.args,error:"Failed to parse tool call arguments as JSON"}}return{type:"tool_call",id:t.id,name:t.name,args:r}}return e}var g0=M({convertOpenAICompletionsStream:()=>tf});async function*tf(e,t={}){let r=t.streamUsage??!0,n=t.provider??"openai",a=t.mapChunk,s=new Map,i=new Map,o=0,c=!1,u,f,p,g=!1,h=(m,v)=>{let b=i.get(m);if(b!==void 0)return{index:b,isNew:!1};let x=o++;return i.set(m,x),s.set(x,{...v}),{index:x,isNew:!0}};for await(let m of e){a&&(m=a(m)),c||(c=!0,yield{event:"message-start",id:m.id}),!g&&(m.model||m.service_tier)&&(g=!0,yield{event:"provider",provider:n,name:"stream_metadata",payload:{model:m.model,service_tier:m.service_tier}}),m.usage&&r&&(u=sf(m.usage),yield{event:"usage",usage:u});let v=m.x_groq?.usage;v&&r&&(u=nf(v),yield{event:"usage",usage:u});let b=m.choices?.[0];if(!b)continue;b.finish_reason!=null&&(f=af(b.finish_reason),p=of(m,b));let{delta:x}=b;if(!x)continue;let I=rf(x);if(I){let{index:S,isNew:L}=h("reasoning",{type:"reasoning",reasoning:""});L&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let W=s.get(S);W.reasoning=(W.reasoning??"")+I,yield{event:"content-block-delta",index:S,delta:{type:"reasoning-delta",reasoning:I}}}if(x.content){let{index:S,isNew:L}=h("text",{type:"text",text:""});L&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let W=s.get(S);W.text=(W.text??"")+x.content,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:x.content}}}if(Array.isArray(x.tool_calls))for(let S of x.tool_calls){let L=S.index??0,{index:W,isNew:ae}=h(`tool:${L}`,{type:"tool_call_chunk",id:S.id,name:S.function?.name,args:"",index:L});ae&&(yield{event:"content-block-start",index:W,content:{type:"tool_call_chunk",id:S.id,name:S.function?.name,args:"",index:L}});let _e=s.get(W);S.id!=null&&(_e.id=S.id),S.function?.name!=null&&(_e.name=S.function.name);let y=S.function?.arguments;y&&(_e.args=(_e.args??"")+y,yield{event:"content-block-delta",index:W,delta:{type:"tool-call-delta",args:y}})}if(x.audio){let{index:S,isNew:L}=h("audio",{type:"audio",id:x.audio.id,data:"",mimeType:"audio/pcm",transcript:x.audio.transcript??""});L&&(yield{event:"content-block-start",index:S,content:{type:"audio",id:x.audio.id,data:"",mimeType:"audio/pcm",transcript:x.audio.transcript??""}});let W=s.get(S);x.audio.transcript&&(W.transcript=(W.transcript??"")+x.audio.transcript,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"audio",transcript:W.transcript}}}),x.audio.data&&(W.data=(W.data??"")+x.audio.data,yield{event:"content-block-delta",index:S,delta:{type:"data-delta",data:x.audio.data,encoding:"base64"}})}x.function_call&&(yield{event:"provider",provider:n,name:"function_call",payload:x.function_call}),b.logprobs&&(yield{event:"provider",provider:n,name:"logprobs",payload:b.logprobs})}for(let[m,v]of s)yield{event:"content-block-finish",index:m,content:ba(v)};yield{event:"message-finish",reason:f,...u?{usage:u}:{},...p?{responseMetadata:p}:{}}}function rf(e){let t=e.reasoning_content??e.reasoning;return typeof t=="string"&&t.length>0?t:void 0}function nf(e){return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0}}function af(e){switch(e){case"stop":return"stop";case"length":case"max_tokens":return"length";case"tool_calls":case"function_call":return"tool_use";case"content_filter":return"content_filter";default:return"stop"}}function sf(e){let t={...e.prompt_tokens_details?.audio_tokens!=null&&{audio:e.prompt_tokens_details.audio_tokens},...e.prompt_tokens_details?.cached_tokens!=null&&{cache_read:e.prompt_tokens_details.cached_tokens}},r={...e.completion_tokens_details?.audio_tokens!=null&&{audio:e.completion_tokens_details.audio_tokens},...e.completion_tokens_details?.reasoning_tokens!=null&&{reasoning:e.completion_tokens_details.reasoning_tokens}};return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(r).length>0&&{output_token_details:r}}}function of(e,t){return{model_provider:"openai",model_name:e.model,system_fingerprint:e.system_fingerprint,service_tier:e.service_tier,finish_reason:t.finish_reason,...e.usage?{usage:e.usage}:{}}}var N="0123456789abcdef".split(""),cf=[-2147483648,8388608,32768,128],Ye=[24,16,8,0],wa=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],de=[];function Xe(e,t){t?(de[0]=de[16]=de[1]=de[2]=de[3]=de[4]=de[5]=de[6]=de[7]=de[8]=de[9]=de[10]=de[11]=de[12]=de[13]=de[14]=de[15]=0,this.blocks=de):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Xe.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,a=0,s,i=e.length,o=this.blocks;a<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(s=this.start;a<i&&s<64;++a)o[s>>>2]|=e[a]<<Ye[s++&3];else for(s=this.start;a<i&&s<64;++a)n=e.charCodeAt(a),n<128?o[s>>>2]|=n<<Ye[s++&3]:n<2048?(o[s>>>2]|=(192|n>>>6)<<Ye[s++&3],o[s>>>2]|=(128|n&63)<<Ye[s++&3]):n<55296||n>=57344?(o[s>>>2]|=(224|n>>>12)<<Ye[s++&3],o[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],o[s>>>2]|=(128|n&63)<<Ye[s++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++a)&1023),o[s>>>2]|=(240|n>>>18)<<Ye[s++&3],o[s>>>2]|=(128|n>>>12&63)<<Ye[s++&3],o[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],o[s>>>2]|=(128|n&63)<<Ye[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Xe.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=cf[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};Xe.prototype.hash=function(){for(var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,u=16,f,p,g,h,m,v,b,x,I,S;u<64;++u)h=c[u-15],f=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[u-2],p=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[u]=c[u-16]+f+c[u-7]+p<<0;for(S=t&r,u=0;u<64;u+=4)this.first?(this.is224?(b=300032,h=c[0]-1413257819,o=h-150054599<<0,n=h+24177077<<0):(b=704751109,h=c[0]-210244248,o=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(f=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),b=e&t,g=b^e&r^S,v=a&s^~a&i,h=o+p+v+wa[u]+c[u],m=f+g,o=n+h<<0,n=h+m<<0),f=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),x=n&e,g=x^n&t^b,v=i&o^~i&a,h=s+p+v+wa[u+1]+c[u+1],m=f+g,i=r+h<<0,r=h+m<<0,f=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),I=r&n,g=I^r&e^x,v=s&i^~s&o,h=a+p+v+wa[u+2]+c[u+2],m=f+g,s=t+h<<0,t=h+m<<0,f=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),S=t&r,g=S^t&n^I,v=s&i^~s&o,h=a+p+v+wa[u+3]+c[u+3],m=f+g,a=e+h<<0,e=h+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+a<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};Xe.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=N[e>>>28&15]+N[e>>>24&15]+N[e>>>20&15]+N[e>>>16&15]+N[e>>>12&15]+N[e>>>8&15]+N[e>>>4&15]+N[e&15]+N[t>>>28&15]+N[t>>>24&15]+N[t>>>20&15]+N[t>>>16&15]+N[t>>>12&15]+N[t>>>8&15]+N[t>>>4&15]+N[t&15]+N[r>>>28&15]+N[r>>>24&15]+N[r>>>20&15]+N[r>>>16&15]+N[r>>>12&15]+N[r>>>8&15]+N[r>>>4&15]+N[r&15]+N[n>>>28&15]+N[n>>>24&15]+N[n>>>20&15]+N[n>>>16&15]+N[n>>>12&15]+N[n>>>8&15]+N[n>>>4&15]+N[n&15]+N[a>>>28&15]+N[a>>>24&15]+N[a>>>20&15]+N[a>>>16&15]+N[a>>>12&15]+N[a>>>8&15]+N[a>>>4&15]+N[a&15]+N[s>>>28&15]+N[s>>>24&15]+N[s>>>20&15]+N[s>>>16&15]+N[s>>>12&15]+N[s>>>8&15]+N[s>>>4&15]+N[s&15]+N[i>>>28&15]+N[i>>>24&15]+N[i>>>20&15]+N[i>>>16&15]+N[i>>>12&15]+N[i>>>8&15]+N[i>>>4&15]+N[i&15];return this.is224||(c+=N[o>>>28&15]+N[o>>>24&15]+N[o>>>20&15]+N[o>>>16&15]+N[o>>>12&15]+N[o>>>8&15]+N[o>>>4&15]+N[o&15]),c};Xe.prototype.toString=Xe.prototype.hex;Xe.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};Xe.prototype.array=Xe.prototype.digest;Xe.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var xa=(...e)=>new Xe(!1,!0).update(e.join("")).hex();var w0=M({sha256:()=>xa});var A0=M({BaseCache:()=>Bc,InMemoryCache:()=>Ws,defaultHashKeyEncoder:()=>zc,deserializeStoredGeneration:()=>uf,serializeGeneration:()=>lf}),zc=(...e)=>xa(e.join("_"));function uf(e){return e.message!==void 0?{text:e.text,message:Ln(e.message)}:{text:e.text}}function lf(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Bc=class{keyEncoder=zc;makeDefaultKeyEncoder(e){this.keyEncoder=e}},df=new Map,Ws=class Zc extends Bc{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new Zc(df)}};var M0=M({BasePromptValue:()=>ka,ChatPromptValue:()=>Js,ImagePromptValue:()=>ff,StringPromptValue:()=>Gs}),ka=class extends Cn{},Gs=class extends ka{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new De(this.value)]}},Js=class extends ka{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Dn(this.messages)}toChatMessages(){return this.messages}},ff=class extends ka{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new De({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var Gc=ii(Wc(),1),bf=Object.defineProperty,wf=(e,t,r)=>t in e?bf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,xf=(e,t,r)=>(wf(e,typeof t!="symbol"?t+"":t,r),r);function kf(e,t){let r=Array.from({length:e.length},(n,a)=>({start:a,end:a+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){let s=e.slice(r[a].start,r[a+1].end),i=t.get(s.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,a])}if(n!=null){let a=n[1];r[a]={start:r[a].start,end:r[a+1].end},r.splice(a+1,1)}else break}return r}function Tf(e,t){return e.length===1?[t.get(e.join(","))]:kf(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function Sf(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Hs=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let r=e.bpe_ranks.split(`
32
+ `).filter(Boolean).reduce((n,a)=>{let[s,i,...o]=a.split(" "),c=Number.parseInt(i,10);return o.forEach((u,f)=>n[u]=c+f),n},{});for(let[n,a]of Object.entries(r)){let s=Gc.default.toByteArray(n);this.rankMap.set(s.join(","),a),this.textMap.set(a,s)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,s])=>(n[s]=this.textEncoder.encode(a),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),a=Hs.specialTokenRegex(Object.keys(this.specialTokens)),s=[],i=new Set(t==="all"?Object.keys(this.specialTokens):t),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!i.has(u)):r);if(o.size>0){let u=Hs.specialTokenRegex([...o]),f=e.match(u);if(f!=null)throw new Error(`The text contains a special token that is not allowed: ${f[0]}`)}let c=0;for(;;){let u=null,f=c;for(;a.lastIndex=f,u=a.exec(e),!(u==null||i.has(u[0]));)f=u.index+1;let p=u?.index??e.length;for(let h of e.substring(c,p).matchAll(n)){let m=this.textEncoder.encode(h[0]),v=this.rankMap.get(m.join(","));if(v!=null){s.push(v);continue}s.push(...Tf(m,this.rankMap))}if(u==null)break;let g=this.specialTokens[u[0]];s.push(g),c=u.index+u[0].length}return s}decode(e){let t=[],r=0;for(let s=0;s<e.length;++s){let i=e[s],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(t.push(o),r+=o.length)}let n=new Uint8Array(r),a=0;for(let s of t)n.set(s,a),a+=s.length;return this.textDecoder.decode(n)}},Sa=Hs;xf(Sa,"specialTokenRegex",e=>new RegExp(e.map(t=>Sf(t)).join("|"),"g"));function Ks(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var q0=M({encodingForModel:()=>Aa,getEncoding:()=>Jc}),Ea={},Ef=new ht({});async function Jc(e){return e in Ea||(Ea[e]=Ef.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new Sa(t)).catch(t=>{throw delete Ea[e],t})),await Ea[e]}async function Aa(e){return Jc(Ks(e))}var nb=M({BaseLangChain:()=>Ca,BaseLanguageModel:()=>bn,calculateMaxTokens:()=>Cf,getEmbeddingContextSize:()=>Af,getModelContextSize:()=>qc,getModelNameForTiktoken:()=>Oa,isOpenAITool:()=>Of}),Oa=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Af=e=>e==="text-embedding-ada-002"?8191:2046,qc=e=>{switch(Oa(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Of(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var Cf=async({prompt:e,modelName:t})=>{let r;try{r=(await Aa(Oa(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return qc(t)-r},If=()=>!1,Ca=class extends Q{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??If(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.4.0")}_addVersion(e,t){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:t}}}},bn=class extends Ca{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){let{cache:n,...a}=r;super({callbacks:e??t,...a}),typeof n=="object"?this.cache=n:n?this.cache=Ws.global():this.cache=void 0,this.caller=new ht(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await Aa("modelName"in this?Oa(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Gs(e):Array.isArray(e)?new Js(e.map(Et)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([n,a])=>a!==void 0).map(([n,a])=>`${n}:${JSON.stringify(a)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:r,messages:n,response_format:a,...s}=e;return s}};function wn(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function xn(e){return e!==void 0&&Q.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function kn(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Se(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Tn(e){return kn(e)||xn(e)||wn(e)}var Eb=M({BaseToolkit:()=>Nf,DynamicStructuredTool:()=>Yc,DynamicTool:()=>Kc,StructuredTool:()=>Ys,Tool:()=>Hc,ToolInputParsingException:()=>xr,isLangChainTool:()=>Tn,isRunnableToolLike:()=>xn,isStructuredTool:()=>wn,isStructuredToolParams:()=>kn,tool:()=>Pf}),Ys=class extends Ca{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let r,n=q(Vt(this.defaultConfig,t));return wr(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){let n=wr(e)?e.args:e,a;if(Se(this.schema))try{a=await It(this.schema,n)}catch(m){let v="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(v=`${v}
33
+ Details: ${m.message}`),ta(m)&&(v=`${v}
34
+
35
+ ${za.prettifyError(m)}`),new xr(v,JSON.stringify(e))}else{let m=re(n,this.schema);if(!m.valid){let v="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(v=`${v}
36
+ Details: ${m.errors.map(b=>`${b.keywordLocation}: ${b.error}`).join(`
37
+ `)}`),new xr(v,JSON.stringify(e))}a=n}let s=jn(t),i=et.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o;wr(e)&&(o=e.id),!o&&pi(s)&&(o=s.toolCall.id);let c;typeof n=="object"&&n!==null&&!Array.isArray(n)&&(c=n),c||(c=typeof e=="string"?e:JSON.stringify(e));let u=await i?.handleToolStart(this.toJSON(),c,s.runId,void 0,void 0,void 0,s.runName,o);delete s.runId;let f;try{let m=await this._call(a,u,s);f=js(m)?await uc(m,async v=>{try{await u?.handleToolEvent(v)}catch(b){await u?.handleToolError(b)}}):m}catch(m){throw await u?.handleToolError(m),m}let p,g;if(this.responseFormat==="content_and_artifact")if(Array.isArray(f)&&f.length===2)[p,g]=f;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
38
+ Result: ${JSON.stringify(f)}`);else p=f;let h=Mf({content:p,artifact:g,toolCallId:o,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(h),h}},Hc=class extends Ys{schema=we.object({input:we.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},Kc=class extends Hc{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let r=jn(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},Yc=class extends Ys{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){let n=jn(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},Nf=class{getTools(){return this.tools}};function Pf(e,t){let r=Cr(t.schema),n=Fr(t.schema);if(!t.schema||r||n)return new Kc({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(i,o,c)=>new Promise((u,f)=>{let p=Y(c,{callbacks:o?.getChild()});Ce.runWithConfig(ke(p),async()=>{try{u(e(i,p))}catch(g){f(g)}})})});let a=t.schema,s=t.description??t.schema.description??`${t.name} tool`;return new Yc({...t,description:s,schema:a,func:async(i,o,c)=>new Promise((u,f)=>{let p,g=()=>{c?.signal&&p&&c.signal.removeEventListener("abort",p)};if(c?.signal){if(p=()=>{g(),f(Ot(c.signal))},c.signal.aborted){p();return}c.signal.addEventListener("abort",p,{once:!0})}let h=Y(c,{callbacks:o?.getChild()});Ce.runWithConfig(ke(h),async()=>{try{let m=await e(i,h);if(js(m)){u(m);return}if(c?.signal?.aborted){g();return}g(),u(m)}catch(m){g(),f(m)}})})})}function Rf(e){return typeof e=="object"&&e!==null&&"type"in e}function Mf(e){let{content:t,artifact:r,toolCallId:n,metadata:a}=e;return n&&!$n(t)?typeof t=="string"||Array.isArray(t)&&t.every(Rf)?new St({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:a}):new St({status:"success",content:$f(t),artifact:r,tool_call_id:n,name:e.name,metadata:a}):t}function $f(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}var $b=M({Embeddings:()=>Df}),Df=class{caller;constructor(e){this.caller=new ht(e??{})}};var Xs=class extends Q{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),e,{...t,runType:"parser"})}},bt=class extends Xs{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},ye=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");li(this,"OUTPUT_PARSING_FAILURE")}};var wt=class extends bt{async*_transform(e){for await(let t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},Lt=class extends wt{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(let n of e){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let a;if(kr(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new Jn({message:n,text:n.content})}else if(Oe(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new Jn({message:Ut(n),text:n.content})}else a=new mt({text:n});r===void 0?r=a:r=r.concat(a);let s=await this.parsePartialResult([r]);s!=null&&!it(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}};var nw=M({applyPatch:()=>pt,compare:()=>Gt});function xt(e){if(!e||!("message"in e))return;let{message:t}=e;if(!Oe(t))return;let r;try{r=t.contentBlocks}catch{return}for(let n of r)if(n.type==="refusal")throw fi.fromRefusal(n,t)}var Ia=class extends Lt{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Gt(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return zt(e[0].text)}async parseResult(e,t){return xt(e[0]),super.parseResult(e,t)}async parse(e){return zt(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}};var Xc=class extends wt{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}};var Zr=class extends wt{re;async*_transform(e){let t="";for await(let r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){let n=[...t.matchAll(this.re)];if(n.length>1){let a=0;for(let s of n.slice(0,-1))yield[s[1]],a+=(s.index??0)+s[0].length;t=t.slice(a)}}else{let n=await this.parse(t);if(n.length>1){for(let a of n.slice(0,-1))yield[a];t=n[n.length-1]}}for(let r of await this.parse(t))yield[r]}},Qc=class extends Zr{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new ye(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},eu=class extends Zr{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{let t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new ye(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===ye.prototype?t:new ye(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},tu=class extends Zr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
39
+
40
+ 1. foo
41
+
42
+ 2. bar
43
+
44
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},ru=class extends Zr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
45
+
46
+ 1. foo
47
+
48
+ 2. bar
49
+
50
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}};var nu=class extends wt{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}};var Na=class extends bt{static lc_name(){return"StandardSchemaOutputParser"}lc_namespace=["langchain","output_parsers","standard_schema"];schema;constructor(e){super(),this.schema=e}static fromSerializableSchema(e){return new this(e)}async parseResult(e,t){return xt(e[0]),super.parseResult(e,t)}async parse(e){try{let t=zt(e,JSON.parse),r=await this.schema["~standard"].validate(t);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(t){throw new ye(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}};var Sn=class extends bt{schema;static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=we.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,we.string().describe(n)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
51
+
52
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
53
+
54
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
55
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
56
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
57
+
58
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
59
+
60
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
61
+ \`\`\`json
62
+ ${JSON.stringify(ct(this.schema))}
63
+ \`\`\`
64
+ `}async parseResult(e,t){return xt(e[0]),super.parseResult(e,t)}async parse(e){try{let t=e.trim(),r=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(n,a)=>`"${a.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await It(this.schema,JSON.parse(r))}catch(t){throw new ye(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}},Qs=class extends Sn{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){let t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
65
+ \`\`\`json
66
+ ${this._schemaToInstruction(ct(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
67
+ \`\`\``}_schemaToInstruction(e,t=2){let r=e;if("type"in r){let n=!1,a;if(Array.isArray(r.type)){let o=r.type.findIndex(c=>c==="null");o!==-1&&(n=!0,r.type.splice(o,1)),a=r.type.join(" | ")}else a=r.type;if(r.type==="object"&&r.properties){let o=r.description?` // ${r.description}`:"";return`{
68
+ ${Object.entries(r.properties).map(([c,u])=>{let f=r.required?.includes(c)?"":" (optional)";return`${" ".repeat(t)}"${c}": ${this._schemaToInstruction(u,t+2)}${f}`}).join(`
69
+ `)}
70
+ ${" ".repeat(t-2)}}${o}`}if(r.type==="array"&&r.items){let o=r.description?` // ${r.description}`:"";return`array[
71
+ ${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}
72
+ ${" ".repeat(t-2)}] ${o}`}let s=n?" (nullable)":"",i=r.description?` // ${r.description}`:"";return`${a}${i}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,t)).join(`
73
+ ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=we.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,we.string().describe(n)])));return new this(t)}},au=class extends bt{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new Qs(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new ye(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var Lf=function(){let e={};e.parser=function(d,l){return new r(d,l)},e.SAXParser=r,e.SAXStream=u,e.createStream=c,e.MAX_BUFFER_LENGTH=65536;let t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(d,l){if(!(this instanceof r))return new r(d,l);var w=this;a(w),w.q=w.c="",w.bufferCheckPosition=e.MAX_BUFFER_LENGTH,w.opt=l||{},w.opt.lowercase=w.opt.lowercase||w.opt.lowercasetags,w.looseCase=w.opt.lowercase?"toLowerCase":"toUpperCase",w.tags=[],w.closed=w.closedRoot=w.sawRoot=!1,w.tag=w.error=null,w.strict=!!d,w.noscript=!!(d||w.opt.noscript),w.state=y.BEGIN,w.strictEntities=w.opt.strictEntities,w.ENTITIES=w.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),w.attribList=[],w.opt.xmlns&&(w.ns=Object.create(m)),w.trackPosition=w.opt.position!==!1,w.trackPosition&&(w.position=w.line=w.column=0),dt(w,"onready")}Object.create||(Object.create=function(d){function l(){}return l.prototype=d,new l}),Object.keys||(Object.keys=function(d){var l=[];for(var w in d)d.hasOwnProperty(w)&&l.push(w);return l});function n(d){for(var l=Math.max(e.MAX_BUFFER_LENGTH,10),w=0,_=0,G=t.length;_<G;_++){var X=d[t[_]].length;if(X>l)switch(t[_]){case"textNode":kt(d);break;case"cdata":ee(d,"oncdata",d.cdata),d.cdata="";break;case"script":ee(d,"onscript",d.script),d.script="";break;default:Tt(d,"Max buffer length exceeded: "+t[_])}w=Math.max(w,X)}d.bufferCheckPosition=e.MAX_BUFFER_LENGTH-w+d.position}function a(d){for(var l=0,w=t.length;l<w;l++)d[t[l]]=""}function s(d){kt(d),d.cdata!==""&&(ee(d,"oncdata",d.cdata),d.cdata=""),d.script!==""&&(ee(d,"onscript",d.script),d.script="")}r.prototype={end:function(){hr(this)},write:Ge,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var i=ReadableStream;i||(i=function(){});var o=e.EVENTS.filter(function(d){return d!=="error"&&d!=="end"});function c(d,l){return new u(d,l)}function u(d,l){if(!(this instanceof u))return new u(d,l);i.apply(this),this._parser=new r(d,l),this.writable=!0,this.readable=!0;var w=this;this._parser.onend=function(){w.emit("end")},this._parser.onerror=function(_){w.emit("error",_),w._parser.error=null},this._decoder=null,o.forEach(function(_){Object.defineProperty(w,"on"+_,{get:function(){return w._parser["on"+_]},set:function(G){if(!G)return w.removeAllListeners(_),w._parser["on"+_]=G,G;w.on(_,G)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(i.prototype,{constructor:{value:u}}),u.prototype.write=function(d){return this._parser.write(d.toString()),this.emit("data",d),!0},u.prototype.end=function(d){return d&&d.length&&this.write(d),this._parser.end(),!0},u.prototype.on=function(d,l){var w=this;return!w._parser["on"+d]&&o.indexOf(d)!==-1&&(w._parser["on"+d]=function(){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);_.splice(0,0,d),w.emit.apply(w,_)}),i.prototype.on.call(w,d,l)};var f="[CDATA[",p="DOCTYPE",g="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",m={xml:g,xmlns:h},v=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,x=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function S(d){return d===" "||d===`
74
+ `||d==="\r"||d===" "}function L(d){return d==='"'||d==="'"}function W(d){return d===">"||S(d)}function ae(d,l){return d.test(l)}function _e(d,l){return!ae(d,l)}var y=0;e.STATE={BEGIN:y++,BEGIN_WHITESPACE:y++,TEXT:y++,TEXT_ENTITY:y++,OPEN_WAKA:y++,SGML_DECL:y++,SGML_DECL_QUOTED:y++,DOCTYPE:y++,DOCTYPE_QUOTED:y++,DOCTYPE_DTD:y++,DOCTYPE_DTD_QUOTED:y++,COMMENT_STARTING:y++,COMMENT:y++,COMMENT_ENDING:y++,COMMENT_ENDED:y++,CDATA:y++,CDATA_ENDING:y++,CDATA_ENDING_2:y++,PROC_INST:y++,PROC_INST_BODY:y++,PROC_INST_ENDING:y++,OPEN_TAG:y++,OPEN_TAG_SLASH:y++,ATTRIB:y++,ATTRIB_NAME:y++,ATTRIB_NAME_SAW_WHITE:y++,ATTRIB_VALUE:y++,ATTRIB_VALUE_QUOTED:y++,ATTRIB_VALUE_CLOSED:y++,ATTRIB_VALUE_UNQUOTED:y++,ATTRIB_VALUE_ENTITY_Q:y++,ATTRIB_VALUE_ENTITY_U:y++,CLOSE_TAG:y++,CLOSE_TAG_SAW_WHITE:y++,SCRIPT:y++,SCRIPT_ENDING:y++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(d){var l=e.ENTITIES[d],w=typeof l=="number"?String.fromCharCode(l):l;e.ENTITIES[d]=w});for(var Ve in e.STATE)e.STATE[e.STATE[Ve]]=Ve;y=e.STATE;function dt(d,l,w){d[l]&&d[l](w)}function ee(d,l,w){d.textNode&&kt(d),dt(d,l,w)}function kt(d){d.textNode=Ur(d.opt,d.textNode),d.textNode&&dt(d,"ontext",d.textNode),d.textNode=""}function Ur(d,l){return d.trim&&(l=l.trim()),d.normalize&&(l=l.replace(/\s+/g," ")),l}function Tt(d,l){return kt(d),d.trackPosition&&(l+=`
75
+ Line: `+d.line+`
76
+ Column: `+d.column+`
77
+ Char: `+d.c),l=new Error(l),d.error=l,dt(d,"onerror",l),d}function hr(d){return d.sawRoot&&!d.closedRoot&&K(d,"Unclosed root tag"),d.state!==y.BEGIN&&d.state!==y.BEGIN_WHITESPACE&&d.state!==y.TEXT&&Tt(d,"Unexpected end"),kt(d),d.c="",d.closed=!0,dt(d,"onend"),r.call(d,d.strict,d.opt),d}function K(d,l){if(typeof d!="object"||!(d instanceof r))throw new Error("bad call to strictFail");d.strict&&Tt(d,l)}function Vr(d){d.strict||(d.tagName=d.tagName[d.looseCase]());var l=d.tags[d.tags.length-1]||d,w=d.tag={name:d.tagName,attributes:{}};d.opt.xmlns&&(w.ns=l.ns),d.attribList.length=0,ee(d,"onopentagstart",w)}function gr(d,l){var w=d.indexOf(":")<0?["",d]:d.split(":"),_=w[0],G=w[1];return l&&d==="xmlns"&&(_="xmlns",G=""),{prefix:_,local:G}}function jt(d){if(d.strict||(d.attribName=d.attribName[d.looseCase]()),d.attribList.indexOf(d.attribName)!==-1||d.tag.attributes.hasOwnProperty(d.attribName)){d.attribName=d.attribValue="";return}if(d.opt.xmlns){var l=gr(d.attribName,!0),w=l.prefix,_=l.local;if(w==="xmlns")if(_==="xml"&&d.attribValue!==g)K(d,"xml: prefix must be bound to "+g+`
78
+ Actual: `+d.attribValue);else if(_==="xmlns"&&d.attribValue!==h)K(d,"xmlns: prefix must be bound to "+h+`
79
+ Actual: `+d.attribValue);else{var G=d.tag,X=d.tags[d.tags.length-1]||d;G.ns===X.ns&&(G.ns=Object.create(X.ns)),G.ns[_]=d.attribValue}d.attribList.push([d.attribName,d.attribValue])}else d.tag.attributes[d.attribName]=d.attribValue,ee(d,"onattribute",{name:d.attribName,value:d.attribValue});d.attribName=d.attribValue=""}function We(d,l){if(d.opt.xmlns){var w=d.tag,_=gr(d.tagName);w.prefix=_.prefix,w.local=_.local,w.uri=w.ns[_.prefix]||"",w.prefix&&!w.uri&&(K(d,"Unbound namespace prefix: "+JSON.stringify(d.tagName)),w.uri=_.prefix);var G=d.tags[d.tags.length-1]||d;w.ns&&G.ns!==w.ns&&Object.keys(w.ns).forEach(function(Ft){ee(d,"onopennamespace",{prefix:Ft,uri:w.ns[Ft]})});for(var X=0,le=d.attribList.length;X<le;X++){var ie=d.attribList[X],ve=ie[0],$e=ie[1],oe=gr(ve,!0),Qe=oe.prefix,yr=oe.local,On=Qe===""?"":w.ns[Qe]||"",A={name:ve,value:$e,prefix:Qe,local:yr,uri:On};Qe&&Qe!=="xmlns"&&!On&&(K(d,"Unbound namespace prefix: "+JSON.stringify(Qe)),A.uri=Qe),d.tag.attributes[ve]=A,ee(d,"onattribute",A)}d.attribList.length=0}d.tag.isSelfClosing=!!l,d.sawRoot=!0,d.tags.push(d.tag),ee(d,"onopentag",d.tag),l||(!d.noscript&&d.tagName.toLowerCase()==="script"?d.state=y.SCRIPT:d.state=y.TEXT,d.tag=null,d.tagName=""),d.attribName=d.attribValue="",d.attribList.length=0}function ft(d){if(!d.tagName){K(d,"Weird empty close tag."),d.textNode+="</>",d.state=y.TEXT;return}if(d.script){if(d.tagName!=="script"){d.script+="</"+d.tagName+">",d.tagName="",d.state=y.SCRIPT;return}ee(d,"onscript",d.script),d.script=""}var l=d.tags.length,w=d.tagName;d.strict||(w=w[d.looseCase]());for(var _=w;l--&&d.tags[l].name!==_;)K(d,"Unexpected close tag");if(l<0){K(d,"Unmatched closing tag: "+d.tagName),d.textNode+="</"+d.tagName+">",d.state=y.TEXT;return}d.tagName=w;for(var G=d.tags.length;G-- >l;){var X=d.tag=d.tags.pop();d.tagName=d.tag.name,ee(d,"onclosetag",d.tagName);var le={};for(var ie in X.ns)le[ie]=X.ns[ie];var ve=d.tags[d.tags.length-1]||d;d.opt.xmlns&&X.ns!==ve.ns&&Object.keys(X.ns).forEach(function($e){var oe=X.ns[$e];ee(d,"onclosenamespace",{prefix:$e,uri:oe})})}l===0&&(d.closedRoot=!0),d.tagName=d.attribValue=d.attribName="",d.attribList.length=0,d.state=y.TEXT}function Wr(d){var l=d.entity,w=l.toLowerCase(),_,G="";return d.ENTITIES[l]?d.ENTITIES[l]:d.ENTITIES[w]?d.ENTITIES[w]:(l=w,l.charAt(0)==="#"&&(l.charAt(1)==="x"?(l=l.slice(2),_=parseInt(l,16),G=_.toString(16)):(l=l.slice(1),_=parseInt(l,10),G=_.toString(10))),l=l.replace(/^0+/,""),isNaN(_)||G.toLowerCase()!==l?(K(d,"Invalid character entity"),"&"+d.entity+";"):String.fromCodePoint(_))}function Gr(d,l){l==="<"?(d.state=y.OPEN_WAKA,d.startTagPosition=d.position):S(l)||(K(d,"Non-whitespace before first tag."),d.textNode=l,d.state=y.TEXT)}function Jr(d,l){var w="";return l<d.length&&(w=d.charAt(l)),w}function Ge(d){var l=this;if(this.error)throw this.error;if(l.closed)return Tt(l,"Cannot write after close. Assign an onready handler.");if(d===null)return hr(l);typeof d=="object"&&(d=d.toString());for(var w=0,_="";_=Jr(d,w++),l.c=_,!!_;)switch(l.trackPosition&&(l.position++,_===`
80
+ `?(l.line++,l.column=0):l.column++),l.state){case y.BEGIN:if(l.state=y.BEGIN_WHITESPACE,_==="\uFEFF")continue;Gr(l,_);continue;case y.BEGIN_WHITESPACE:Gr(l,_);continue;case y.TEXT:if(l.sawRoot&&!l.closedRoot){for(var G=w-1;_&&_!=="<"&&_!=="&";)_=Jr(d,w++),_&&l.trackPosition&&(l.position++,_===`
81
+ `?(l.line++,l.column=0):l.column++);l.textNode+=d.substring(G,w-1)}_==="<"&&!(l.sawRoot&&l.closedRoot&&!l.strict)?(l.state=y.OPEN_WAKA,l.startTagPosition=l.position):(!S(_)&&(!l.sawRoot||l.closedRoot)&&K(l,"Text data outside of root node."),_==="&"?l.state=y.TEXT_ENTITY:l.textNode+=_);continue;case y.SCRIPT:_==="<"?l.state=y.SCRIPT_ENDING:l.script+=_;continue;case y.SCRIPT_ENDING:_==="/"?l.state=y.CLOSE_TAG:(l.script+="<"+_,l.state=y.SCRIPT);continue;case y.OPEN_WAKA:if(_==="!")l.state=y.SGML_DECL,l.sgmlDecl="";else if(!S(_))if(ae(v,_))l.state=y.OPEN_TAG,l.tagName=_;else if(_==="/")l.state=y.CLOSE_TAG,l.tagName="";else if(_==="?")l.state=y.PROC_INST,l.procInstName=l.procInstBody="";else{if(K(l,"Unencoded <"),l.startTagPosition+1<l.position){var X=l.position-l.startTagPosition;_=new Array(X).join(" ")+_}l.textNode+="<"+_,l.state=y.TEXT}continue;case y.SGML_DECL:(l.sgmlDecl+_).toUpperCase()===f?(ee(l,"onopencdata"),l.state=y.CDATA,l.sgmlDecl="",l.cdata=""):l.sgmlDecl+_==="--"?(l.state=y.COMMENT,l.comment="",l.sgmlDecl=""):(l.sgmlDecl+_).toUpperCase()===p?(l.state=y.DOCTYPE,(l.doctype||l.sawRoot)&&K(l,"Inappropriately located doctype declaration"),l.doctype="",l.sgmlDecl=""):_===">"?(ee(l,"onsgmldeclaration",l.sgmlDecl),l.sgmlDecl="",l.state=y.TEXT):(L(_)&&(l.state=y.SGML_DECL_QUOTED),l.sgmlDecl+=_);continue;case y.SGML_DECL_QUOTED:_===l.q&&(l.state=y.SGML_DECL,l.q=""),l.sgmlDecl+=_;continue;case y.DOCTYPE:_===">"?(l.state=y.TEXT,ee(l,"ondoctype",l.doctype),l.doctype=!0):(l.doctype+=_,_==="["?l.state=y.DOCTYPE_DTD:L(_)&&(l.state=y.DOCTYPE_QUOTED,l.q=_));continue;case y.DOCTYPE_QUOTED:l.doctype+=_,_===l.q&&(l.q="",l.state=y.DOCTYPE);continue;case y.DOCTYPE_DTD:l.doctype+=_,_==="]"?l.state=y.DOCTYPE:L(_)&&(l.state=y.DOCTYPE_DTD_QUOTED,l.q=_);continue;case y.DOCTYPE_DTD_QUOTED:l.doctype+=_,_===l.q&&(l.state=y.DOCTYPE_DTD,l.q="");continue;case y.COMMENT:_==="-"?l.state=y.COMMENT_ENDING:l.comment+=_;continue;case y.COMMENT_ENDING:_==="-"?(l.state=y.COMMENT_ENDED,l.comment=Ur(l.opt,l.comment),l.comment&&ee(l,"oncomment",l.comment),l.comment=""):(l.comment+="-"+_,l.state=y.COMMENT);continue;case y.COMMENT_ENDED:_!==">"?(K(l,"Malformed comment"),l.comment+="--"+_,l.state=y.COMMENT):l.state=y.TEXT;continue;case y.CDATA:_==="]"?l.state=y.CDATA_ENDING:l.cdata+=_;continue;case y.CDATA_ENDING:_==="]"?l.state=y.CDATA_ENDING_2:(l.cdata+="]"+_,l.state=y.CDATA);continue;case y.CDATA_ENDING_2:_===">"?(l.cdata&&ee(l,"oncdata",l.cdata),ee(l,"onclosecdata"),l.cdata="",l.state=y.TEXT):_==="]"?l.cdata+="]":(l.cdata+="]]"+_,l.state=y.CDATA);continue;case y.PROC_INST:_==="?"?l.state=y.PROC_INST_ENDING:S(_)?l.state=y.PROC_INST_BODY:l.procInstName+=_;continue;case y.PROC_INST_BODY:if(!l.procInstBody&&S(_))continue;_==="?"?l.state=y.PROC_INST_ENDING:l.procInstBody+=_;continue;case y.PROC_INST_ENDING:_===">"?(ee(l,"onprocessinginstruction",{name:l.procInstName,body:l.procInstBody}),l.procInstName=l.procInstBody="",l.state=y.TEXT):(l.procInstBody+="?"+_,l.state=y.PROC_INST_BODY);continue;case y.OPEN_TAG:ae(b,_)?l.tagName+=_:(Vr(l),_===">"?We(l):_==="/"?l.state=y.OPEN_TAG_SLASH:(S(_)||K(l,"Invalid character in tag name"),l.state=y.ATTRIB));continue;case y.OPEN_TAG_SLASH:_===">"?(We(l,!0),ft(l)):(K(l,"Forward-slash in opening tag not followed by >"),l.state=y.ATTRIB);continue;case y.ATTRIB:if(S(_))continue;_===">"?We(l):_==="/"?l.state=y.OPEN_TAG_SLASH:ae(v,_)?(l.attribName=_,l.attribValue="",l.state=y.ATTRIB_NAME):K(l,"Invalid attribute name");continue;case y.ATTRIB_NAME:_==="="?l.state=y.ATTRIB_VALUE:_===">"?(K(l,"Attribute without value"),l.attribValue=l.attribName,jt(l),We(l)):S(_)?l.state=y.ATTRIB_NAME_SAW_WHITE:ae(b,_)?l.attribName+=_:K(l,"Invalid attribute name");continue;case y.ATTRIB_NAME_SAW_WHITE:if(_==="=")l.state=y.ATTRIB_VALUE;else{if(S(_))continue;K(l,"Attribute without value"),l.tag.attributes[l.attribName]="",l.attribValue="",ee(l,"onattribute",{name:l.attribName,value:""}),l.attribName="",_===">"?We(l):ae(v,_)?(l.attribName=_,l.state=y.ATTRIB_NAME):(K(l,"Invalid attribute name"),l.state=y.ATTRIB)}continue;case y.ATTRIB_VALUE:if(S(_))continue;L(_)?(l.q=_,l.state=y.ATTRIB_VALUE_QUOTED):(K(l,"Unquoted attribute value"),l.state=y.ATTRIB_VALUE_UNQUOTED,l.attribValue=_);continue;case y.ATTRIB_VALUE_QUOTED:if(_!==l.q){_==="&"?l.state=y.ATTRIB_VALUE_ENTITY_Q:l.attribValue+=_;continue}jt(l),l.q="",l.state=y.ATTRIB_VALUE_CLOSED;continue;case y.ATTRIB_VALUE_CLOSED:S(_)?l.state=y.ATTRIB:_===">"?We(l):_==="/"?l.state=y.OPEN_TAG_SLASH:ae(v,_)?(K(l,"No whitespace between attributes"),l.attribName=_,l.attribValue="",l.state=y.ATTRIB_NAME):K(l,"Invalid attribute name");continue;case y.ATTRIB_VALUE_UNQUOTED:if(!W(_)){_==="&"?l.state=y.ATTRIB_VALUE_ENTITY_U:l.attribValue+=_;continue}jt(l),_===">"?We(l):l.state=y.ATTRIB;continue;case y.CLOSE_TAG:if(l.tagName)_===">"?ft(l):ae(b,_)?l.tagName+=_:l.script?(l.script+="</"+l.tagName,l.tagName="",l.state=y.SCRIPT):(S(_)||K(l,"Invalid tagname in closing tag"),l.state=y.CLOSE_TAG_SAW_WHITE);else{if(S(_))continue;_e(v,_)?l.script?(l.script+="</"+_,l.state=y.SCRIPT):K(l,"Invalid tagname in closing tag."):l.tagName=_}continue;case y.CLOSE_TAG_SAW_WHITE:if(S(_))continue;_===">"?ft(l):K(l,"Invalid characters in closing tag");continue;case y.TEXT_ENTITY:case y.ATTRIB_VALUE_ENTITY_Q:case y.ATTRIB_VALUE_ENTITY_U:var le,ie;switch(l.state){case y.TEXT_ENTITY:le=y.TEXT,ie="textNode";break;case y.ATTRIB_VALUE_ENTITY_Q:le=y.ATTRIB_VALUE_QUOTED,ie="attribValue";break;case y.ATTRIB_VALUE_ENTITY_U:le=y.ATTRIB_VALUE_UNQUOTED,ie="attribValue"}if(_===";")if(l.opt.unparsedEntities){var ve=Wr(l);l.entity="",l.state=le,l.write(ve)}else l[ie]+=Wr(l),l.entity="",l.state=le;else ae(l.entity.length?I:x,_)?l.entity+=_:(K(l,"Invalid character in entity name"),l[ie]+="&"+l.entity+_,l.entity="",l.state=le);continue;default:throw new Error(l,"Unknown state: "+l.state)}return l.position>=l.bufferCheckPosition&&n(l),l}return String.fromCodePoint||(function(){var d=String.fromCharCode,l=Math.floor,w=function(){var _=16384,G=[],X,le,ie=-1,ve=arguments.length;if(!ve)return"";for(var $e="";++ie<ve;){var oe=Number(arguments[ie]);if(!isFinite(oe)||oe<0||oe>1114111||l(oe)!==oe)throw RangeError("Invalid code point: "+oe);oe<=65535?G.push(oe):(oe-=65536,X=(oe>>10)+55296,le=oe%1024+56320,G.push(X,le)),(ie+1===ve||G.length>_)&&($e+=d.apply(null,G),G.length=0)}return $e};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w})(),e},su=Lf();var Pa=`The output should be formatted as a XML file.
82
+ 1. Output should conform to the tags below.
83
+ 2. If tags are not given, make them on your own.
84
+ 3. Remember to always open and close all the tags.
85
+
86
+ As an example, for the tags ["foo", "bar", "baz"]:
87
+ 1. String "<foo>
88
+ <bar>
89
+ <baz></baz>
90
+ </bar>
91
+ </foo>" is a well-formatted instance of the schema.
92
+ 2. String "<foo>
93
+ <bar>
94
+ </foo>" is a badly-formatted instance.
95
+ 3. String "<foo>
96
+ <tag>
97
+ </tag>
98
+ </foo>" is a badly-formatted instance.
99
+
100
+ Here are the output tags:
101
+ \`\`\`
102
+ {tags}
103
+ \`\`\``,iu=class extends Lt{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?Gt(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Ra(e[0].text)}async parse(e){return Ra(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?Pa.replace("{tags}",this.tags?.join(", ")??""):Pa}},jf=e=>e.split(`
104
+ `).map(t=>t.replace(/^\s+/,"")).join(`
105
+ `).trim(),ou=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(ou),t):(t[e.name]=e.text??void 0,t)};function Ra(e){let t=jf(e),r=su.parser(!0),n={},a=[];r.onopentag=o=>{let c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};a.length>0?a[a.length-1].children.push(c):n=c,o.isSelfClosing||a.push(c)},r.onclosetag=()=>{if(a.length>0){let o=a.pop();a.length===0&&o&&(n=o)}},r.ontext=o=>{if(a.length>0){let c=a[a.length-1];c.text+=o}},r.onattribute=o=>{if(a.length>0){let c=a[a.length-1];c.attributes[o.name]=o.value}};let s=/```(xml)?(.*)```/s.exec(t),i=s?s[2]:t;return r.write(i).close(),n&&n.name==="?xml"&&(n=n.children[0]),ou(n)}var cx=M({AsymmetricStructuredOutputParser:()=>au,BaseCumulativeTransformOutputParser:()=>Lt,BaseLLMOutputParser:()=>Xs,BaseOutputParser:()=>bt,BaseTransformOutputParser:()=>wt,BytesOutputParser:()=>Xc,CommaSeparatedListOutputParser:()=>Qc,CustomListOutputParser:()=>eu,JsonMarkdownStructuredOutputParser:()=>Qs,JsonOutputParser:()=>Ia,ListOutputParser:()=>Zr,MarkdownListOutputParser:()=>ru,NumberedListOutputParser:()=>tu,OutputParserException:()=>ye,StandardSchemaOutputParser:()=>Na,StringOutputParser:()=>nu,StructuredOutputParser:()=>Sn,XMLOutputParser:()=>iu,XML_FORMAT_INSTRUCTIONS:()=>Pa,parseJsonMarkdown:()=>zt,parsePartialJson:()=>Hr,parseXMLMarkdown:()=>Ra});function ei(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=Hr(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(a){throw new ye([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${a.message}`].join(`
106
+ `))}let n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function cu(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 uu(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var ti=class extends Lt{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 xt(e[0]),await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let r=e[0].message,n;if(Tr(r)&&r.tool_calls?.length?n=r.tool_calls.map(s=>{let{id:i,...o}=s;return this.returnId?{id:i,...o}:o}):r.additional_kwargs.tool_calls!==void 0&&(n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(s=>ei(s,{returnId:this.returnId,partial:t}))),!n)return[];let a=[];for(let s of n)if(s!==void 0){let i={type:s.name,args:s.args,id:s.id};a.push(i)}return a}},Ma=class extends ti{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 r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new ye(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let t=await Qn(this.zodSchema,e);if(t.success)return t.data;throw new ye(`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(n=>n.type===this.keyName),r=t;if(t.length)return this.returnId||(r=t.map(n=>n.args)),this.returnSingle?r[0]:r}async parseResult(e){xt(e[0]);let t=(await super.parsePartialResult(e,!1)).filter(n=>n.type===this.keyName),r=t;if(t.length)return this.returnId||(r=t.map(n=>n.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(n=>this._validateResult(n)))}};var Px=M({assembleStructuredOutputPipeline:()=>ri,createContentParser:()=>Ff,createFunctionCallingParser:()=>zf});function Ff(e){return Se(e)?Sn.fromZodSchema(e):dr(e)?Na.fromSerializableSchema(e):new Ia}function zf(e,t,r){let n=r??Ma;return Se(e)?new n({returnSingle:!0,keyName:t,zodSchema:e}):dr(e)?new n({returnSingle:!0,keyName:t,serializableSchema:e}):new n({returnSingle:!0,keyName:t})}function ri(e,t,r,n){if(!r){let c=e.pipe(t);return n?c.withConfig({runName:n}):c}let a=pr.assign({parsed:(c,u)=>t.invoke(c.raw,u)}),s=pr.assign({parsed:()=>null}),i=a.withFallbacks({fallbacks:[s]}),o=zr.from([{raw:e},i]);return n?o.withConfig({runName:n}):o}var lu=e=>e();function En(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var rk=M({BaseChatModel:()=>du,SimpleChatModel:()=>Bf});function ni(e){let t=[];for(let r of e){let n=r;if(Array.isArray(r.content))for(let a=0;a<r.content.length;a++){let s=r.content[a];(Pn(s)||Rn(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,a),Mn(s),...r.content.slice(a+1)]}))}t.push(n)}return t}var du=class lt extends bn{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=lu(()=>{let r=t.outputVersion??_r("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async invoke(t,r){let n=lt._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}async*_streamChatModelEvents(t,r,n){let a=this._streamResponseChunks(t,r,n);yield*Vs(a,{signal:r.signal})}streamEvents(t,r,n){if(r?.version==="v1"||r?.version==="v2")return super.streamEvents(t,r,n);let a=lt._convertInputToPromptValue(t).toChatMessages(),[,s]=this._separateRunnableConfigFromCallOptionsCompat(r),i=this._streamChatModelEvents(a,s);return new va(i)}streamV2(t,r){return this.streamEvents(t,r)}async*_streamIterator(t,r){if(this._streamResponseChunks===lt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{let n=lt._convertInputToPromptValue(t).toChatMessages(),[a,s]=this._separateRunnableConfigFromCallOptionsCompat(r),i={...a.metadata,...this.getLsParamsWithDefaults(s)},o=this._getInvocationParamsForTracing(s),c=await et.configure(a.callbacks,this.callbacks,a.tags,this.tags,i,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),u={options:this._getCallOptionsForTracing(s,o),invocation_params:o,batch_size:1},f=s.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[ni(n)],a.runId,void 0,u,void 0,void 0,a.runName),g;try{for await(let m of this._streamResponseChunks(n,s,p?.[0])){if(s.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},f==="v1"?yield En(m.message):yield m.message,g?g=g.concat(m):g=m}s.signal?.throwIfAborted()}catch(m){throw await Promise.all((p??[]).map(v=>v?.handleLLMError(m))),m}let h;g&&pe.isInstance(g.message)&&g.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:g.message.usage_metadata.input_tokens,completionTokens:g.message.usage_metadata.output_tokens,totalTokens:g.message.usage_metadata.total_tokens}}),await Promise.all((p??[]).map(m=>m?.handleLLMEnd({generations:[[g]],llmOutput:h})))}}getLsParams(t){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}getLsParamsWithDefaults(t){return{...this.getLsParams(t),ls_integration:"langchain_chat_model"}}async _generateUncached(t,r,n,a){let s=t.map(h=>h.map(Et)),i;if(a!==void 0&&a.length===s.length)i=a;else{let h={...n.metadata,...this.getLsParamsWithDefaults(r)},m=this._getInvocationParamsForTracing(r),v=await et.configure(n.callbacks,this.callbacks,n.tags,this.tags,h,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(m)}),b={options:this._getCallOptionsForTracing(r,m),invocation_params:m,batch_size:1};i=await v?.handleChatModelStart(this.toJSON(),s.map(ni),n.runId,void 0,b,void 0,void 0,n.runName)}let o=r.outputVersion??this.outputVersion,c=[],u=[],f=!!i?.[0].handlers.find(ui),p=!!i?.[0].handlers.find(In);if(f&&!this.disableStreaming&&s.length===1&&(this._streamChatModelEvents!==lt.prototype._streamChatModelEvents||this._streamResponseChunks!==lt.prototype._streamResponseChunks))try{let h=!1,m=i?.[0],v=this._streamChatModelEvents(s[0],r),b=await new va({async*[Symbol.asyncIterator](){for await(let S of v){r.signal?.throwIfAborted(),h=!0;let L=S.event==="message-start"&&S.id==null&&m?.runId!=null?{...S,id:`run-${m.runId}`}:S;await m?.handleChatModelStreamEvent(L),yield L}}});if(r.signal?.throwIfAborted(),!h)throw new Error("Received empty response from chat model call.");if(b.id==null){let S=i?.at(0)?.runId;S!=null&&b._updateId(`run-${S}`)}let x={text:b.text,message:b};c.push([x]);let I=b.usage_metadata!==void 0?{tokenUsage:{promptTokens:b.usage_metadata.input_tokens,completionTokens:b.usage_metadata.output_tokens,totalTokens:b.usage_metadata.total_tokens}}:void 0;await i?.[0].handleLLMEnd({generations:c,llmOutput:I})}catch(h){throw await i?.[0].handleLLMError(h),h}else if(p&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==lt.prototype._streamResponseChunks)try{let h=await this._streamResponseChunks(s[0],r,i?.[0]),m;for await(let b of h){if(r.signal?.aborted){let x=m?.message;throw new $a("Model invocation was aborted.",x)}if(b.message.id==null){let x=i?.at(0)?.runId;x!=null&&b.message._updateId(`run-${x}`)}m===void 0?m=b:m=Pe(m,b)}if(r.signal?.aborted){let b=m?.message;throw new $a("Model invocation was aborted.",b)}if(m===void 0)throw new Error("Received empty response from chat model call.");o==="v1"&&(m.message=En(m.message)),c.push([m]);let v;pe.isInstance(m.message)&&m.message.usage_metadata!==void 0&&(v={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}}),await i?.[0].handleLLMEnd({generations:c,llmOutput:v})}catch(h){throw await i?.[0].handleLLMError(h),h}else{let h=await Promise.allSettled(s.map(async(m,v)=>{let b=await this._generate(m,{...r,promptIndex:v},i?.[v]);if(o==="v1")for(let x of b.generations)x.message=En(x.message);return b}));await Promise.all(h.map(async(m,v)=>{if(m.status==="fulfilled"){let b=m.value;for(let x of b.generations){if(x.message.id==null){let I=i?.at(0)?.runId;I!=null&&x.message._updateId(`run-${I}`)}x.message.response_metadata={...x.generationInfo,...x.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),c[v]=b.generations,u[v]=b.llmOutput,i?.[v]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await i?.[v]?.handleLLMError(m.reason),Promise.reject(m.reason)}))}let g={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(g,Jt,{value:i?{runIds:i?.map(h=>h.runId)}:void 0,configurable:!0}),g}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s}){let i=t.map(x=>x.map(Et)),o={...s.metadata,...this.getLsParamsWithDefaults(a)},c=this._getInvocationParamsForTracing(a),u=await et.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),f={options:this._getCallOptionsForTracing(a,c),invocation_params:c,batch_size:1},p=await u?.handleChatModelStart(this.toJSON(),i.map(ni),s.runId,void 0,f,void 0,void 0,s.runName),g=[],h=(await Promise.allSettled(i.map(async(x,I)=>{let S=lt._convertInputToPromptValue(x).toString(),L=await r.lookup(S,n);return L==null&&g.push(I),L}))).map((x,I)=>({result:x,runManager:p?.[I]})).filter(({result:x})=>x.status==="fulfilled"&&x.value!=null||x.status==="rejected"),m=a.outputVersion??this.outputVersion,v=[];await Promise.all(h.map(async({result:x,runManager:I},S)=>{if(x.status==="fulfilled"){let L=x.value;return v[S]=L.map(W=>("message"in W&&Oe(W.message)&&Tr(W.message)&&(W.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m==="v1"&&(W.message=En(W.message))),W.generationInfo={...W.generationInfo,tokenUsage:{}},W)),L.length&&await I?.handleLLMNewToken(L[0].text),I?.handleLLMEnd({generations:[L]},void 0,void 0,void 0,{cached:!0})}else return await I?.handleLLMError(x.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(x.reason)}));let b={generations:v,missingPromptIndices:g,startedRunManagers:p};return Object.defineProperty(b,Jt,{value:p?{runIds:p?.map(x=>x.runId)}:void 0,configurable:!0}),b}async generate(t,r,n){let a;Array.isArray(r)?a={stop:r}:a=r;let s=t.map(m=>m.map(Et)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(s,o,i);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:f,missingPromptIndices:p,startedRunManagers:g}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i}),h={};if(p.length>0){let m=await this._generateUncached(p.map(v=>s[v]),o,i,g!==void 0?p.map(v=>g?.[v]):void 0);await Promise.all(m.generations.map(async(v,b)=>{let x=p[b];f[x]=v;let I=lt._convertInputToPromptValue(s[x]).toString();return c.update(I,u,v)})),h=m.llmOutput??{}}return{generations:f,llmOutput:h}}_getInvocationParamsForTracing(t){return this.invocationParams(t)}_getCallOptionsForTracing(t,r){return t}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,n){let a=t.map(s=>s.toChatMessages());return this.generate(a,r,n)}withStructuredOutput(t,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let n=t,a=r?.name,s=Or(n)??"A function available to call.",i=r?.method,o=r?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=a??"extract";!Se(n)&&!dr(n)&&"name"in n&&(c=n.name);let u=Se(n)||dr(n)?ct(n):n,f=[{type:"function",function:{name:c,description:s,parameters:u}}],p=this.bindTools(f),g=Ze.from(h=>{if(!pe.isInstance(h))throw new Error("Input is not an AIMessageChunk.");if(!h.tool_calls||h.tool_calls.length===0)throw new Error("No tool calls found in the response.");let m=h.tool_calls.find(v=>v.name===c);if(!m)throw new Error(`No tool call found with name ${c}.`);return m.args});return ri(p,g,o,o?"StructuredOutputRunnable":"StructuredOutput")}},Bf=class extends du{async _generate(e,t,r){let n=await this._call(e,t,r),a=new Je(n);if(typeof a.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:a.content,message:a}]}}};var dk=M({BaseLLM:()=>fu,LLM:()=>Zf}),fu=class An extends bn{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){let n=An._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async*_streamIterator(t,r){if(this._streamResponseChunks===An.prototype._streamResponseChunks)yield this.invoke(t,r);else{let n=An._convertInputToPromptValue(t),[a,s]=this._separateRunnableConfigFromCallOptionsCompat(r),i=this.invocationParams(s),o=await et.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(i)}),c={options:s,invocation_params:i,batch_size:1},u=await o?.handleLLMStart(this.toJSON(),[n.toString()],a.runId,void 0,c,void 0,void 0,a.runName),f=new mt({text:""});try{for await(let p of this._streamResponseChunks(n.toString(),s,u?.[0]))f?f=f.concat(p):f=p,typeof p.text=="string"&&(yield p.text)}catch(p){throw await Promise.all((u??[]).map(g=>g?.handleLLMError(p))),p}await Promise.all((u??[]).map(p=>p?.handleLLMEnd({generations:[[f]]})))}}async generatePrompt(t,r,n){let a=t.map(s=>s.toString());return this.generate(a,r,n)}invocationParams(t){return{}}_flattenLLMResult(t){let r=[];for(let n=0;n<t.generations.length;n+=1){let a=t.generations[n];if(n===0)r.push({generations:[a],llmOutput:t.llmOutput});else{let s=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[a],llmOutput:s})}}return r}async _generateUncached(t,r,n,a){let s;if(a!==void 0&&a.length===t.length)s=a;else{let u=this.invocationParams(r),f=await et.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(u)}),p={options:r,invocation_params:u,batch_size:t.length};s=await f?.handleLLMStart(this.toJSON(),t,n.runId,void 0,p,void 0,void 0,n?.runName)}let i=!!s?.[0].handlers.find(In),o;if(i&&t.length===1&&this._streamResponseChunks!==An.prototype._streamResponseChunks)try{let u=await this._streamResponseChunks(t[0],r,s?.[0]),f;for await(let p of u)f===void 0?f=p:f=Pe(f,p);if(f===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[f]],llmOutput:{}},await s?.[0].handleLLMEnd(o)}catch(u){throw await s?.[0].handleLLMError(u),u}else{try{o=await this._generate(t,r,s?.[0])}catch(f){throw await Promise.all((s??[]).map(p=>p?.handleLLMError(f))),f}let u=this._flattenLLMResult(o);await Promise.all((s??[]).map((f,p)=>f?.handleLLMEnd(u[p])))}let c=s?.map(u=>u.runId)||void 0;return Object.defineProperty(o,Jt,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:t,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s,runId:i}){let o=this.invocationParams(a),c=await et.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),u={options:a,invocation_params:o,batch_size:t.length},f=await c?.handleLLMStart(this.toJSON(),t,i,void 0,u,void 0,void 0,s?.runName),p=[],g=(await Promise.allSettled(t.map(async(v,b)=>{let x=await r.lookup(v,n);return x==null&&p.push(b),x}))).map((v,b)=>({result:v,runManager:f?.[b]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),h=[];await Promise.all(g.map(async({result:v,runManager:b},x)=>{if(v.status==="fulfilled"){let I=v.value;return h[x]=I.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),I.length&&await b?.handleLLMNewToken(I[0].text),b?.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await b?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));let m={generations:h,missingPromptIndices:p,startedRunManagers:f};return Object.defineProperty(m,Jt,{value:f?{runIds:f?.map(v=>v.runId)}:void 0,configurable:!0}),m}async generate(t,r,n){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let a;Array.isArray(r)?a={stop:r}:a=r;let[s,i]=this._separateRunnableConfigFromCallOptionsCompat(a);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(t,i,s);let{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:u,missingPromptIndices:f,startedRunManagers:p}=await this._generateCached({prompts:t,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:s,runId:s.runId}),g={};if(f.length>0){let h=await this._generateUncached(f.map(m=>t[m]),i,s,p!==void 0?f.map(m=>p?.[m]):void 0);await Promise.all(h.generations.map(async(m,v)=>{let b=f[v];return u[b]=m,o.update(t[b],c,m)})),g=h.llmOutput??{}}return{generations:u,llmOutput:g}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Zf=class extends fu{async _generate(e,t,r){return{generations:await Promise.all(e.map((n,a)=>this._call(n,{...t,promptIndex:a},r).then(s=>[{text:s}])))}}};var gk=M({JsonOutputKeyToolsParser:()=>Ma,JsonOutputToolsParser:()=>ti,convertLangChainToolCallToOpenAI:()=>cu,makeInvalidToolCall:()=>uu,parseToolCall:()=>ei});var vk=M({chunkArray:()=>Uf}),Uf=(e,t)=>e.reduce((r,n,a)=>{let s=Math.floor(a/t);return r[s]=(r[s]||[]).concat([n]),r},[]);var Tk=M({convertToOpenAIFunction:()=>pu,convertToOpenAITool:()=>Vf,isLangChainTool:()=>Tn,isRunnableToolLike:()=>xn,isStructuredTool:()=>wn,isStructuredToolParams:()=>kn});function pu(e,t){let r=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:ct(e.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function Vf(e,t){let r=typeof t=="number"?void 0:t,n;return Tn(e)?n={type:"function",function:pu(e)}:n=e,r?.strict!==void 0&&(n.function.strict=r.strict),n}var Ok=M({DEFAULT_LANGSMITH_GATEWAY:()=>mu,resolveLangSmithGatewayConfig:()=>Yf}),Wf="LANGSMITH_GATEWAY",Gf="LANGSMITH_GATEWAY_API_KEY",Jf="LANGSMITH_API_KEY",mu="https://gateway.smith.langchain.com",qf=["true","1","yes"],Hf=["false","0","no"];function Kf(e){let t=_r(Wf);if(!(!t||Hf.includes(t.toLowerCase())))return`${qf.includes(t.toLowerCase())?mu:t.replace(/\/+$/,"")}/${e}`}function Yf({baseURL:e,providerPath:t}){if(e!==void 0)return{baseURL:e};let r=Kf(t);return r===void 0?{}:{baseURL:r,apiKey:_r(Gf)||_r(Jf)}}export{Gt as a,Ne as b,gp as c,be as d,Ct as e,Sp as f,Ip as g,Jn as h,Gp as i,te as j,ce as k,Se as l,Qn as m,Co as n,Or as o,No as p,Yn as q,Po as r,Ro as s,Mo as t,$o as u,T as v,we as w,by as x,dr as y,da as z,Vy as A,ct as B,Yy as C,fa as D,Q as E,$t as F,zr as G,Ze as H,Me as I,mv as J,M0 as K,Gs as L,Js as M,ff as N,xa as O,w0 as P,A0 as Q,$b as R,Df as S,q0 as T,nb as U,Of as V,bn as W,pr as X,a0 as Y,Xs as Z,bt as _,Lt as $,nw as aa,Ia as ba,cx as ca,ei as da,cu as ea,uu as fa,c0 as ga,Px as ha,Ff as ia,zf as ja,ri as ka,_v as la,va as ma,f0 as na,ba as oa,rk as pa,du as qa,dk as ra,Zf as sa,g0 as ta,tf as ua,gk as va,Tn as wa,Eb as xa,Ys as ya,Pf as za,vk as Aa,Tk as Ba,Vf as Ca,Ok as Da,mu as Ea,Yf as Fa};