@midscene/android-playground 0.26.7-beta-20250818035341.0 → 0.26.7-beta-20250820105545.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! For license information please see 806.d6c23766.js.LICENSE.txt */
1
+ /*! For license information please see 806.8de50496.js.LICENSE.txt */
2
2
  (self.webpackChunkandroid_playground=self.webpackChunkandroid_playground||[]).push([["806"],{25537:function(e,t,r){"use strict";r.d(t,{iN:()=>T,R_:()=>b,EV:()=>E,Ti:()=>$,ez:()=>_});var n=r(20117),i=r(76981),o=2,a=.16,s=.05,l=.05,u=.15,c=5,h=4,f=[{index:7,opacity:.15},{index:6,opacity:.25},{index:5,opacity:.3},{index:5,opacity:.45},{index:5,opacity:.65},{index:5,opacity:.85},{index:4,opacity:.9},{index:3,opacity:.95},{index:2,opacity:.97},{index:1,opacity:.98}];function d(e){var t=e.r,r=e.g,i=e.b,o=(0,n.py)(t,r,i);return{h:360*o.h,s:o.s,v:o.v}}function p(e){var t=e.r,r=e.g,i=e.b;return"#".concat((0,n.vq)(t,r,i,!1))}function m(e,t,r){var n=r/100;return{r:(t.r-e.r)*n+e.r,g:(t.g-e.g)*n+e.g,b:(t.b-e.b)*n+e.b}}function g(e,t,r){var n;return(n=Math.round(e.h)>=60&&240>=Math.round(e.h)?r?Math.round(e.h)-o*t:Math.round(e.h)+o*t:r?Math.round(e.h)+o*t:Math.round(e.h)-o*t)<0?n+=360:n>=360&&(n-=360),n}function y(e,t,r){var n;return 0===e.h&&0===e.s?e.s:((n=r?e.s-a*t:t===h?e.s+a:e.s+s*t)>1&&(n=1),r&&t===c&&n>.1&&(n=.1),n<.06&&(n=.06),Number(n.toFixed(2)))}function v(e,t,r){var n;return(n=r?e.v+l*t:e.v-u*t)>1&&(n=1),Number(n.toFixed(2))}function b(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[],n=(0,i.uA)(e),o=c;o>0;o-=1){var a=d(n),s=p((0,i.uA)({h:g(a,o,!0),s:y(a,o,!0),v:v(a,o,!0)}));r.push(s)}r.push(p(n));for(var l=1;l<=h;l+=1){var u=d(n),b=p((0,i.uA)({h:g(u,l),s:y(u,l),v:v(u,l)}));r.push(b)}return"dark"===t.theme?f.map(function(e){var n=e.index,o=e.opacity;return p(m((0,i.uA)(t.backgroundColor||"#141414"),(0,i.uA)(r[n]),100*o))}):r}var _={red:"#F5222D",volcano:"#FA541C",orange:"#FA8C16",gold:"#FAAD14",yellow:"#FADB14",lime:"#A0D911",green:"#52C41A",cyan:"#13C2C2",blue:"#1677FF",geekblue:"#2F54EB",purple:"#722ED1",magenta:"#EB2F96",grey:"#666666"},w=["#fff1f0","#ffccc7","#ffa39e","#ff7875","#ff4d4f","#f5222d","#cf1322","#a8071a","#820014","#5c0011"];w.primary=w[5];var x=["#fff2e8","#ffd8bf","#ffbb96","#ff9c6e","#ff7a45","#fa541c","#d4380d","#ad2102","#871400","#610b00"];x.primary=x[5];var S=["#fff7e6","#ffe7ba","#ffd591","#ffc069","#ffa940","#fa8c16","#d46b08","#ad4e00","#873800","#612500"];S.primary=S[5];var E=["#fffbe6","#fff1b8","#ffe58f","#ffd666","#ffc53d","#faad14","#d48806","#ad6800","#874d00","#613400"];E.primary=E[5];var C=["#feffe6","#ffffb8","#fffb8f","#fff566","#ffec3d","#fadb14","#d4b106","#ad8b00","#876800","#614700"];C.primary=C[5];var A=["#fcffe6","#f4ffb8","#eaff8f","#d3f261","#bae637","#a0d911","#7cb305","#5b8c00","#3f6600","#254000"];A.primary=A[5];var k=["#f6ffed","#d9f7be","#b7eb8f","#95de64","#73d13d","#52c41a","#389e0d","#237804","#135200","#092b00"];k.primary=k[5];var O=["#e6fffb","#b5f5ec","#87e8de","#5cdbd3","#36cfc9","#13c2c2","#08979c","#006d75","#00474f","#002329"];O.primary=O[5];var T=["#e6f4ff","#bae0ff","#91caff","#69b1ff","#4096ff","#1677ff","#0958d9","#003eb3","#002c8c","#001d66"];T.primary=T[5];var I=["#f0f5ff","#d6e4ff","#adc6ff","#85a5ff","#597ef7","#2f54eb","#1d39c4","#10239e","#061178","#030852"];I.primary=I[5];var P=["#f9f0ff","#efdbff","#d3adf7","#b37feb","#9254de","#722ed1","#531dab","#391085","#22075e","#120338"];P.primary=P[5];var R=["#fff0f6","#ffd6e7","#ffadd2","#ff85c0","#f759ab","#eb2f96","#c41d7f","#9e1068","#780650","#520339"];R.primary=R[5];var M=["#a6a6a6","#999999","#8c8c8c","#808080","#737373","#666666","#404040","#1a1a1a","#000000","#000000"];M.primary=M[5];var $={red:w,volcano:x,orange:S,gold:E,yellow:C,lime:A,green:k,cyan:O,blue:T,geekblue:I,purple:P,magenta:R,grey:M},N=["#2a1215","#431418","#58181c","#791a1f","#a61d24","#d32029","#e84749","#f37370","#f89f9a","#fac8c3"];N.primary=N[5];var j=["#2b1611","#441d12","#592716","#7c3118","#aa3e19","#d84a1b","#e87040","#f3956a","#f8b692","#fad4bc"];j.primary=j[5];var B=["#2b1d11","#442a11","#593815","#7c4a15","#aa6215","#d87a16","#e89a3c","#f3b765","#f8cf8d","#fae3b7"];B.primary=B[5];var L=["#2b2111","#443111","#594214","#7c5914","#aa7714","#d89614","#e8b339","#f3cc62","#f8df8b","#faedb5"];L.primary=L[5];var F=["#2b2611","#443b11","#595014","#7c6e14","#aa9514","#d8bd14","#e8d639","#f3ea62","#f8f48b","#fafab5"];F.primary=F[5];var D=["#1f2611","#2e3c10","#3e4f13","#536d13","#6f9412","#8bbb11","#a9d134","#c9e75d","#e4f88b","#f0fab5"];D.primary=D[5];var z=["#162312","#1d3712","#274916","#306317","#3c8618","#49aa19","#6abe39","#8fd460","#b2e58b","#d5f2bb"];z.primary=z[5];var U=["#112123","#113536","#144848","#146262","#138585","#13a8a8","#33bcb7","#58d1c9","#84e2d8","#b2f1e8"];U.primary=U[5];var Z=["#111a2c","#112545","#15325b","#15417e","#1554ad","#1668dc","#3c89e8","#65a9f3","#8dc5f8","#b7dcfa"];Z.primary=Z[5];var H=["#131629","#161d40","#1c2755","#203175","#263ea0","#2b4acb","#5273e0","#7f9ef3","#a8c1f8","#d2e0fa"];H.primary=H[5];var G=["#1a1325","#24163a","#301c4d","#3e2069","#51258f","#642ab5","#854eca","#ab7ae0","#cda8f0","#ebd7fa"];G.primary=G[5];var W=["#291321","#40162f","#551c3b","#75204f","#a02669","#cb2b83","#e0529c","#f37fb7","#f8a8cc","#fad2e3"];W.primary=W[5];var q=["#151515","#1f1f1f","#2d2d2d","#393939","#494949","#5a5a5a","#6a6a6a","#7b7b7b","#888888","#969696"];q.primary=q[5]},1781:function(e,t,r){"use strict";r.d(t,{IX:()=>C,rb:()=>N});var n=r(52655),i=r(57987),o=r(50793),a=r(19741),s=r(44194),l=r(99607),u=r(71123),c=r(83739),h=r(61764),f=r(14425),d=r(20652);let p=(0,c.Z)(function e(){(0,u.Z)(this,e)});var m="CALC_UNIT",g=RegExp(m,"g");function y(e){return"number"==typeof e?"".concat(e).concat(m):e}var v=function(e){(0,f.Z)(r,e);var t=(0,d.Z)(r);function r(e,i){(0,u.Z)(this,r),a=t.call(this),(0,o.Z)((0,h.Z)(a),"result",""),(0,o.Z)((0,h.Z)(a),"unitlessCssVar",void 0),(0,o.Z)((0,h.Z)(a),"lowPriority",void 0);var a,s=(0,n.Z)(e);return a.unitlessCssVar=i,e instanceof r?a.result="(".concat(e.result,")"):"number"===s?a.result=y(e):"string"===s&&(a.result=e),a}return(0,c.Z)(r,[{key:"add",value:function(e){return e instanceof r?this.result="".concat(this.result," + ").concat(e.getResult()):("number"==typeof e||"string"==typeof e)&&(this.result="".concat(this.result," + ").concat(y(e))),this.lowPriority=!0,this}},{key:"sub",value:function(e){return e instanceof r?this.result="".concat(this.result," - ").concat(e.getResult()):("number"==typeof e||"string"==typeof e)&&(this.result="".concat(this.result," - ").concat(y(e))),this.lowPriority=!0,this}},{key:"mul",value:function(e){return this.lowPriority&&(this.result="(".concat(this.result,")")),e instanceof r?this.result="".concat(this.result," * ").concat(e.getResult(!0)):("number"==typeof e||"string"==typeof e)&&(this.result="".concat(this.result," * ").concat(e)),this.lowPriority=!1,this}},{key:"div",value:function(e){return this.lowPriority&&(this.result="(".concat(this.result,")")),e instanceof r?this.result="".concat(this.result," / ").concat(e.getResult(!0)):("number"==typeof e||"string"==typeof e)&&(this.result="".concat(this.result," / ").concat(e)),this.lowPriority=!1,this}},{key:"getResult",value:function(e){return this.lowPriority||e?"(".concat(this.result,")"):this.result}},{key:"equal",value:function(e){var t=this,r=(e||{}).unit,n=!0;return("boolean"==typeof r?n=r:Array.from(this.unitlessCssVar).some(function(e){return t.result.includes(e)})&&(n=!1),this.result=this.result.replace(g,n?"px":""),void 0!==this.lowPriority)?"calc(".concat(this.result,")"):this.result}}]),r}(p);let b=function(e){(0,f.Z)(r,e);var t=(0,d.Z)(r);function r(e){var n;return(0,u.Z)(this,r),n=t.call(this),(0,o.Z)((0,h.Z)(n),"result",0),e instanceof r?n.result=e.result:"number"==typeof e&&(n.result=e),n}return(0,c.Z)(r,[{key:"add",value:function(e){return e instanceof r?this.result+=e.result:"number"==typeof e&&(this.result+=e),this}},{key:"sub",value:function(e){return e instanceof r?this.result-=e.result:"number"==typeof e&&(this.result-=e),this}},{key:"mul",value:function(e){return e instanceof r?this.result*=e.result:"number"==typeof e&&(this.result*=e),this}},{key:"div",value:function(e){return e instanceof r?this.result/=e.result:"number"==typeof e&&(this.result/=e),this}},{key:"equal",value:function(){return this.result}}]),r}(p),_=function(e,t){var r="css"===e?v:b;return function(e){return new r(e,t)}},w=function(e,t){return"".concat([t,e.replace(/([A-Z]+)([A-Z][a-z]+)/g,"$1-$2").replace(/([a-z])([A-Z])/g,"$1-$2")].filter(Boolean).join("-"))};r(69580);let x=function(e,t,r,n){var o=(0,a.Z)({},t[e]);null!=n&&n.deprecatedTokens&&n.deprecatedTokens.forEach(function(e){var t,r=(0,i.Z)(e,2),n=r[0],a=r[1];(null!=o&&o[n]||null!=o&&o[a])&&(null!=(t=o[a])||(o[a]=null==o?void 0:o[n]))});var s=(0,a.Z)((0,a.Z)({},r),o);return Object.keys(s).forEach(function(e){s[e]===t[e]&&delete s[e]}),s};var S="undefined"!=typeof CSSINJS_STATISTIC,E=!0;function C(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(!S)return Object.assign.apply(Object,[{}].concat(t));E=!1;var i={};return t.forEach(function(e){if("object"===(0,n.Z)(e)){var t=Object.keys(e);t.forEach(function(t){Object.defineProperty(i,t,{configurable:!0,enumerable:!0,get:function(){return e[t]}})})}}),E=!0,i}var A={};function k(){}let O=function(e){var t,r=e,n=k;return S&&"undefined"!=typeof Proxy&&(t=new Set,r=new Proxy(e,{get:function(e,r){if(E){var n;null==(n=t)||n.add(r)}return e[r]}}),n=function(e,r){var n;A[e]={global:Array.from(t),component:(0,a.Z)((0,a.Z)({},null==(n=A[e])?void 0:n.component),r)}}),{token:r,keys:t,flush:n}},T=function(e,t,r){if("function"==typeof r){var n;return r(C(t,null!=(n=t[e])?n:{}))}return null!=r?r:{}},I=function(e){return"js"===e?{max:Math.max,min:Math.min}:{max:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return"max(".concat(t.map(function(e){return(0,l.bf)(e)}).join(","),")")},min:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return"min(".concat(t.map(function(e){return(0,l.bf)(e)}).join(","),")")}}};var P=6e5,R=new(function(){function e(){(0,u.Z)(this,e),(0,o.Z)(this,"map",new Map),(0,o.Z)(this,"objectIDMap",new WeakMap),(0,o.Z)(this,"nextID",0),(0,o.Z)(this,"lastAccessBeat",new Map),(0,o.Z)(this,"accessBeat",0)}return(0,c.Z)(e,[{key:"set",value:function(e,t){this.clear();var r=this.getCompositeKey(e);this.map.set(r,t),this.lastAccessBeat.set(r,Date.now())}},{key:"get",value:function(e){var t=this.getCompositeKey(e),r=this.map.get(t);return this.lastAccessBeat.set(t,Date.now()),this.accessBeat+=1,r}},{key:"getCompositeKey",value:function(e){var t=this;return e.map(function(e){return e&&"object"===(0,n.Z)(e)?"obj_".concat(t.getObjectID(e)):"".concat((0,n.Z)(e),"_").concat(e)}).join("|")}},{key:"getObjectID",value:function(e){if(this.objectIDMap.has(e))return this.objectIDMap.get(e);var t=this.nextID;return this.objectIDMap.set(e,t),this.nextID+=1,t}},{key:"clear",value:function(){var e=this;if(this.accessBeat>1e4){var t=Date.now();this.lastAccessBeat.forEach(function(r,n){t-r>P&&(e.map.delete(n),e.lastAccessBeat.delete(n))}),this.accessBeat=0}}}]),e}());let M=function(e,t){return s.useMemo(function(){var r=R.get(t);if(r)return r;var n=e();return R.set(t,n),n},t)},$=function(){return{}},N=function(e){var t=e.useCSP,r=void 0===t?$:t,u=e.useToken,c=e.usePrefix,h=e.getResetStyles,f=e.getCommonStyle,d=e.getCompUnitless;function p(e,t,r){var n=r.unitless,i=r.injectStyle,o=void 0===i||i,a=r.prefixToken,c=r.ignore,h=function(i){var o=i.rootCls,s=i.cssVar,h=void 0===s?{}:s,f=u().realToken;return(0,l.CI)({path:[e],prefix:h.prefix,key:h.key,unitless:n,ignore:c,token:f,scope:o},function(){var n=T(e,f,t),i=x(e,f,n,{deprecatedTokens:null==r?void 0:r.deprecatedTokens});return Object.keys(n).forEach(function(e){i[a(e)]=i[e],delete i[e]}),i}),null};return function(t){var r=u().cssVar;return[function(n){return o&&r?s.createElement(s.Fragment,null,s.createElement(h,{rootCls:t,cssVar:r,component:e}),n):n},null==r?void 0:r.key]}}function m(t,o,s){var d=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},p=Array.isArray(t)?t:[t,t],m=(0,i.Z)(p,1)[0],g=p.join("-"),y=e.layer||{name:"antd"};return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=u(),p=i.theme,v=i.realToken,b=i.hashId,S=i.token,E=i.cssVar,A=c(),k=A.rootPrefixCls,P=A.iconPrefixCls,R=r(),$=E?"css":"js",N=M(function(){var e=new Set;return E&&Object.keys(d.unitless||{}).forEach(function(t){e.add((0,l.ks)(t,E.prefix)),e.add((0,l.ks)(t,w(m,E.prefix)))}),_($,e)},[$,m,null==E?void 0:E.prefix]),j=I($),B=j.max,L=j.min,F={theme:p,token:S,hashId:b,nonce:function(){return R.nonce},clientOnly:d.clientOnly,layer:y,order:d.order||-999};return(0,l.xy)((0,a.Z)((0,a.Z)({},F),{},{clientOnly:!1,path:["Shared",k]}),function(){return"function"==typeof h?h(S):[]}),[(0,l.xy)((0,a.Z)((0,a.Z)({},F),{},{path:[g,e,P]}),function(){if(!1===d.injectStyle)return[];var r=O(S),i=r.token,a=r.flush,u=T(m,v,s),c=".".concat(e),h=x(m,v,u,{deprecatedTokens:d.deprecatedTokens});E&&u&&"object"===(0,n.Z)(u)&&Object.keys(u).forEach(function(e){u[e]="var(".concat((0,l.ks)(e,w(m,E.prefix)),")")});var p=C(i,{componentCls:c,prefixCls:e,iconCls:".".concat(P),antCls:".".concat(k),calc:N,max:B,min:L},E?u:h),g=o(p,{hashId:b,prefixCls:e,rootPrefixCls:k,iconPrefixCls:P});a(m,h);var y="function"==typeof f?f(p,e,t,d.resetFont):null;return[!1===d.resetStyle?null:y,g]}),b]}}return{genStyleHooks:function(e,t,r,n){var s=Array.isArray(e)?e[0]:e;function l(e){return"".concat(String(s)).concat(e.slice(0,1).toUpperCase()).concat(e.slice(1))}var u=(null==n?void 0:n.unitless)||{},c="function"==typeof d?d(e):{},h=(0,a.Z)((0,a.Z)({},c),{},(0,o.Z)({},l("zIndexPopup"),!0));Object.keys(u).forEach(function(e){h[l(e)]=u[e]});var f=(0,a.Z)((0,a.Z)({},n),{},{unitless:h,prefixToken:l}),g=m(e,t,r,f),y=p(s,r,f);return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,r=g(e,t),n=(0,i.Z)(r,2)[1],o=y(t),a=(0,i.Z)(o,2);return[a[0],n,a[1]]}},genSubStyleComponent:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=m(e,t,r,(0,a.Z)({resetStyle:!1,order:-998},n));return function(e){var t=e.prefixCls,r=e.rootCls,n=void 0===r?t:r;return i(t,n),null}},genComponentStyleHook:m}}},99607:function(e,t,r){"use strict";r.d(t,{ks:()=>D,fp:()=>el,jG:()=>I,xy:()=>tl,CI:()=>tf,E4:()=>td,bf:()=>L});var n,i=r(50793),o=r(57987),a=r(81632),s=r(19741);let l=function(e){for(var t,r=0,n=0,i=e.length;i>=4;++n,i-=4)t=(65535&(t=255&e.charCodeAt(n)|(255&e.charCodeAt(++n))<<8|(255&e.charCodeAt(++n))<<16|(255&e.charCodeAt(++n))<<24))*0x5bd1e995+((t>>>16)*59797<<16),t^=t>>>24,r=(65535&t)*0x5bd1e995+((t>>>16)*59797<<16)^(65535&r)*0x5bd1e995+((r>>>16)*59797<<16);switch(i){case 3:r^=(255&e.charCodeAt(n+2))<<16;case 2:r^=(255&e.charCodeAt(n+1))<<8;case 1:r^=255&e.charCodeAt(n),r=(65535&r)*0x5bd1e995+((r>>>16)*59797<<16)}return r^=r>>>13,(((r=(65535&r)*0x5bd1e995+((r>>>16)*59797<<16))^r>>>15)>>>0).toString(36)};var u=r(96345),c=r(44194),h=r.t(c,2);r(20638),r(43942);var f=r(71123),d=r(83739),p="%";function m(e){return e.join(p)}let g=function(){function e(t){(0,f.Z)(this,e),(0,i.Z)(this,"instanceId",void 0),(0,i.Z)(this,"cache",new Map),this.instanceId=t}return(0,d.Z)(e,[{key:"get",value:function(e){return this.opGet(m(e))}},{key:"opGet",value:function(e){return this.cache.get(e)||null}},{key:"update",value:function(e,t){return this.opUpdate(m(e),t)}},{key:"opUpdate",value:function(e,t){var r=t(this.cache.get(e));null===r?this.cache.delete(e):this.cache.set(e,r)}}]),e}();var y="data-token-hash",v="data-css-hash",b="__cssinjs_instance__";function _(){var e=Math.random().toString(12).slice(2);if("undefined"!=typeof document&&document.head&&document.body){var t=document.body.querySelectorAll("style[".concat(v,"]"))||[],r=document.head.firstChild;Array.from(t).forEach(function(t){t[b]=t[b]||e,t[b]===e&&document.head.insertBefore(t,r)});var n={};Array.from(document.querySelectorAll("style[".concat(v,"]"))).forEach(function(t){var r,i=t.getAttribute(v);n[i]?t[b]===e&&(null==(r=t.parentNode)||r.removeChild(t)):n[i]=!0})}return new g(e)}let w=c.createContext({hashPriority:"low",cache:_(),defaultCache:!0});var x=r(52655),S=r(33229);function E(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}var C=function(){function e(){(0,f.Z)(this,e),(0,i.Z)(this,"cache",void 0),(0,i.Z)(this,"keys",void 0),(0,i.Z)(this,"cacheCallTimes",void 0),this.cache=new Map,this.keys=[],this.cacheCallTimes=0}return(0,d.Z)(e,[{key:"size",value:function(){return this.keys.length}},{key:"internalGet",value:function(e){var t,r,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i={map:this.cache};return e.forEach(function(e){if(i){var t;i=null==(t=i)||null==(t=t.map)?void 0:t.get(e)}else i=void 0}),null!=(t=i)&&t.value&&n&&(i.value[1]=this.cacheCallTimes++),null==(r=i)?void 0:r.value}},{key:"get",value:function(e){var t;return null==(t=this.internalGet(e,!0))?void 0:t[0]}},{key:"has",value:function(e){return!!this.internalGet(e)}},{key:"set",value:function(t,r){var n=this;if(!this.has(t)){if(this.size()+1>e.MAX_CACHE_SIZE+e.MAX_CACHE_OFFSET){var i=this.keys.reduce(function(e,t){var r=(0,o.Z)(e,2)[1];return n.internalGet(t)[1]<r?[t,n.internalGet(t)[1]]:e},[this.keys[0],this.cacheCallTimes]),a=(0,o.Z)(i,1)[0];this.delete(a)}this.keys.push(t)}var s=this.cache;t.forEach(function(e,i){if(i===t.length-1)s.set(e,{value:[r,n.cacheCallTimes++]});else{var o=s.get(e);o?o.map||(o.map=new Map):s.set(e,{map:new Map}),s=s.get(e).map}})}},{key:"deleteByPath",value:function(e,t){var r,n=e.get(t[0]);if(1===t.length)return n.map?e.set(t[0],{map:n.map}):e.delete(t[0]),null==(r=n.value)?void 0:r[0];var i=this.deleteByPath(n.map,t.slice(1));return n.map&&0!==n.map.size||n.value||e.delete(t[0]),i}},{key:"delete",value:function(e){if(this.has(e))return this.keys=this.keys.filter(function(t){return!E(t,e)}),this.deleteByPath(this.cache,e)}}]),e}();(0,i.Z)(C,"MAX_CACHE_SIZE",20),(0,i.Z)(C,"MAX_CACHE_OFFSET",5);var A=r(28740),k=0,O=function(){function e(t){(0,f.Z)(this,e),(0,i.Z)(this,"derivatives",void 0),(0,i.Z)(this,"id",void 0),this.derivatives=Array.isArray(t)?t:[t],this.id=k,0===t.length&&(0,A.Kp)(t.length>0,"[Ant Design CSS-in-JS] Theme should have at least one derivative function."),k+=1}return(0,d.Z)(e,[{key:"getDerivativeToken",value:function(e){return this.derivatives.reduce(function(t,r){return r(e,t)},void 0)}}]),e}(),T=new C;function I(e){var t=Array.isArray(e)?e:[e];return T.has(t)||T.set(t,new O(t)),T.get(t)}var P=new WeakMap,R={};function M(e,t){for(var r=P,n=0;n<t.length;n+=1){var i=t[n];r.has(i)||r.set(i,new WeakMap),r=r.get(i)}return r.has(R)||r.set(R,e()),r.get(R)}var $=new WeakMap;function N(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=$.get(e)||"";return r||(Object.keys(e).forEach(function(n){var i=e[n];r+=n,i instanceof O?r+=i.id:i&&"object"===(0,x.Z)(i)?r+=N(i,t):r+=i}),t&&(r=l(r)),$.set(e,r)),r}function j(e,t){return l("".concat(t,"_").concat(N(e,!0)))}"random-".concat(Date.now(),"-").concat(Math.random()).replace(/\./g,"");var B=(0,S.Z)();function L(e){return"number"==typeof e?"".concat(e,"px"):e}function F(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(o)return e;var a=(0,s.Z)((0,s.Z)({},n),{},(0,i.Z)((0,i.Z)({},y,t),v,r)),l=Object.keys(a).map(function(e){var t=a[e];return t?"".concat(e,'="').concat(t,'"'):null}).filter(function(e){return e}).join(" ");return"<style ".concat(l,">").concat(e,"</style>")}var D=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return"--".concat(t?"".concat(t,"-"):"").concat(e).replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z0-9]+)/g,"$1-$2").replace(/([a-z])([A-Z0-9])/g,"$1-$2").toLowerCase()},z=function(e,t,r){return Object.keys(e).length?".".concat(t).concat(null!=r&&r.scope?".".concat(r.scope):"","{").concat(Object.entries(e).map(function(e){var t=(0,o.Z)(e,2),r=t[0],n=t[1];return"".concat(r,":").concat(n,";")}).join(""),"}"):""},U=function(e,t,r){var n={},i={};return Object.entries(e).forEach(function(e){var t=(0,o.Z)(e,2),a=t[0],s=t[1];if(null!=r&&null!=(l=r.preserve)&&l[a])i[a]=s;else if(("string"==typeof s||"number"==typeof s)&&!(null!=r&&null!=(u=r.ignore)&&u[a])){var l,u,c,h=D(a,null==r?void 0:r.prefix);n[h]="number"!=typeof s||null!=r&&null!=(c=r.unitless)&&c[a]?String(s):"".concat(s,"px"),i[a]="var(".concat(h,")")}}),[i,z(n,t,{scope:null==r?void 0:r.scope})]},Z=r(16713),H=(0,s.Z)({},h).useInsertionEffect,G=function(e,t,r){c.useMemo(e,r),(0,Z.Z)(function(){return t(!0)},r)};let W=H?function(e,t,r){return H(function(){return e(),t()},r)}:G;var q=(0,s.Z)({},h).useInsertionEffect,V=function(e){var t=[],r=!1;function n(e){r||t.push(e)}return c.useEffect(function(){return r=!1,function(){r=!0,t.length&&t.forEach(function(e){return e()})}},e),n},X=function(){return function(e){e()}};let Y=void 0!==q?V:X,K=function(){return!1};function J(e,t,r,n,i){var s=c.useContext(w).cache,l=m([e].concat((0,a.Z)(t))),u=Y([l]);K();var h=function(e){s.opUpdate(l,function(t){var n=t||[void 0,void 0],i=(0,o.Z)(n,2),a=i[0],s=[void 0===a?0:a,i[1]||r()];return e?e(s):s})};c.useMemo(function(){h()},[l]);var f=s.opGet(l)[1];return W(function(){null==i||i(f)},function(e){return h(function(t){var r=(0,o.Z)(t,2),n=r[0],a=r[1];return e&&0===n&&(null==i||i(f)),[n+1,a]}),function(){s.opUpdate(l,function(t){var r=t||[],i=(0,o.Z)(r,2),a=i[0],c=void 0===a?0:a,h=i[1];return 0==c-1?(u(function(){(e||!s.opGet(l))&&(null==n||n(h,!1))}),null):[c-1,h]})}},[l]),f}var Q={},ee="css",et=new Map;function er(e){et.set(e,(et.get(e)||0)+1)}function en(e,t){"undefined"!=typeof document&&document.querySelectorAll("style[".concat(y,'="').concat(e,'"]')).forEach(function(e){if(e[b]===t){var r;null==(r=e.parentNode)||r.removeChild(e)}})}var ei=0;function eo(e,t){et.set(e,(et.get(e)||0)-1);var r=Array.from(et.keys()),n=r.filter(function(e){return 0>=(et.get(e)||0)});r.length-n.length>ei&&n.forEach(function(e){en(e,t),et.delete(e)})}var ea=function(e,t,r,n){var i=r.getDerivativeToken(e),o=(0,s.Z)((0,s.Z)({},i),t);return n&&(o=n(o)),o},es="token";function el(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=(0,c.useContext)(w),i=n.cache.instanceId,h=n.container,f=r.salt,d=void 0===f?"":f,p=r.override,m=void 0===p?Q:p,g=r.formatToken,_=r.getComputedToken,x=r.cssVar,S=M(function(){return Object.assign.apply(Object,[{}].concat((0,a.Z)(t)))},t),E=N(S),C=N(m),A=x?N(x):"";return J(es,[d,e.id,E,C,A],function(){var t,r=_?_(S,m,e):ea(S,m,e,g),n=(0,s.Z)({},r),i="";if(x){var a=U(r,x.key,{prefix:x.prefix,ignore:x.ignore,unitless:x.unitless,preserve:x.preserve}),u=(0,o.Z)(a,2);r=u[0],i=u[1]}var c=j(r,d);r._tokenKey=c,n._tokenKey=j(n,d);var h=null!=(t=null==x?void 0:x.key)?t:c;r._themeKey=h,er(h);var f="".concat(ee,"-").concat(l(c));return r._hashId=f,[r,f,n,i,(null==x?void 0:x.key)||""]},function(e){eo(e[0]._themeKey,i)},function(e){var t=(0,o.Z)(e,4),r=t[0],n=t[3];if(x&&n){var a=(0,u.hq)(n,l("css-variables-".concat(r._themeKey)),{mark:v,prepend:"queue",attachTo:h,priority:-999});a[b]=i,a.setAttribute(y,r._themeKey)}})}var eu=function(e,t,r){var n=(0,o.Z)(e,5),i=n[2],a=n[3],s=n[4],l=(r||{}).plain;if(!a)return null;var u=i._tokenKey,c=-999,h=F(a,s,u,{"data-rc-order":"prependQueue","data-rc-priority":"".concat(c)},l);return[c,u,h]},ec=r(25833);let eh={animationIterationCount:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};var ef="comm",ed="rule",ep="decl",em="@import",eg="@keyframes",ey="@layer",ev=Math.abs,eb=String.fromCharCode;function e_(e){return e.trim()}function ew(e,t,r){return e.replace(t,r)}function ex(e,t,r){return e.indexOf(t,r)}function eS(e,t){return 0|e.charCodeAt(t)}function eE(e,t,r){return e.slice(t,r)}function eC(e){return e.length}function eA(e){return e.length}function ek(e,t){return t.push(e),e}function eO(e,t){for(var r="",n=0;n<e.length;n++)r+=t(e[n],n,e,t)||"";return r}function eT(e,t,r,n){switch(e.type){case ey:if(e.children.length)break;case em:case ep:return e.return=e.return||e.value;case ef:return"";case eg:return e.return=e.value+"{"+eO(e.children,n)+"}";case ed:if(!eC(e.value=e.props.join(",")))return""}return eC(r=eO(e.children,n))?e.return=e.value+"{"+r+"}":""}var eI=1,eP=1,eR=0,eM=0,e$=0,eN="";function ej(e,t,r,n,i,o,a,s){return{value:e,root:t,parent:r,type:n,props:i,children:o,line:eI,column:eP,length:a,return:"",siblings:s}}function eB(){return e$}function eL(){return e$=eM>0?eS(eN,--eM):0,eP--,10===e$&&(eP=1,eI--),e$}function eF(){return e$=eM<eR?eS(eN,eM++):0,eP++,10===e$&&(eP=1,eI++),e$}function eD(){return eS(eN,eM)}function ez(){return eM}function eU(e,t){return eE(eN,e,t)}function eZ(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function eH(e){return eI=eP=1,eR=eC(eN=e),eM=0,[]}function eG(e){return eN="",e}function eW(e){return e_(eU(eM-1,eX(91===e?e+2:40===e?e+1:e)))}function eq(e){for(;e$=eD();)if(e$<33)eF();else break;return eZ(e)>2||eZ(e$)>3?"":" "}function eV(e,t){for(;--t&&eF()&&!(e$<48)&&!(e$>102)&&(!(e$>57)||!(e$<65))&&(!(e$>70)||!(e$<97)););return eU(e,ez()+(t<6&&32==eD()&&32==eF()))}function eX(e){for(;eF();)switch(e$){case e:return eM;case 34:case 39:34!==e&&39!==e&&eX(e$);break;case 40:41===e&&eX(e);break;case 92:eF()}return eM}function eY(e,t){for(;eF();)if(e+e$===57)break;else if(e+e$===84&&47===eD())break;return"/*"+eU(t,eM-1)+"*"+eb(47===e?e:eF())}function eK(e){for(;!eZ(eD());)eF();return eU(e,eM)}function eJ(e){return eG(eQ("",null,null,null,[""],e=eH(e),0,[0],e))}function eQ(e,t,r,n,i,o,a,s,l){for(var u=0,c=0,h=a,f=0,d=0,p=0,m=1,g=1,y=1,v=0,b="",_=i,w=o,x=n,S=b;g;)switch(p=v,v=eF()){case 40:if(108!=p&&58==eS(S,h-1)){-1!=ex(S+=ew(eW(v),"&","&\f"),"&\f",ev(u?s[u-1]:0))&&(y=-1);break}case 34:case 39:case 91:S+=eW(v);break;case 9:case 10:case 13:case 32:S+=eq(p);break;case 92:S+=eV(ez()-1,7);continue;case 47:switch(eD()){case 42:case 47:ek(e1(eY(eF(),ez()),t,r,l),l),(5==eZ(p||1)||5==eZ(eD()||1))&&eC(S)&&" "!==eE(S,-1,void 0)&&(S+=" ");break;default:S+="/"}break;case 123*m:s[u++]=eC(S)*y;case 125*m:case 59:case 0:switch(v){case 0:case 125:g=0;case 59+c:-1==y&&(S=ew(S,/\f/g,"")),d>0&&(eC(S)-h||0===m&&47===p)&&ek(d>32?e2(S+";",n,r,h-1,l):e2(ew(S," ","")+";",n,r,h-2,l),l);break;case 59:S+=";";default:if(ek(x=e0(S,t,r,u,c,i,s,b,_=[],w=[],h,o),o),123===v)if(0===c)eQ(S,t,x,x,_,o,h,s,w);else switch(99===f&&110===eS(S,3)?100:f){case 100:case 108:case 109:case 115:eQ(e,x,x,n&&ek(e0(e,x,x,0,0,i,s,b,i,_=[],h,w),w),i,w,h,s,n?_:w);break;default:eQ(S,x,x,x,[""],w,0,s,w)}}u=c=d=0,m=y=1,b=S="",h=a;break;case 58:h=1+eC(S),d=p;default:if(m<1){if(123==v)--m;else if(125==v&&0==m++&&125==eL())continue}switch(S+=eb(v),v*m){case 38:y=c>0?1:(S+="\f",-1);break;case 44:s[u++]=(eC(S)-1)*y,y=1;break;case 64:45===eD()&&(S+=eW(eF())),f=eD(),c=h=eC(b=S+=eK(ez())),v++;break;case 45:45===p&&2==eC(S)&&(m=0)}}return o}function e0(e,t,r,n,i,o,a,s,l,u,c,h){for(var f=i-1,d=0===i?o:[""],p=eA(d),m=0,g=0,y=0;m<n;++m)for(var v=0,b=eE(e,f+1,f=ev(g=a[m])),_=e;v<p;++v)(_=e_(g>0?d[v]+" "+b:ew(b,/&\f/g,d[v])))&&(l[y++]=_);return ej(e,t,r,0===i?ed:s,l,u,c,h)}function e1(e,t,r,n){return ej(e,t,r,ef,eb(eB()),eE(e,2,-2),0,n)}function e2(e,t,r,n,i){return ej(e,t,r,ep,eE(e,0,n),eE(e,n+1,-1),n,i)}var e3="data-ant-cssinjs-cache-path",e5="_FILE_STYLE__",e4=!0;function e6(){if(!n&&(n={},(0,S.Z)())){var e,t=document.createElement("div");t.className=e3,t.style.position="fixed",t.style.visibility="hidden",t.style.top="-9999px",document.body.appendChild(t);var r=getComputedStyle(t).content||"";(r=r.replace(/^"/,"").replace(/"$/,"")).split(";").forEach(function(e){var t=e.split(":"),r=(0,o.Z)(t,2),i=r[0],a=r[1];n[i]=a});var i=document.querySelector("style[".concat(e3,"]"));i&&(e4=!1,null==(e=i.parentNode)||e.removeChild(i)),document.body.removeChild(t)}}function e8(e){return e6(),!!n[e]}function e9(e){var t=n[e],r=null;if(t&&(0,S.Z)())if(e4)r=e5;else{var i=document.querySelector("style[".concat(v,'="').concat(n[e],'"]'));i?r=i.innerHTML:delete n[e]}return[r,t]}var e7="_skip_check_",te="_multi_value_";function tt(e){return eO(eJ(e),eT).replace(/\{%%%\:[^;];}/g,";")}function tr(e){return"object"===(0,x.Z)(e)&&e&&(e7 in e||te in e)}function tn(e,t,r){if(!t)return e;var n=".".concat(t),i="low"===r?":where(".concat(n,")"):n;return e.split(",").map(function(e){var t,r=e.trim().split(/\s+/),n=r[0]||"",o=(null==(t=n.match(/^\w+/))?void 0:t[0])||"";return[n="".concat(o).concat(i).concat(n.slice(o.length))].concat((0,a.Z)(r.slice(1))).join(" ")}).join(",")}var ti=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{root:!0,parentSelectors:[]},i=n.root,l=n.injectHash,u=n.parentSelectors,c=r.hashId,h=r.layer,f=(r.path,r.hashPriority),d=r.transformers,p=void 0===d?[]:d,m=(r.linters,""),g={};function y(t){var n=t.getName(c);if(!g[n]){var i=e(t.style,r,{root:!1,parentSelectors:u}),a=(0,o.Z)(i,1)[0];g[n]="@keyframes ".concat(t.getName(c)).concat(a)}}function v(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e.forEach(function(e){Array.isArray(e)?v(e,t):e&&t.push(e)}),t}return v(Array.isArray(t)?t:[t]).forEach(function(t){var n="string"!=typeof t||i?t:{};if("string"==typeof n)m+="".concat(n,"\n");else if(n._keyframe)y(n);else{var h=p.reduce(function(e,t){var r;return(null==t||null==(r=t.visit)?void 0:r.call(t,e))||e},n);Object.keys(h).forEach(function(t){var n=h[t];if("object"!==(0,x.Z)(n)||!n||"animationName"===t&&n._keyframe||tr(n)){function d(e,t){var r=e.replace(/[A-Z]/g,function(e){return"-".concat(e.toLowerCase())}),n=t;eh[e]||"number"!=typeof n||0===n||(n="".concat(n,"px")),"animationName"===e&&null!=t&&t._keyframe&&(y(t),n=t.getName(c)),m+="".concat(r,":").concat(n,";")}var p,v=null!=(p=null==n?void 0:n.value)?p:n;"object"===(0,x.Z)(n)&&null!=n&&n[te]&&Array.isArray(v)?v.forEach(function(e){d(t,e)}):d(t,v)}else{var b=!1,_=t.trim(),w=!1;(i||l)&&c?_.startsWith("@")?b=!0:_="&"===_?tn("",c,f):tn(t,c,f):i&&!c&&("&"===_||""===_)&&(_="",w=!0);var S=e(n,r,{root:w,injectHash:b,parentSelectors:[].concat((0,a.Z)(u),[_])}),E=(0,o.Z)(S,2),C=E[0],A=E[1];g=(0,s.Z)((0,s.Z)({},g),A),m+="".concat(_).concat(C)}})}}),i?h&&(m="@layer ".concat(h.name," {").concat(m,"}"),h.dependencies&&(g["@layer ".concat(h.name)]=h.dependencies.map(function(e){return"@layer ".concat(e,", ").concat(h.name,";")}).join("\n"))):m="{".concat(m,"}"),[m,g]};function to(e,t){return l("".concat(e.join("%")).concat(t))}function ta(){return null}var ts="style";function tl(e,t){var r=e.token,n=e.path,l=e.hashId,h=e.layer,f=e.nonce,d=e.clientOnly,p=e.order,m=void 0===p?0:p,g=c.useContext(w),_=g.autoClear,x=(g.mock,g.defaultCache),S=g.hashPriority,E=g.container,C=g.ssrInline,A=g.transformers,k=g.linters,O=g.cache,T=g.layer,I=r._tokenKey,P=[I];T&&P.push("layer"),P.push.apply(P,(0,a.Z)(n));var R=B,M=J(ts,P,function(){var e=P.join("|");if(e8(e)){var r=e9(e),i=(0,o.Z)(r,2),a=i[0],s=i[1];if(a)return[a,I,s,{},d,m]}var u=ti(t(),{hashId:l,hashPriority:S,layer:T?h:void 0,path:n.join("-"),transformers:A,linters:k}),c=(0,o.Z)(u,2),f=c[0],p=c[1],g=tt(f),y=to(P,g);return[g,I,y,p,d,m]},function(e,t){var r=(0,o.Z)(e,3)[2];(t||_)&&B&&(0,u.jL)(r,{mark:v})},function(e){var t=(0,o.Z)(e,4),r=t[0],n=(t[1],t[2]),i=t[3];if(R&&r!==e5){var a={mark:v,prepend:!T&&"queue",attachTo:E,priority:m},l="function"==typeof f?f():f;l&&(a.csp={nonce:l});var c=[],h=[];Object.keys(i).forEach(function(e){e.startsWith("@layer")?c.push(e):h.push(e)}),c.forEach(function(e){(0,u.hq)(tt(i[e]),"_layer-".concat(e),(0,s.Z)((0,s.Z)({},a),{},{prepend:!0}))});var d=(0,u.hq)(r,n,a);d[b]=O.instanceId,d.setAttribute(y,I),h.forEach(function(e){(0,u.hq)(tt(i[e]),"_effect-".concat(e),a)})}}),$=(0,o.Z)(M,3),N=$[0],j=$[1],L=$[2];return function(e){var t;return t=C&&!R&&x?c.createElement("style",(0,ec.Z)({},(0,i.Z)((0,i.Z)({},y,j),v,L),{dangerouslySetInnerHTML:{__html:N}})):c.createElement(ta,null),c.createElement(c.Fragment,null,t,e)}}var tu=function(e,t,r){var n=(0,o.Z)(e,6),i=n[0],a=n[1],s=n[2],l=n[3],u=n[4],c=n[5],h=(r||{}).plain;if(u)return null;var f=i,d={"data-rc-order":"prependQueue","data-rc-priority":"".concat(c)};return f=F(i,a,s,d,h),l&&Object.keys(l).forEach(function(e){if(!t[e]){t[e]=!0;var r=F(tt(l[e]),a,"_effect-".concat(e),d,h);e.startsWith("@layer")?f=r+f:f+=r}}),[c,s,f]},tc="cssVar",th=function(e,t,r){var n=(0,o.Z)(e,4),i=n[1],a=n[2],s=n[3],l=(r||{}).plain;if(!i)return null;var u=-999,c=F(i,s,a,{"data-rc-order":"prependQueue","data-rc-priority":"".concat(u)},l);return[u,a,c]};let tf=function(e,t){var r=e.key,n=e.prefix,i=e.unitless,s=e.ignore,l=e.token,h=e.scope,f=void 0===h?"":h,d=(0,c.useContext)(w),p=d.cache.instanceId,m=d.container,g=l._tokenKey,_=[].concat((0,a.Z)(e.path),[r,f,g]);return J(tc,_,function(){var e=U(t(),r,{prefix:n,unitless:i,ignore:s,scope:f}),a=(0,o.Z)(e,2),l=a[0],u=a[1],c=to(_,u);return[l,u,c,r]},function(e){var t=(0,o.Z)(e,3)[2];B&&(0,u.jL)(t,{mark:v})},function(e){var t=(0,o.Z)(e,3),n=t[1],i=t[2];if(n){var a=(0,u.hq)(n,i,{mark:v,prepend:"queue",attachTo:m,priority:-999});a[b]=p,a.setAttribute(y,r)}})};(0,i.Z)((0,i.Z)((0,i.Z)({},ts,tu),es,eu),tc,th);let td=function(){function e(t,r){(0,f.Z)(this,e),(0,i.Z)(this,"name",void 0),(0,i.Z)(this,"style",void 0),(0,i.Z)(this,"_keyframe",!0),this.name=t,this.style=r}return(0,d.Z)(e,[{key:"getName",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e?"".concat(e,"-").concat(this.name):this.name}}]),e}();function tp(e){return e.notSplit=!0,e}tp(["borderTop","borderBottom"]),tp(["borderTop"]),tp(["borderBottom"]),tp(["borderLeft","borderRight"]),tp(["borderLeft"]),tp(["borderRight"])},14532:function(e,t,r){"use strict";r.d(t,{Z:()=>j});var n=r(25833),i=r(57987),o=r(50793),a=r(52755),s=r(44194),l=r(41229),u=r.n(l),c=r(25537),h=r(22655),f=r(19741),d=r(52655),p=r(96345),m=r(5940),g=r(28740);function y(e){return e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}function v(e,t){(0,g.ZP)(e,"[@ant-design/icons] ".concat(t))}function b(e){return"object"===(0,d.Z)(e)&&"string"==typeof e.name&&"string"==typeof e.theme&&("object"===(0,d.Z)(e.icon)||"function"==typeof e.icon)}function _(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.keys(e).reduce(function(t,r){var n=e[r];return"class"===r?(t.className=n,delete t.class):(delete t[r],t[y(r)]=n),t},{})}function w(e,t,r){return r?s.createElement(e.tag,(0,f.Z)((0,f.Z)({key:t},_(e.attrs)),r),(e.children||[]).map(function(r,n){return w(r,"".concat(t,"-").concat(e.tag,"-").concat(n))})):s.createElement(e.tag,(0,f.Z)({key:t},_(e.attrs)),(e.children||[]).map(function(r,n){return w(r,"".concat(t,"-").concat(e.tag,"-").concat(n))}))}function x(e){return(0,c.R_)(e)[0]}function S(e){return e?Array.isArray(e)?e:[e]:[]}var E="\n.anticon {\n display: inline-flex;\n align-items: center;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.anticon > * {\n line-height: 1;\n}\n\n.anticon svg {\n display: inline-block;\n}\n\n.anticon::before {\n display: none;\n}\n\n.anticon .anticon-icon {\n display: block;\n}\n\n.anticon[tabindex] {\n cursor: pointer;\n}\n\n.anticon-spin::before,\n.anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n",C=function(e){var t=(0,s.useContext)(h.Z),r=t.csp,n=t.prefixCls,i=E;n&&(i=i.replace(/anticon/g,n)),(0,s.useEffect)(function(){var t=e.current,n=(0,m.A)(t);(0,p.hq)(i,"@ant-design-icons",{prepend:!0,csp:r,attachTo:n})},[])},A=["icon","className","onClick","style","primaryColor","secondaryColor"],k={primaryColor:"#333",secondaryColor:"#E6E6E6",calculated:!1};function O(e){var t=e.primaryColor,r=e.secondaryColor;k.primaryColor=t,k.secondaryColor=r||x(t),k.calculated=!!r}function T(){return(0,f.Z)({},k)}var I=function(e){var t=e.icon,r=e.className,n=e.onClick,i=e.style,o=e.primaryColor,l=e.secondaryColor,u=(0,a.Z)(e,A),c=s.useRef(),h=k;if(o&&(h={primaryColor:o,secondaryColor:l||x(o)}),C(c),v(b(t),"icon should be icon definiton, but got ".concat(t)),!b(t))return null;var d=t;return d&&"function"==typeof d.icon&&(d=(0,f.Z)((0,f.Z)({},d),{},{icon:d.icon(h.primaryColor,h.secondaryColor)})),w(d.icon,"svg-".concat(d.name),(0,f.Z)((0,f.Z)({className:r,onClick:n,style:i,"data-icon":d.name,width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true"},u),{},{ref:c}))};I.displayName="IconReact",I.getTwoToneColors=T,I.setTwoToneColors=O;let P=I;function R(e){var t=S(e),r=(0,i.Z)(t,2),n=r[0],o=r[1];return P.setTwoToneColors({primaryColor:n,secondaryColor:o})}function M(){var e=P.getTwoToneColors();return e.calculated?[e.primaryColor,e.secondaryColor]:e.primaryColor}var $=["className","icon","spin","rotate","tabIndex","onClick","twoToneColor"];R(c.iN.primary);var N=s.forwardRef(function(e,t){var r=e.className,l=e.icon,c=e.spin,f=e.rotate,d=e.tabIndex,p=e.onClick,m=e.twoToneColor,g=(0,a.Z)(e,$),y=s.useContext(h.Z),v=y.prefixCls,b=void 0===v?"anticon":v,_=y.rootClassName,w=u()(_,b,(0,o.Z)((0,o.Z)({},"".concat(b,"-").concat(l.name),!!l.name),"".concat(b,"-spin"),!!c||"loading"===l.name),r),x=d;void 0===x&&p&&(x=-1);var E=f?{msTransform:"rotate(".concat(f,"deg)"),transform:"rotate(".concat(f,"deg)")}:void 0,C=S(m),A=(0,i.Z)(C,2),k=A[0],O=A[1];return s.createElement("span",(0,n.Z)({role:"img","aria-label":l.name},g,{ref:t,tabIndex:x,onClick:p,className:w}),s.createElement(P,{icon:l,primaryColor:k,secondaryColor:O,style:E}))});N.displayName="AntdIcon",N.getTwoToneColor=M,N.setTwoToneColor=R;let j=N},22655:function(e,t,r){"use strict";r.d(t,{Z:()=>n});let n=(0,r(44194).createContext)({})},9004:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"border",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},11322:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M715.8 493.5L335 165.1c-14.2-12.2-35-1.2-35 18.5v656.8c0 19.7 20.8 30.7 35 18.5l380.8-328.4c10.9-9.4 10.9-27.6 0-37z"}}]},name:"caret-right",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},4007:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"}}]},name:"check-circle",theme:"filled"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},55655:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64c247.4 0 448 200.6 448 448S759.4 960 512 960 64 759.4 64 512 264.6 64 512 64zm127.98 274.82h-.04l-.08.06L512 466.75 384.14 338.88c-.04-.05-.06-.06-.08-.06a.12.12 0 00-.07 0c-.03 0-.05.01-.09.05l-45.02 45.02a.2.2 0 00-.05.09.12.12 0 000 .07v.02a.27.27 0 00.06.06L466.75 512 338.88 639.86c-.05.04-.06.06-.06.08a.12.12 0 000 .07c0 .03.01.05.05.09l45.02 45.02a.2.2 0 00.09.05.12.12 0 00.07 0c.02 0 .04-.01.08-.05L512 557.25l127.86 127.87c.04.04.06.05.08.05a.12.12 0 00.07 0c.03 0 .05-.01.09-.05l45.02-45.02a.2.2 0 00.05-.09.12.12 0 000-.07v-.02a.27.27 0 00-.05-.06L557.25 512l127.87-127.86c.04-.04.05-.06.05-.08a.12.12 0 000-.07c0-.03-.01-.05-.05-.09l-45.02-45.02a.2.2 0 00-.09-.05.12.12 0 00-.07 0z"}}]},name:"close-circle",theme:"filled"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},32110:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M799.86 166.31c.02 0 .04.02.08.06l57.69 57.7c.04.03.05.05.06.08a.12.12 0 010 .06c0 .03-.02.05-.06.09L569.93 512l287.7 287.7c.04.04.05.06.06.09a.12.12 0 010 .07c0 .02-.02.04-.06.08l-57.7 57.69c-.03.04-.05.05-.07.06a.12.12 0 01-.07 0c-.03 0-.05-.02-.09-.06L512 569.93l-287.7 287.7c-.04.04-.06.05-.09.06a.12.12 0 01-.07 0c-.02 0-.04-.02-.08-.06l-57.69-57.7c-.04-.03-.05-.05-.06-.07a.12.12 0 010-.07c0-.03.02-.05.06-.09L454.07 512l-287.7-287.7c-.04-.04-.05-.06-.06-.09a.12.12 0 010-.07c0-.02.02-.04.06-.08l57.7-57.69c.03-.04.05-.05.07-.06a.12.12 0 01.07 0c.03 0 .05.02.09.06L512 454.07l287.7-287.7c.04-.04.06-.05.09-.06a.12.12 0 01.07 0z"}}]},name:"close",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},50408:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M505.7 661a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"download",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},58111:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"}}]},name:"ellipsis",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},73654:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-32 232c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V296zm32 440a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"}}]},name:"exclamation-circle",theme:"filled"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},94878:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM770.87 199.13l-52.2-52.2a8.01 8.01 0 014.7-13.6l179.4-21c5.1-.6 9.5 3.7 8.9 8.9l-21 179.4c-.8 6.6-8.9 9.4-13.6 4.7l-52.4-52.4-256.2 256.2a8.03 8.03 0 01-11.3 0l-42.4-42.4a8.03 8.03 0 010-11.3l256.1-256.3z"}}]},name:"export",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},24452:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"}}]},name:"info-circle",theme:"filled"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},7379:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}},{tag:"path",attrs:{d:"M464 336a48 48 0 1096 0 48 48 0 10-96 0zm72 112h-48c-4.4 0-8 3.6-8 8v272c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V456c0-4.4-3.6-8-8-8z"}}]},name:"info-circle",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},16383:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"}}]},name:"loading",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},43876:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M744 62H280c-35.3 0-64 28.7-64 64v768c0 35.3 28.7 64 64 64h464c35.3 0 64-28.7 64-64V126c0-35.3-28.7-64-64-64zm-8 824H288V134h448v752zM472 784a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"mobile",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},96033:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z"}}]},name:"right",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},35725:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M931.4 498.9L94.9 79.5c-3.4-1.7-7.3-2.1-11-1.2a15.99 15.99 0 00-11.7 19.3l86.2 352.2c1.3 5.3 5.2 9.6 10.4 11.3l147.7 50.7-147.6 50.7c-5.2 1.8-9.1 6-10.3 11.3L72.2 926.5c-.9 3.7-.5 7.6 1.2 10.9 3.9 7.9 13.5 11.1 21.5 7.2l836.5-417c3.1-1.5 5.6-4.1 7.2-7.1 3.9-8 .7-17.6-7.2-21.6zM170.8 826.3l50.3-205.6 295.2-101.3c2.3-.8 4.2-2.6 5-5 1.4-4.2-.8-8.7-5-10.2L221.1 403 171 198.2l628 314.9-628.2 313.2z"}}]},name:"send",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},42968:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(25833),i=r(44194);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M924.8 625.7l-65.5-56c3.1-19 4.7-38.4 4.7-57.8s-1.6-38.8-4.7-57.8l65.5-56a32.03 32.03 0 009.3-35.2l-.9-2.6a443.74 443.74 0 00-79.7-137.9l-1.8-2.1a32.12 32.12 0 00-35.1-9.5l-81.3 28.9c-30-24.6-63.5-44-99.7-57.6l-15.7-85a32.05 32.05 0 00-25.8-25.7l-2.7-.5c-52.1-9.4-106.9-9.4-159 0l-2.7.5a32.05 32.05 0 00-25.8 25.7l-15.8 85.4a351.86 351.86 0 00-99 57.4l-81.9-29.1a32 32 0 00-35.1 9.5l-1.8 2.1a446.02 446.02 0 00-79.7 137.9l-.9 2.6c-4.5 12.5-.8 26.5 9.3 35.2l66.3 56.6c-3.1 18.8-4.6 38-4.6 57.1 0 19.2 1.5 38.4 4.6 57.1L99 625.5a32.03 32.03 0 00-9.3 35.2l.9 2.6c18.1 50.4 44.9 96.9 79.7 137.9l1.8 2.1a32.12 32.12 0 0035.1 9.5l81.9-29.1c29.8 24.5 63.1 43.9 99 57.4l15.8 85.4a32.05 32.05 0 0025.8 25.7l2.7.5a449.4 449.4 0 00159 0l2.7-.5a32.05 32.05 0 0025.8-25.7l15.7-85a350 350 0 0099.7-57.6l81.3 28.9a32 32 0 0035.1-9.5l1.8-2.1c34.8-41.1 61.6-87.5 79.7-137.9l.9-2.6c4.5-12.3.8-26.3-9.3-35zM788.3 465.9c2.5 15.1 3.8 30.6 3.8 46.1s-1.3 31-3.8 46.1l-6.6 40.1 74.7 63.9a370.03 370.03 0 01-42.6 73.6L721 702.8l-31.4 25.8c-23.9 19.6-50.5 35-79.3 45.8l-38.1 14.3-17.9 97a377.5 377.5 0 01-85 0l-17.9-97.2-37.8-14.5c-28.5-10.8-55-26.2-78.7-45.7l-31.4-25.9-93.4 33.2c-17-22.9-31.2-47.6-42.6-73.6l75.5-64.5-6.5-40c-2.4-14.9-3.7-30.3-3.7-45.5 0-15.3 1.2-30.6 3.7-45.5l6.5-40-75.5-64.5c11.3-26.1 25.6-50.7 42.6-73.6l93.4 33.2 31.4-25.9c23.7-19.5 50.2-34.9 78.7-45.7l37.9-14.3 17.9-97.2c28.1-3.2 56.8-3.2 85 0l17.9 97 38.1 14.3c28.7 10.8 55.4 26.2 79.3 45.8l31.4 25.8 92.8-32.9c17 22.9 31.2 47.6 42.6 73.6L781.8 426l6.5 39.9zM512 326c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm79.2 255.2A111.6 111.6 0 01512 614c-29.9 0-58-11.7-79.2-32.8A111.6 111.6 0 01400 502c0-29.9 11.7-58 32.8-79.2C454 401.6 482.1 390 512 390c29.9 0 58 11.6 79.2 32.8A111.6 111.6 0 01624 502c0 29.9-11.7 58-32.8 79.2z"}}]},name:"setting",theme:"outlined"};var a=r(14532),s=function(e,t){return i.createElement(a.Z,(0,n.Z)({},e,{ref:t,icon:o}))};let l=i.forwardRef(s)},93096:function(e,t,r){"use strict";r.d(t,{y:()=>_});var n,i=r(90534);r(73656);let o=(0,i.YR)("identity");function a(e){return`SUCCESS. Scopes: ${Array.isArray(e)?e.join(", "):e}.`}function s(e,t){let r="ERROR.";return(null==e?void 0:e.length)&&(r+=` Scopes: ${Array.isArray(e)?e.join(", "):e}.`),`${r} Error message: ${"string"==typeof t?t:t.message}.`}function l(e,t,r=o){let n=t?`${t.fullTitle} ${e}`:e;function i(e){r.info(`${n} =>`,e)}function a(e){r.warning(`${n} =>`,e)}function s(e){r.verbose(`${n} =>`,e)}function u(e){r.error(`${n} =>`,e)}return{title:e,fullTitle:n,info:i,warning:a,verbose:s,error:u}}function u(e,t=o){let r=l(e,void 0,t);return Object.assign(Object.assign({},r),{parent:t,getToken:l("=> getToken()",r,t)})}let c="CredentialUnavailableError";class h extends Error{constructor(e,t){super(e,t),this.name=c}}let f="AggregateAuthenticationError";class d extends Error{constructor(e,t){super(`${t}
3
3
  ${e.join("\n")}`),this.errors=e,this.name=f}}let p="4.5.0";!function(e){e.AzureChina="https://login.chinacloudapi.cn",e.AzureGermany="https://login.microsoftonline.de",e.AzureGovernment="https://login.microsoftonline.us",e.AzurePublicCloud="https://login.microsoftonline.com"}(n||(n={})),n.AzurePublicCloud;let m=(0,r(82679).U)({namespace:"Microsoft.AAD",packageName:"@azure/identity",packageVersion:p}),g=u("ChainedTokenCredential");class y{constructor(...e){this._sources=[],this._sources=e}async getToken(e,t={}){let{token:r}=await this.getTokenInternal(e,t);return r}async getTokenInternal(e,t={}){let r,n=null,i=[];return m.withSpan("ChainedTokenCredential.getToken",t,async t=>{for(let o=0;o<this._sources.length&&null===n;o++)try{n=await this._sources[o].getToken(e,t),r=this._sources[o]}catch(t){if("CredentialUnavailableError"===t.name||"AuthenticationRequiredError"===t.name)i.push(t);else throw g.getToken.info(s(e,t)),t}if(!n&&i.length>0){let t=new d(i,"ChainedTokenCredential authentication failed.");throw g.getToken.info(s(e,t)),t}if(g.getToken.info(`Result for ${r.constructor.name}: ${a(e)}`),null===n)throw new h("Failed to retrieve a valid token");return{token:n,successfulCredential:r}})}}let v=Error("DefaultAzureCredential is not supported in the browser. Use InteractiveBrowserCredential instead."),b=u("DefaultAzureCredential");class _ extends y{constructor(e){throw super(),b.info(s("",v)),v}getToken(){throw b.getToken.info(s("",v)),v}}},11260:function(e,t,r){"use strict";r.d(t,{r:()=>q});let n=new Set(["Deserialize","Serialize","Retry","Sign"]);class i{constructor(e){var t;this._policies=[],this._policies=null!=(t=null==e?void 0:e.slice(0))?t:[],this._orderedPolicies=void 0}addPolicy(e,t={}){if(t.phase&&t.afterPhase)throw Error("Policies inside a phase cannot specify afterPhase.");if(t.phase&&!n.has(t.phase))throw Error(`Invalid phase name: ${t.phase}`);if(t.afterPhase&&!n.has(t.afterPhase))throw Error(`Invalid afterPhase name: ${t.afterPhase}`);this._policies.push({policy:e,options:t}),this._orderedPolicies=void 0}removePolicy(e){let t=[];return this._policies=this._policies.filter(r=>(!e.name||r.policy.name!==e.name)&&(!e.phase||r.options.phase!==e.phase)||(t.push(r.policy),!1)),this._orderedPolicies=void 0,t}sendRequest(e,t){return this.getOrderedPolicies().reduceRight((e,t)=>r=>t.sendRequest(r,e),t=>e.sendRequest(t))(t)}getOrderedPolicies(){return this._orderedPolicies||(this._orderedPolicies=this.orderPolicies()),this._orderedPolicies}clone(){return new i(this._policies)}static create(){return new i}orderPolicies(){let e=[],t=new Map;function r(e){return{name:e,policies:new Set,hasRun:!1,hasAfterPolicies:!1}}let n=r("Serialize"),i=r("None"),o=r("Deserialize"),a=r("Retry"),s=r("Sign"),l=[n,i,o,a,s];function u(e){return"Retry"===e?a:"Serialize"===e?n:"Deserialize"===e?o:"Sign"===e?s:i}for(let e of this._policies){let r=e.policy,n=e.options,i=r.name;if(t.has(i))throw Error("Duplicate policy names not allowed in pipeline");let o={policy:r,dependsOn:new Set,dependants:new Set};n.afterPhase&&(o.afterPhase=u(n.afterPhase),o.afterPhase.hasAfterPolicies=!0),t.set(i,o),u(n.phase).policies.add(o)}for(let e of this._policies){let{policy:r,options:n}=e,i=r.name,o=t.get(i);if(!o)throw Error(`Missing node for policy ${i}`);if(n.afterPolicies)for(let e of n.afterPolicies){let r=t.get(e);r&&(o.dependsOn.add(r),r.dependants.add(o))}if(n.beforePolicies)for(let e of n.beforePolicies){let r=t.get(e);r&&(r.dependsOn.add(o),o.dependants.add(r))}}function c(r){for(let n of(r.hasRun=!0,r.policies))if((!n.afterPhase||n.afterPhase.hasRun&&!n.afterPhase.policies.size)&&0===n.dependsOn.size){for(let t of(e.push(n.policy),n.dependants))t.dependsOn.delete(n);t.delete(n.policy.name),r.policies.delete(n)}}function h(){for(let e of l){if(c(e),e.policies.size>0&&e!==i){i.hasRun||c(i);return}e.hasAfterPolicies&&c(i)}}let f=0;for(;t.size>0;){f++;let t=e.length;if(h(),e.length<=t&&f>1)throw Error("Cannot satisfy policy dependencies due to requirements cycle.")}return e}}function o(){return i.create()}var a,s,l,u,c,h=r(90534);let f=(0,h.YR)("core-rest-pipeline");class d extends Error{constructor(e){super(e),this.name="AbortError"}}function p(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function m(e){if(p(e)){let t="string"==typeof e.name,r="string"==typeof e.message;return t&&r}return!1}function g(){let e="";for(let t=0;t<32;t++){let r=Math.floor(16*Math.random());12===t?e+="4":16===t?e+=3&r|8:e+=r.toString(16),(7===t||11===t||15===t||19===t)&&(e+="-")}return e}let y="function"==typeof(null==(a=null==globalThis?void 0:globalThis.crypto)?void 0:a.randomUUID)?globalThis.crypto.randomUUID.bind(globalThis.crypto):g;function v(){return y()}"undefined"!=typeof window&&window.document,"object"==typeof self&&"function"==typeof(null==self?void 0:self.importScripts)&&((null==(s=self.constructor)?void 0:s.name)==="DedicatedWorkerGlobalScope"||(null==(l=self.constructor)?void 0:l.name)==="ServiceWorkerGlobalScope"||null==(u=self.constructor)||u.name),"undefined"!=typeof Deno&&void 0!==Deno.version&&Deno.version.deno,"undefined"!=typeof Bun&&Bun.version,void 0!==globalThis.process&&globalThis.process.version&&(null==(c=globalThis.process.versions)||c.node),"undefined"!=typeof navigator&&(null==navigator||navigator.product);let b="REDACTED",_=["x-ms-client-request-id","x-ms-return-client-request-id","x-ms-useragent","x-ms-correlation-request-id","x-ms-request-id","client-request-id","ms-cv","return-client-request-id","traceparent","Access-Control-Allow-Credentials","Access-Control-Allow-Headers","Access-Control-Allow-Methods","Access-Control-Allow-Origin","Access-Control-Expose-Headers","Access-Control-Max-Age","Access-Control-Request-Headers","Access-Control-Request-Method","Origin","Accept","Accept-Encoding","Cache-Control","Connection","Content-Length","Content-Type","Date","ETag","Expires","If-Match","If-Modified-Since","If-None-Match","If-Unmodified-Since","Last-Modified","Pragma","Request-Id","Retry-After","Server","Transfer-Encoding","User-Agent","WWW-Authenticate"],w=["api-version"];class x{constructor({additionalAllowedHeaderNames:e=[],additionalAllowedQueryParameters:t=[]}={}){e=_.concat(e),t=w.concat(t),this.allowedHeaderNames=new Set(e.map(e=>e.toLowerCase())),this.allowedQueryParameters=new Set(t.map(e=>e.toLowerCase()))}sanitize(e){let t=new Set;return JSON.stringify(e,(e,r)=>{if(r instanceof Error)return Object.assign(Object.assign({},r),{name:r.name,message:r.message});if("headers"===e)return this.sanitizeHeaders(r);if("url"===e)return this.sanitizeUrl(r);if("query"===e)return this.sanitizeQuery(r);if("body"!==e){if("response"===e)return;else if("operationSpec"===e)return;else if(Array.isArray(r)||p(r)){if(t.has(r))return"[Circular]";t.add(r)}return r}},2)}sanitizeUrl(e){if("string"!=typeof e||null===e||""===e)return e;let t=new URL(e);if(!t.search)return e;for(let[e]of t.searchParams)this.allowedQueryParameters.has(e.toLowerCase())||t.searchParams.set(e,b);return t.toString()}sanitizeHeaders(e){let t={};for(let r of Object.keys(e))this.allowedHeaderNames.has(r.toLowerCase())?t[r]=e[r]:t[r]=b;return t}sanitizeQuery(e){if("object"!=typeof e||null===e)return e;let t={};for(let r of Object.keys(e))this.allowedQueryParameters.has(r.toLowerCase())?t[r]=e[r]:t[r]=b;return t}}function S(){return"x-ms-useragent"}(function(){S()})(),Symbol("rawContent");let E="The operation was aborted.";function C(e,t,r){return new Promise((n,i)=>{let o,a,s=()=>i(new d((null==r?void 0:r.abortErrorMsg)?null==r?void 0:r.abortErrorMsg:E)),l=()=>{(null==r?void 0:r.abortSignal)&&a&&r.abortSignal.removeEventListener("abort",a)};if(a=()=>(o&&clearTimeout(o),l(),s()),(null==r?void 0:r.abortSignal)&&r.abortSignal.aborted)return s();o=setTimeout(()=>{l(),n(t)},e),(null==r?void 0:r.abortSignal)&&r.abortSignal.addEventListener("abort",a)})}function A(e){return e.toLowerCase()}function*k(e){for(let t of e.values())yield[t.name,t.value]}(0,h.YR)("core-rest-pipeline retryPolicy");class O{constructor(e){if(this._headersMap=new Map,e)for(let t of Object.keys(e))this.set(t,e[t])}set(e,t){this._headersMap.set(A(e),{name:e,value:String(t).trim()})}get(e){var t;return null==(t=this._headersMap.get(A(e)))?void 0:t.value}has(e){return this._headersMap.has(A(e))}delete(e){this._headersMap.delete(A(e))}toJSON(e={}){let t={};if(e.preserveCase)for(let e of this._headersMap.values())t[e.name]=e.value;else for(let[e,r]of this._headersMap)t[e]=r.value;return t}toString(){return JSON.stringify(this.toJSON({preserveCase:!0}))}[Symbol.iterator](){return k(this._headersMap)}}function T(e){return new O(e)}r(82679);let I={},P=new x;class R extends Error{constructor(e,t={}){super(e),this.name="RestError",this.code=t.code,this.statusCode=t.statusCode,Object.defineProperty(this,"request",{value:t.request,enumerable:!1}),Object.defineProperty(this,"response",{value:t.response,enumerable:!1}),Object.setPrototypeOf(this,R.prototype)}[I](){return`RestError: ${this.message}
4
4
  ${P.sanitize(Object.assign(Object.assign({},this),{request:this.request,response:this.response}))}`}}function M(e){return e instanceof R||m(e)&&"RestError"===e.name}R.REQUEST_SEND_ERROR="REQUEST_SEND_ERROR",R.PARSE_ERROR="PARSE_ERROR";class ${constructor(e){var t,r,n,i,o,a,s;this.url=e.url,this.body=e.body,this.headers=null!=(t=e.headers)?t:T(),this.method=null!=(r=e.method)?r:"GET",this.timeout=null!=(n=e.timeout)?n:0,this.multipartBody=e.multipartBody,this.formData=e.formData,this.disableKeepAlive=null!=(i=e.disableKeepAlive)&&i,this.proxySettings=e.proxySettings,this.streamResponseStatusCodes=e.streamResponseStatusCodes,this.withCredentials=null!=(o=e.withCredentials)&&o,this.abortSignal=e.abortSignal,this.tracingOptions=e.tracingOptions,this.onUploadProgress=e.onUploadProgress,this.onDownloadProgress=e.onDownloadProgress,this.requestId=e.requestId||v(),this.allowInsecureConnection=null!=(a=e.allowInsecureConnection)&&a,this.enableBrowserStreams=null!=(s=e.enableBrowserStreams)&&s}}function N(e){return new $(e)}let j={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:12e4};async function B(e,t,r){async function n(){if(Date.now()<r)try{return await e()}catch(e){return null}{let t=await e();if(null===t)throw Error("Failed to refresh access token.");return t}}let i=await n();for(;null===i;)await C(t),i=await n();return i}function L(e,t){let r,n=null,i=null,o=Object.assign(Object.assign({},j),t),a={get isRefreshing(){return null!==n},get shouldRefresh(){var s;if(a.isRefreshing)return!1;if((null==i?void 0:i.refreshAfterTimestamp)&&i.refreshAfterTimestamp<Date.now())return!0;return(null!=(s=null==i?void 0:i.expiresOnTimestamp)?s:0)-o.refreshWindowInMs<Date.now()},get mustRefresh(){return null===i||i.expiresOnTimestamp-o.forcedRefreshWindowInMs<Date.now()}};function l(t,s){var l;return a.isRefreshing||(n=B(()=>e.getToken(t,s),o.retryIntervalInMs,null!=(l=null==i?void 0:i.expiresOnTimestamp)?l:Date.now()).then(e=>(n=null,i=e,r=s.tenantId,i)).catch(e=>{throw n=null,i=null,r=void 0,e})),n}return async(e,t)=>{let n=!!t.claims,o=r!==t.tenantId;return(n&&(i=null),o||n||a.mustRefresh)?l(e,t):(a.shouldRefresh&&l(e,t),i)}}let F="bearerTokenAuthenticationPolicy";async function D(e,t){try{return[await t(e),void 0]}catch(e){if(M(e)&&e.response)return[e.response,e];throw e}}async function z(e){let{scopes:t,getAccessToken:r,request:n}=e,i={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions,enableCae:!0},o=await r(t,i);o&&e.request.headers.set("Authorization",`Bearer ${o.token}`)}function U(e){return 401===e.status&&e.headers.has("WWW-Authenticate")}async function Z(e,t){var r;let{scopes:n}=e,i=await e.getAccessToken(n,{enableCae:!0,claims:t});return!!i&&(e.request.headers.set("Authorization",`${null!=(r=i.tokenType)?r:"Bearer"} ${i.token}`),!0)}function H(e){var t,r,n;let{credential:i,scopes:o,challengeCallbacks:a}=e,s=e.logger||f,l={authorizeRequest:null!=(r=null==(t=null==a?void 0:a.authorizeRequest)?void 0:t.bind(a))?r:z,authorizeRequestOnChallenge:null==(n=null==a?void 0:a.authorizeRequestOnChallenge)?void 0:n.bind(a)},u=i?L(i):()=>Promise.resolve(null);return{name:F,async sendRequest(e,t){let r,n,i;if(!e.url.toLowerCase().startsWith("https://"))throw Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");if(await l.authorizeRequest({scopes:Array.isArray(o)?o:[o],request:e,getAccessToken:u,logger:s}),[r,n]=await D(e,t),U(r)){let a=W(r.headers.get("WWW-Authenticate"));if(a){let l;try{l=atob(a)}catch(e){return s.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${a}`),r}(i=await Z({scopes:Array.isArray(o)?o:[o],response:r,request:e,getAccessToken:u,logger:s},l))&&([r,n]=await D(e,t))}else if(l.authorizeRequestOnChallenge&&((i=await l.authorizeRequestOnChallenge({scopes:Array.isArray(o)?o:[o],request:e,response:r,getAccessToken:u,logger:s}))&&([r,n]=await D(e,t)),U(r))&&(a=W(r.headers.get("WWW-Authenticate")))){let l;try{l=atob(a)}catch(e){return s.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${a}`),r}(i=await Z({scopes:Array.isArray(o)?o:[o],response:r,request:e,getAccessToken:u,logger:s},l))&&([r,n]=await D(e,t))}}if(!n)return r;throw n}}}function G(e){let t,r=/(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g,n=/(\w+)="([^"]*)"/g,i=[];for(;null!==(t=r.exec(e));){let e,r=t[1],o=t[2],a={};for(;null!==(e=n.exec(o));)a[e[1]]=e[2];i.push({scheme:r,params:a})}return i}function W(e){var t;if(e)return null==(t=G(e).find(e=>"Bearer"===e.scheme&&e.params.claims&&"insufficient_claims"===e.params.error))?void 0:t.params.claims}function q(e,t,r){let{abortSignal:n,tracingOptions:i}=r||{},a=o();return a.addPolicy(H({credential:e,scopes:t})),async function(){var e;let t=null==(e=(await a.sendRequest({sendRequest:e=>Promise.resolve({request:e,status:200,headers:e.headers})},N({url:"https://example.com",abortSignal:n,tracingOptions:i}))).headers.get("authorization"))?void 0:e.split(" ")[1];if(!t)throw Error("Failed to get access token");return t}}},20117:function(e,t,r){"use strict";r.d(t,{T6:()=>d,VD:()=>p,WE:()=>u,Yt:()=>m,lC:()=>o,py:()=>l,rW:()=>i,s:()=>h,ve:()=>s,vq:()=>c});var n=r(33146);function i(e,t,r){return{r:255*(0,n.sh)(e,255),g:255*(0,n.sh)(t,255),b:255*(0,n.sh)(r,255)}}function o(e,t,r){e=(0,n.sh)(e,255);var i=Math.max(e,t=(0,n.sh)(t,255),r=(0,n.sh)(r,255)),o=Math.min(e,t,r),a=0,s=0,l=(i+o)/2;if(i===o)s=0,a=0;else{var u=i-o;switch(s=l>.5?u/(2-i-o):u/(i+o),i){case e:a=(t-r)/u+6*(t<r);break;case t:a=(r-e)/u+2;break;case r:a=(e-t)/u+4}a/=6}return{h:a,s:s,l:l}}function a(e,t,r){return(r<0&&(r+=1),r>1&&(r-=1),r<1/6)?e+6*r*(t-e):r<.5?t:r<2/3?e+(t-e)*(2/3-r)*6:e}function s(e,t,r){if(e=(0,n.sh)(e,360),t=(0,n.sh)(t,100),r=(0,n.sh)(r,100),0===t)o=r,s=r,i=r;else{var i,o,s,l=r<.5?r*(1+t):r+t-r*t,u=2*r-l;i=a(u,l,e+1/3),o=a(u,l,e),s=a(u,l,e-1/3)}return{r:255*i,g:255*o,b:255*s}}function l(e,t,r){e=(0,n.sh)(e,255);var i=Math.max(e,t=(0,n.sh)(t,255),r=(0,n.sh)(r,255)),o=Math.min(e,t,r),a=0,s=i,l=i-o,u=0===i?0:l/i;if(i===o)a=0;else{switch(i){case e:a=(t-r)/l+6*(t<r);break;case t:a=(r-e)/l+2;break;case r:a=(e-t)/l+4}a/=6}return{h:a,s:u,v:s}}function u(e,t,r){e=6*(0,n.sh)(e,360),t=(0,n.sh)(t,100),r=(0,n.sh)(r,100);var i=Math.floor(e),o=e-i,a=r*(1-t),s=r*(1-o*t),l=r*(1-(1-o)*t),u=i%6;return{r:255*[r,s,a,a,l,r][u],g:255*[l,r,r,s,a,a][u],b:255*[a,a,l,r,r,s][u]}}function c(e,t,r,i){var o=[(0,n.FZ)(Math.round(e).toString(16)),(0,n.FZ)(Math.round(t).toString(16)),(0,n.FZ)(Math.round(r).toString(16))];return i&&o[0].startsWith(o[0].charAt(1))&&o[1].startsWith(o[1].charAt(1))&&o[2].startsWith(o[2].charAt(1))?o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0):o.join("")}function h(e,t,r,i,o){var a=[(0,n.FZ)(Math.round(e).toString(16)),(0,n.FZ)(Math.round(t).toString(16)),(0,n.FZ)(Math.round(r).toString(16)),(0,n.FZ)(f(i))];return o&&a[0].startsWith(a[0].charAt(1))&&a[1].startsWith(a[1].charAt(1))&&a[2].startsWith(a[2].charAt(1))&&a[3].startsWith(a[3].charAt(1))?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0)+a[3].charAt(0):a.join("")}function f(e){return Math.round(255*parseFloat(e)).toString(16)}function d(e){return p(e)/255}function p(e){return parseInt(e,16)}function m(e){return{r:e>>16,g:(65280&e)>>8,b:255&e}}},53099:function(e,t,r){"use strict";r.d(t,{R:()=>n});var n={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",goldenrod:"#daa520",gold:"#ffd700",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavenderblush:"#fff0f5",lavender:"#e6e6fa",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}},76981:function(e,t,r){"use strict";r.d(t,{uA:()=>a});var n=r(20117),i=r(53099),o=r(33146);function a(e){var t={r:0,g:0,b:0},r=1,i=null,a=null,s=null,l=!1,u=!1;return"string"==typeof e&&(e=d(e)),"object"==typeof e&&(p(e.r)&&p(e.g)&&p(e.b)?(t=(0,n.rW)(e.r,e.g,e.b),l=!0,u="%"===String(e.r).substr(-1)?"prgb":"rgb"):p(e.h)&&p(e.s)&&p(e.v)?(i=(0,o.JX)(e.s),a=(0,o.JX)(e.v),t=(0,n.WE)(e.h,i,a),l=!0,u="hsv"):p(e.h)&&p(e.s)&&p(e.l)&&(i=(0,o.JX)(e.s),s=(0,o.JX)(e.l),t=(0,n.ve)(e.h,i,s),l=!0,u="hsl"),Object.prototype.hasOwnProperty.call(e,"a")&&(r=e.a)),r=(0,o.Yq)(r),{ok:l,format:e.format||u,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:r}}var s="[-\\+]?\\d+%?",l="[-\\+]?\\d*\\.\\d+%?",u="(?:".concat(l,")|(?:").concat(s,")"),c="[\\s|\\(]+(".concat(u,")[,|\\s]+(").concat(u,")[,|\\s]+(").concat(u,")\\s*\\)?"),h="[\\s|\\(]+(".concat(u,")[,|\\s]+(").concat(u,")[,|\\s]+(").concat(u,")[,|\\s]+(").concat(u,")\\s*\\)?"),f={CSS_UNIT:new RegExp(u),rgb:RegExp("rgb"+c),rgba:RegExp("rgba"+h),hsl:RegExp("hsl"+c),hsla:RegExp("hsla"+h),hsv:RegExp("hsv"+c),hsva:RegExp("hsva"+h),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/};function d(e){if(0===(e=e.trim().toLowerCase()).length)return!1;var t=!1;if(i.R[e])e=i.R[e],t=!0;else if("transparent"===e)return{r:0,g:0,b:0,a:0,format:"name"};var r=f.rgb.exec(e);return r?{r:r[1],g:r[2],b:r[3]}:(r=f.rgba.exec(e))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=f.hsl.exec(e))?{h:r[1],s:r[2],l:r[3]}:(r=f.hsla.exec(e))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=f.hsv.exec(e))?{h:r[1],s:r[2],v:r[3]}:(r=f.hsva.exec(e))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=f.hex8.exec(e))?{r:(0,n.VD)(r[1]),g:(0,n.VD)(r[2]),b:(0,n.VD)(r[3]),a:(0,n.T6)(r[4]),format:t?"name":"hex8"}:(r=f.hex6.exec(e))?{r:(0,n.VD)(r[1]),g:(0,n.VD)(r[2]),b:(0,n.VD)(r[3]),format:t?"name":"hex"}:(r=f.hex4.exec(e))?{r:(0,n.VD)(r[1]+r[1]),g:(0,n.VD)(r[2]+r[2]),b:(0,n.VD)(r[3]+r[3]),a:(0,n.T6)(r[4]+r[4]),format:t?"name":"hex8"}:!!(r=f.hex3.exec(e))&&{r:(0,n.VD)(r[1]+r[1]),g:(0,n.VD)(r[2]+r[2]),b:(0,n.VD)(r[3]+r[3]),format:t?"name":"hex"}}function p(e){return!!f.CSS_UNIT.exec(String(e))}},66671:function(e,t,r){"use strict";r.d(t,{C:()=>s});var n=r(20117),i=r(53099),o=r(76981),a=r(33146),s=function(){function e(t,r){if(void 0===t&&(t=""),void 0===r&&(r={}),t instanceof e)return t;"number"==typeof t&&(t=(0,n.Yt)(t)),this.originalInput=t;var i,a=(0,o.uA)(t);this.originalInput=t,this.r=a.r,this.g=a.g,this.b=a.b,this.a=a.a,this.roundA=Math.round(100*this.a)/100,this.format=null!=(i=r.format)?i:a.format,this.gradientType=r.gradientType,this.r<1&&(this.r=Math.round(this.r)),this.g<1&&(this.g=Math.round(this.g)),this.b<1&&(this.b=Math.round(this.b)),this.isValid=a.ok}return e.prototype.isDark=function(){return 128>this.getBrightness()},e.prototype.isLight=function(){return!this.isDark()},e.prototype.getBrightness=function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},e.prototype.getLuminance=function(){var e,t,r,n=this.toRgb(),i=n.r/255,o=n.g/255,a=n.b/255;return .2126*(e=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(t=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4))+.0722*(r=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4))},e.prototype.getAlpha=function(){return this.a},e.prototype.setAlpha=function(e){return this.a=(0,a.Yq)(e),this.roundA=Math.round(100*this.a)/100,this},e.prototype.isMonochrome=function(){return 0===this.toHsl().s},e.prototype.toHsv=function(){var e=(0,n.py)(this.r,this.g,this.b);return{h:360*e.h,s:e.s,v:e.v,a:this.a}},e.prototype.toHsvString=function(){var e=(0,n.py)(this.r,this.g,this.b),t=Math.round(360*e.h),r=Math.round(100*e.s),i=Math.round(100*e.v);return 1===this.a?"hsv(".concat(t,", ").concat(r,"%, ").concat(i,"%)"):"hsva(".concat(t,", ").concat(r,"%, ").concat(i,"%, ").concat(this.roundA,")")},e.prototype.toHsl=function(){var e=(0,n.lC)(this.r,this.g,this.b);return{h:360*e.h,s:e.s,l:e.l,a:this.a}},e.prototype.toHslString=function(){var e=(0,n.lC)(this.r,this.g,this.b),t=Math.round(360*e.h),r=Math.round(100*e.s),i=Math.round(100*e.l);return 1===this.a?"hsl(".concat(t,", ").concat(r,"%, ").concat(i,"%)"):"hsla(".concat(t,", ").concat(r,"%, ").concat(i,"%, ").concat(this.roundA,")")},e.prototype.toHex=function(e){return void 0===e&&(e=!1),(0,n.vq)(this.r,this.g,this.b,e)},e.prototype.toHexString=function(e){return void 0===e&&(e=!1),"#"+this.toHex(e)},e.prototype.toHex8=function(e){return void 0===e&&(e=!1),(0,n.s)(this.r,this.g,this.b,this.a,e)},e.prototype.toHex8String=function(e){return void 0===e&&(e=!1),"#"+this.toHex8(e)},e.prototype.toHexShortString=function(e){return void 0===e&&(e=!1),1===this.a?this.toHexString(e):this.toHex8String(e)},e.prototype.toRgb=function(){return{r:Math.round(this.r),g:Math.round(this.g),b:Math.round(this.b),a:this.a}},e.prototype.toRgbString=function(){var e=Math.round(this.r),t=Math.round(this.g),r=Math.round(this.b);return 1===this.a?"rgb(".concat(e,", ").concat(t,", ").concat(r,")"):"rgba(".concat(e,", ").concat(t,", ").concat(r,", ").concat(this.roundA,")")},e.prototype.toPercentageRgb=function(){var e=function(e){return"".concat(Math.round(100*(0,a.sh)(e,255)),"%")};return{r:e(this.r),g:e(this.g),b:e(this.b),a:this.a}},e.prototype.toPercentageRgbString=function(){var e=function(e){return Math.round(100*(0,a.sh)(e,255))};return 1===this.a?"rgb(".concat(e(this.r),"%, ").concat(e(this.g),"%, ").concat(e(this.b),"%)"):"rgba(".concat(e(this.r),"%, ").concat(e(this.g),"%, ").concat(e(this.b),"%, ").concat(this.roundA,")")},e.prototype.toName=function(){if(0===this.a)return"transparent";if(this.a<1)return!1;for(var e="#"+(0,n.vq)(this.r,this.g,this.b,!1),t=0,r=Object.entries(i.R);t<r.length;t++){var o=r[t],a=o[0];if(e===o[1])return a}return!1},e.prototype.toString=function(e){var t=!!e;e=null!=e?e:this.format;var r=!1,n=this.a<1&&this.a>=0;return!t&&n&&(e.startsWith("hex")||"name"===e)?"name"===e&&0===this.a?this.toName():this.toRgbString():("rgb"===e&&(r=this.toRgbString()),"prgb"===e&&(r=this.toPercentageRgbString()),("hex"===e||"hex6"===e)&&(r=this.toHexString()),"hex3"===e&&(r=this.toHexString(!0)),"hex4"===e&&(r=this.toHex8String(!0)),"hex8"===e&&(r=this.toHex8String()),"name"===e&&(r=this.toName()),"hsl"===e&&(r=this.toHslString()),"hsv"===e&&(r=this.toHsvString()),r||this.toHexString())},e.prototype.toNumber=function(){return(Math.round(this.r)<<16)+(Math.round(this.g)<<8)+Math.round(this.b)},e.prototype.clone=function(){return new e(this.toString())},e.prototype.lighten=function(t){void 0===t&&(t=10);var r=this.toHsl();return r.l+=t/100,r.l=(0,a.V2)(r.l),new e(r)},e.prototype.brighten=function(t){void 0===t&&(t=10);var r=this.toRgb();return r.r=Math.max(0,Math.min(255,r.r-Math.round(-(t/100*255)))),r.g=Math.max(0,Math.min(255,r.g-Math.round(-(t/100*255)))),r.b=Math.max(0,Math.min(255,r.b-Math.round(-(t/100*255)))),new e(r)},e.prototype.darken=function(t){void 0===t&&(t=10);var r=this.toHsl();return r.l-=t/100,r.l=(0,a.V2)(r.l),new e(r)},e.prototype.tint=function(e){return void 0===e&&(e=10),this.mix("white",e)},e.prototype.shade=function(e){return void 0===e&&(e=10),this.mix("black",e)},e.prototype.desaturate=function(t){void 0===t&&(t=10);var r=this.toHsl();return r.s-=t/100,r.s=(0,a.V2)(r.s),new e(r)},e.prototype.saturate=function(t){void 0===t&&(t=10);var r=this.toHsl();return r.s+=t/100,r.s=(0,a.V2)(r.s),new e(r)},e.prototype.greyscale=function(){return this.desaturate(100)},e.prototype.spin=function(t){var r=this.toHsl(),n=(r.h+t)%360;return r.h=n<0?360+n:n,new e(r)},e.prototype.mix=function(t,r){void 0===r&&(r=50);var n=this.toRgb(),i=new e(t).toRgb(),o=r/100;return new e({r:(i.r-n.r)*o+n.r,g:(i.g-n.g)*o+n.g,b:(i.b-n.b)*o+n.b,a:(i.a-n.a)*o+n.a})},e.prototype.analogous=function(t,r){void 0===t&&(t=6),void 0===r&&(r=30);var n=this.toHsl(),i=360/r,o=[this];for(n.h=(n.h-(i*t>>1)+720)%360;--t;)n.h=(n.h+i)%360,o.push(new e(n));return o},e.prototype.complement=function(){var t=this.toHsl();return t.h=(t.h+180)%360,new e(t)},e.prototype.monochromatic=function(t){void 0===t&&(t=6);for(var r=this.toHsv(),n=r.h,i=r.s,o=r.v,a=[],s=1/t;t--;)a.push(new e({h:n,s:i,v:o})),o=(o+s)%1;return a},e.prototype.splitcomplement=function(){var t=this.toHsl(),r=t.h;return[this,new e({h:(r+72)%360,s:t.s,l:t.l}),new e({h:(r+216)%360,s:t.s,l:t.l})]},e.prototype.onBackground=function(t){var r=this.toRgb(),n=new e(t).toRgb(),i=r.a+n.a*(1-r.a);return new e({r:(r.r*r.a+n.r*n.a*(1-r.a))/i,g:(r.g*r.a+n.g*n.a*(1-r.a))/i,b:(r.b*r.a+n.b*n.a*(1-r.a))/i,a:i})},e.prototype.triad=function(){return this.polyad(3)},e.prototype.tetrad=function(){return this.polyad(4)},e.prototype.polyad=function(t){for(var r=this.toHsl(),n=r.h,i=[this],o=360/t,a=1;a<t;a++)i.push(new e({h:(n+a*o)%360,s:r.s,l:r.l}));return i},e.prototype.equals=function(t){return this.toRgbString()===new e(t).toRgbString()},e}()},33146:function(e,t,r){"use strict";function n(e,t){o(e)&&(e="100%");var r=a(e);return(e=360===t?e:Math.min(t,Math.max(0,parseFloat(e))),r&&(e=parseInt(String(e*t),10)/100),1e-6>Math.abs(e-t))?1:e=360===t?(e<0?e%t+t:e%t)/parseFloat(String(t)):e%t/parseFloat(String(t))}function i(e){return Math.min(1,Math.max(0,e))}function o(e){return"string"==typeof e&&-1!==e.indexOf(".")&&1===parseFloat(e)}function a(e){return"string"==typeof e&&-1!==e.indexOf("%")}function s(e){return(isNaN(e=parseFloat(e))||e<0||e>1)&&(e=1),e}function l(e){return e<=1?"".concat(100*Number(e),"%"):e}function u(e){return 1===e.length?"0"+e:String(e)}r.d(t,{FZ:()=>u,JX:()=>l,V2:()=>i,Yq:()=>s,sh:()=>n})},68013:function(e,t,r){"use strict";r.d(t,{Z:()=>S});var n=r(57987),i=r(44194),o=r(56321),a=r(33229);r(28740);var s=r(38726);let l=i.createContext(null);var u=r(81632),c=r(16713),h=[];function f(e,t){var r=i.useState(function(){return(0,a.Z)()?document.createElement("div"):null}),o=(0,n.Z)(r,1)[0],s=i.useRef(!1),f=i.useContext(l),d=i.useState(h),p=(0,n.Z)(d,2),m=p[0],g=p[1],y=f||(s.current?void 0:function(e){g(function(t){return[e].concat((0,u.Z)(t))})});function v(){o.parentElement||document.body.appendChild(o),s.current=!0}function b(){var e;null==(e=o.parentElement)||e.removeChild(o),s.current=!1}return(0,c.Z)(function(){return e?f?f(v):v():b(),b},[e]),(0,c.Z)(function(){m.length&&(m.forEach(function(e){return e()}),g(h))},[m]),[o,y]}var d=r(96345);function p(e){var t,r,n="rc-scrollbar-measure-".concat(Math.random().toString(36).substring(7)),i=document.createElement("div");i.id=n;var o=i.style;if(o.position="absolute",o.left="0",o.top="0",o.width="100px",o.height="100px",o.overflow="scroll",e){var a=getComputedStyle(e);o.scrollbarColor=a.scrollbarColor,o.scrollbarWidth=a.scrollbarWidth;var s=getComputedStyle(e,"::-webkit-scrollbar"),l=parseInt(s.width,10),u=parseInt(s.height,10);try{var c=l?"width: ".concat(s.width,";"):"",h=u?"height: ".concat(s.height,";"):"";(0,d.hq)("\n#".concat(n,"::-webkit-scrollbar {\n").concat(c,"\n").concat(h,"\n}"),n)}catch(e){console.error(e),t=l,r=u}}document.body.appendChild(i);var f=e&&t&&!isNaN(t)?t:i.offsetWidth-i.clientWidth,p=e&&r&&!isNaN(r)?r:i.offsetHeight-i.clientHeight;return document.body.removeChild(i),(0,d.jL)(n),{width:f,height:p}}function m(e){return"undefined"!=typeof document&&e&&e instanceof Element?p(e):{width:0,height:0}}function g(){return document.body.scrollHeight>(window.innerHeight||document.documentElement.clientHeight)&&window.innerWidth>document.body.offsetWidth}var y="rc-util-locker-".concat(Date.now()),v=0;function b(e){var t=!!e,r=i.useState(function(){return v+=1,"".concat(y,"_").concat(v)}),o=(0,n.Z)(r,1)[0];(0,c.Z)(function(){if(t){var e=m(document.body).width,r=g();(0,d.hq)("\nhtml body {\n overflow-y: hidden;\n ".concat(r?"width: calc(100% - ".concat(e,"px);"):"","\n}"),o)}else(0,d.jL)(o);return function(){(0,d.jL)(o)}},[t,o])}var _=!1;function w(e){return"boolean"==typeof e&&(_=e),_}var x=function(e){return!1!==e&&((0,a.Z)()&&e?"string"==typeof e?document.querySelector(e):"function"==typeof e?e():e:null)};let S=i.forwardRef(function(e,t){var r=e.open,u=e.autoLock,c=e.getContainer,h=e.debug,d=e.autoDestroy,p=void 0===d||d,m=e.children,g=i.useState(r),y=(0,n.Z)(g,2),v=y[0],_=y[1],S=v||r;i.useEffect(function(){(p||r)&&_(r)},[r,p]);var E=i.useState(function(){return x(c)}),C=(0,n.Z)(E,2),A=C[0],k=C[1];i.useEffect(function(){var e=x(c);k(null!=e?e:null)});var O=f(S&&!A,h),T=(0,n.Z)(O,2),I=T[0],P=T[1],R=null!=A?A:I;b(u&&r&&(0,a.Z)()&&(R===I||R===document.body));var M=null;m&&(0,s.Yr)(m)&&t&&(M=m.ref);var $=(0,s.x1)(M,t);if(!S||!(0,a.Z)()||void 0===A)return null;var N=!1===R||w(),j=m;return t&&(j=i.cloneElement(m,{ref:$})),i.createElement(l.Provider,{value:P},N?j:(0,o.createPortal)(j,R))})},74912:function(e,t,r){"use strict";r.d(t,{Z:()=>q});var n=r(19741),i=r(57987),o=r(52755),a=r(68013),s=r(41229),l=r.n(s),u=r(29659),c=r(40660),h=r(5940),f=r(81446),d=r(21096),p=r(16713),m=r(88487),g=r(44194),y=r(25833),v=r(55940),b=r(38726);function _(e){var t=e.prefixCls,r=e.align,n=e.arrow,i=e.arrowPos,o=n||{},a=o.className,s=o.content,u=i.x,c=void 0===u?0:u,h=i.y,f=void 0===h?0:h,d=g.useRef();if(!r||!r.points)return null;var p={position:"absolute"};if(!1!==r.autoArrow){var m=r.points[0],y=r.points[1],v=m[0],b=m[1],_=y[0],w=y[1];v!==_&&["t","b"].includes(v)?"t"===v?p.top=0:p.bottom=0:p.top=f,b!==w&&["l","r"].includes(b)?"l"===b?p.left=0:p.right=0:p.left=c}return g.createElement("div",{ref:d,className:l()("".concat(t,"-arrow"),a),style:p},s)}function w(e){var t=e.prefixCls,r=e.open,n=e.zIndex,i=e.mask,o=e.motion;return i?g.createElement(v.ZP,(0,y.Z)({},o,{motionAppear:!0,visible:r,removeOnLeave:!0}),function(e){var r=e.className;return g.createElement("div",{style:{zIndex:n},className:l()("".concat(t,"-mask"),r)})}):null}let x=g.memo(function(e){return e.children},function(e,t){return t.cache}),S=g.forwardRef(function(e,t){var r=e.popup,o=e.className,a=e.prefixCls,s=e.style,c=e.target,h=e.onVisibleChanged,f=e.open,d=e.keepDom,m=e.fresh,S=e.onClick,E=e.mask,C=e.arrow,A=e.arrowPos,k=e.align,O=e.motion,T=e.maskMotion,I=e.forceRender,P=e.getPopupContainer,R=e.autoDestroy,M=e.portal,$=e.zIndex,N=e.onMouseEnter,j=e.onMouseLeave,B=e.onPointerEnter,L=e.ready,F=e.offsetX,D=e.offsetY,z=e.offsetR,U=e.offsetB,Z=e.onAlign,H=e.onPrepare,G=e.stretch,W=e.targetWidth,q=e.targetHeight,V="function"==typeof r?r():r,X=f||d,Y=(null==P?void 0:P.length)>0,K=g.useState(!P||!Y),J=(0,i.Z)(K,2),Q=J[0],ee=J[1];if((0,p.Z)(function(){!Q&&Y&&c&&ee(!0)},[Q,Y,c]),!Q)return null;var et="auto",er={left:"-1000vw",top:"-1000vh",right:et,bottom:et};if(L||!f){var en,ei=k.points,eo=k.dynamicInset||(null==(en=k._experimental)?void 0:en.dynamicInset),ea=eo&&"r"===ei[0][1],es=eo&&"b"===ei[0][0];ea?(er.right=z,er.left=et):(er.left=F,er.right=et),es?(er.bottom=U,er.top=et):(er.top=D,er.bottom=et)}var el={};return G&&(G.includes("height")&&q?el.height=q:G.includes("minHeight")&&q&&(el.minHeight=q),G.includes("width")&&W?el.width=W:G.includes("minWidth")&&W&&(el.minWidth=W)),f||(el.pointerEvents="none"),g.createElement(M,{open:I||X,getContainer:P&&function(){return P(c)},autoDestroy:R},g.createElement(w,{prefixCls:a,open:f,zIndex:$,mask:E,motion:T}),g.createElement(u.Z,{onResize:Z,disabled:!f},function(e){return g.createElement(v.ZP,(0,y.Z)({motionAppear:!0,motionEnter:!0,motionLeave:!0,removeOnLeave:!1,forceRender:I,leavedClassName:"".concat(a,"-hidden")},O,{onAppearPrepare:H,onEnterPrepare:H,visible:f,onVisibleChanged:function(e){var t;null==O||null==(t=O.onVisibleChanged)||t.call(O,e),h(e)}}),function(r,i){var u=r.className,c=r.style,h=l()(a,u,o);return g.createElement("div",{ref:(0,b.sQ)(e,t,i),className:h,style:(0,n.Z)((0,n.Z)((0,n.Z)((0,n.Z)({"--arrow-x":"".concat(A.x||0,"px"),"--arrow-y":"".concat(A.y||0,"px")},er),el),c),{},{boxSizing:"border-box",zIndex:$},s),onMouseEnter:N,onMouseLeave:j,onPointerEnter:B,onClick:S},C&&g.createElement(_,{prefixCls:a,arrow:C,arrowPos:A,align:k}),g.createElement(x,{cache:!f&&!m},V))})}))}),E=g.forwardRef(function(e,t){var r=e.children,n=e.getTriggerDOMNode,i=(0,b.Yr)(r),o=g.useCallback(function(e){(0,b.mH)(t,n?n(e):e)},[n]),a=(0,b.x1)(o,r.ref);return i?g.cloneElement(r,{ref:a}):r}),C=g.createContext(null);function A(e){return e?Array.isArray(e)?e:[e]:[]}function k(e,t,r,n){return g.useMemo(function(){var i=A(null!=r?r:t),o=A(null!=n?n:t),a=new Set(i),s=new Set(o);return e&&(a.has("hover")&&(a.delete("hover"),a.add("click")),s.has("hover")&&(s.delete("hover"),s.add("click"))),[a,s]},[e,t,r,n])}var O=r(19014);function T(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2?arguments[2]:void 0;return r?e[0]===t[0]:e[0]===t[0]&&e[1]===t[1]}function I(e,t,r,n){for(var i=r.points,o=Object.keys(e),a=0;a<o.length;a+=1){var s,l=o[a];if(T(null==(s=e[l])?void 0:s.points,i,n))return"".concat(t,"-placement-").concat(l)}return""}function P(e,t,r,n){return t||(r?{motionName:"".concat(e,"-").concat(r)}:n?{motionName:n}:null)}function R(e){return e.ownerDocument.defaultView}function M(e){for(var t=[],r=null==e?void 0:e.parentElement,n=["hidden","scroll","clip","auto"];r;){var i=R(r).getComputedStyle(r);[i.overflowX,i.overflowY,i.overflow].some(function(e){return n.includes(e)})&&t.push(r),r=r.parentElement}return t}function $(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return Number.isNaN(e)?t:e}function N(e){return $(parseFloat(e),0)}function j(e,t){var r=(0,n.Z)({},e);return(t||[]).forEach(function(e){if(!(e instanceof HTMLBodyElement||e instanceof HTMLHtmlElement)){var t=R(e).getComputedStyle(e),n=t.overflow,i=t.overflowClipMargin,o=t.borderTopWidth,a=t.borderBottomWidth,s=t.borderLeftWidth,l=t.borderRightWidth,u=e.getBoundingClientRect(),c=e.offsetHeight,h=e.clientHeight,f=e.offsetWidth,d=e.clientWidth,p=N(o),m=N(a),g=N(s),y=N(l),v=$(Math.round(u.width/f*1e3)/1e3),b=$(Math.round(u.height/c*1e3)/1e3),_=(f-d-g-y)*v,w=(c-h-p-m)*b,x=p*b,S=m*b,E=g*v,C=y*v,A=0,k=0;if("clip"===n){var O=N(i);A=O*v,k=O*b}var T=u.x+E-A,I=u.y+x-k,P=T+u.width+2*A-E-C-_,M=I+u.height+2*k-x-S-w;r.left=Math.max(r.left,T),r.top=Math.max(r.top,I),r.right=Math.min(r.right,P),r.bottom=Math.min(r.bottom,M)}}),r}function B(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r="".concat(t),n=r.match(/^(.*)\%$/);return n?e*(parseFloat(n[1])/100):parseFloat(r)}function L(e,t){var r=t||[],n=(0,i.Z)(r,2),o=n[0],a=n[1];return[B(e.width,o),B(e.height,a)]}function F(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return[e[0],e[1]]}function D(e,t){var r,n,i=t[0],o=t[1];return n="t"===i?e.y:"b"===i?e.y+e.height:e.y+e.height/2,{x:r="l"===o?e.x:"r"===o?e.x+e.width:e.x+e.width/2,y:n}}function z(e,t){var r={t:"b",b:"t",l:"r",r:"l"};return e.map(function(e,n){return n===t?r[e]||"c":e}).join("")}function U(e,t,r,o,a,s,l){var u=g.useState({ready:!1,offsetX:0,offsetY:0,offsetR:0,offsetB:0,arrowX:0,arrowY:0,scaleX:1,scaleY:1,align:a[o]||{}}),h=(0,i.Z)(u,2),d=h[0],m=h[1],y=g.useRef(0),v=g.useMemo(function(){return t?M(t):[]},[t]),b=g.useRef({}),_=function(){b.current={}};e||_();var w=(0,f.Z)(function(){if(t&&r&&e){var u,h,f,d,p=t,g=p.ownerDocument,y=R(p).getComputedStyle(p),_=y.width,w=y.height,x=y.position,S=p.style.left,E=p.style.top,C=p.style.right,A=p.style.bottom,k=p.style.overflow,T=(0,n.Z)((0,n.Z)({},a[o]),s),I=g.createElement("div");if(null==(P=p.parentElement)||P.appendChild(I),I.style.left="".concat(p.offsetLeft,"px"),I.style.top="".concat(p.offsetTop,"px"),I.style.position=x,I.style.height="".concat(p.offsetHeight,"px"),I.style.width="".concat(p.offsetWidth,"px"),p.style.left="0",p.style.top="0",p.style.right="auto",p.style.bottom="auto",p.style.overflow="hidden",Array.isArray(r))U={x:r[0],y:r[1],width:0,height:0};else{var P,M,N,B,U,Z,H,G=r.getBoundingClientRect();G.x=null!=(Z=G.x)?Z:G.left,G.y=null!=(H=G.y)?H:G.top,U={x:G.x,y:G.y,width:G.width,height:G.height}}var W=p.getBoundingClientRect();W.x=null!=(M=W.x)?M:W.left,W.y=null!=(N=W.y)?N:W.top;var q=g.documentElement,V=q.clientWidth,X=q.clientHeight,Y=q.scrollWidth,K=q.scrollHeight,J=q.scrollTop,Q=q.scrollLeft,ee=W.height,et=W.width,er=U.height,en=U.width,ei={left:0,top:0,right:V,bottom:X},eo={left:-Q,top:-J,right:Y-Q,bottom:K-J},ea=T.htmlRegion,es="visible",el="visibleFirst";"scroll"!==ea&&ea!==el&&(ea=es);var eu=ea===el,ec=j(eo,v),eh=j(ei,v),ef=ea===es?eh:ec,ed=eu?eh:ef;p.style.left="auto",p.style.top="auto",p.style.right="0",p.style.bottom="0";var ep=p.getBoundingClientRect();p.style.left=S,p.style.top=E,p.style.right=C,p.style.bottom=A,p.style.overflow=k,null==(B=p.parentElement)||B.removeChild(I);var em=$(Math.round(et/parseFloat(_)*1e3)/1e3),eg=$(Math.round(ee/parseFloat(w)*1e3)/1e3);if(!(0===em||0===eg||(0,c.Sh)(r)&&!(0,O.Z)(r))){var ey=T.offset,ev=T.targetOffset,eb=L(W,ey),e_=(0,i.Z)(eb,2),ew=e_[0],ex=e_[1],eS=L(U,ev),eE=(0,i.Z)(eS,2),eC=eE[0],eA=eE[1];U.x-=eC,U.y-=eA;var ek=T.points||[],eO=(0,i.Z)(ek,2),eT=eO[0],eI=eO[1],eP=F(eI),eR=F(eT),eM=D(U,eP),e$=D(W,eR),eN=(0,n.Z)({},T),ej=eM.x-e$.x+ew,eB=eM.y-e$.y+ex,eL=tS(ej,eB),eF=tS(ej,eB,eh),eD=D(U,["t","l"]),ez=D(W,["t","l"]),eU=D(U,["b","r"]),eZ=D(W,["b","r"]),eH=T.overflow||{},eG=eH.adjustX,eW=eH.adjustY,eq=eH.shiftX,eV=eH.shiftY,eX=function(e){return"boolean"==typeof e?e:e>=0};tE();var eY=eX(eW),eK=eR[0]===eP[0];if(eY&&"t"===eR[0]&&(h>ed.bottom||b.current.bt)){var eJ=eB;eK?eJ-=ee-er:eJ=eD.y-eZ.y-ex;var eQ=tS(ej,eJ),e0=tS(ej,eJ,eh);eQ>eL||eQ===eL&&(!eu||e0>=eF)?(b.current.bt=!0,eB=eJ,ex=-ex,eN.points=[z(eR,0),z(eP,0)]):b.current.bt=!1}if(eY&&"b"===eR[0]&&(u<ed.top||b.current.tb)){var e1=eB;eK?e1+=ee-er:e1=eU.y-ez.y-ex;var e2=tS(ej,e1),e3=tS(ej,e1,eh);e2>eL||e2===eL&&(!eu||e3>=eF)?(b.current.tb=!0,eB=e1,ex=-ex,eN.points=[z(eR,0),z(eP,0)]):b.current.tb=!1}var e5=eX(eG),e4=eR[1]===eP[1];if(e5&&"l"===eR[1]&&(d>ed.right||b.current.rl)){var e6=ej;e4?e6-=et-en:e6=eD.x-eZ.x-ew;var e8=tS(e6,eB),e9=tS(e6,eB,eh);e8>eL||e8===eL&&(!eu||e9>=eF)?(b.current.rl=!0,ej=e6,ew=-ew,eN.points=[z(eR,1),z(eP,1)]):b.current.rl=!1}if(e5&&"r"===eR[1]&&(f<ed.left||b.current.lr)){var e7=ej;e4?e7+=et-en:e7=eU.x-ez.x-ew;var te=tS(e7,eB),tt=tS(e7,eB,eh);te>eL||te===eL&&(!eu||tt>=eF)?(b.current.lr=!0,ej=e7,ew=-ew,eN.points=[z(eR,1),z(eP,1)]):b.current.lr=!1}tE();var tr=!0===eq?0:eq;"number"==typeof tr&&(f<eh.left&&(ej-=f-eh.left-ew,U.x+en<eh.left+tr&&(ej+=U.x-eh.left+en-tr)),d>eh.right&&(ej-=d-eh.right-ew,U.x>eh.right-tr&&(ej+=U.x-eh.right+tr)));var tn=!0===eV?0:eV;"number"==typeof tn&&(u<eh.top&&(eB-=u-eh.top-ex,U.y+er<eh.top+tn&&(eB+=U.y-eh.top+er-tn)),h>eh.bottom&&(eB-=h-eh.bottom-ex,U.y>eh.bottom-tn&&(eB+=U.y-eh.bottom+tn)));var ti=W.x+ej,to=ti+et,ta=W.y+eB,ts=ta+ee,tl=U.x,tu=tl+en,tc=U.y,th=tc+er,tf=Math.max(ti,tl),td=Math.min(to,tu),tp=(tf+td)/2,tm=tp-ti,tg=Math.max(ta,tc),ty=Math.min(ts,th),tv=(tg+ty)/2,tb=tv-ta;null==l||l(t,eN);var t_=ep.right-W.x-(ej+W.width),tw=ep.bottom-W.y-(eB+W.height);1===em&&(ej=Math.round(ej),t_=Math.round(t_)),1===eg&&(eB=Math.round(eB),tw=Math.round(tw));var tx={ready:!0,offsetX:ej/em,offsetY:eB/eg,offsetR:t_/em,offsetB:tw/eg,arrowX:tm/em,arrowY:tb/eg,scaleX:em,scaleY:eg,align:eN};m(tx)}function tS(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ef,n=W.x+e,i=W.y+t,o=n+et,a=i+ee,s=Math.max(n,r.left),l=Math.max(i,r.top);return Math.max(0,(Math.min(o,r.right)-s)*(Math.min(a,r.bottom)-l))}function tE(){h=(u=W.y+eB)+ee,d=(f=W.x+ej)+et}}}),x=function(){y.current+=1;var e=y.current;Promise.resolve().then(function(){y.current===e&&w()})},S=function(){m(function(e){return(0,n.Z)((0,n.Z)({},e),{},{ready:!1})})};return(0,p.Z)(S,[o]),(0,p.Z)(function(){e||S()},[e]),[d.ready,d.offsetX,d.offsetY,d.offsetR,d.offsetB,d.arrowX,d.arrowY,d.scaleX,d.scaleY,d.align,x]}var Z=r(81632);function H(e,t,r,n,i){(0,p.Z)(function(){if(e&&t&&r){var o=r,a=M(t),s=M(o),l=R(o),u=new Set([l].concat((0,Z.Z)(a),(0,Z.Z)(s)));function c(){n(),i()}return u.forEach(function(e){e.addEventListener("scroll",c,{passive:!0})}),l.addEventListener("resize",c,{passive:!0}),n(),function(){u.forEach(function(e){e.removeEventListener("scroll",c),l.removeEventListener("resize",c)})}}},[e,t,r])}function G(e,t,r,n,i,o,a,s){var l=g.useRef(e);l.current=e,g.useEffect(function(){if(t&&n&&(!i||o)){var e=function(e){var t;l.current&&!a((null==(t=e.composedPath)||null==(t=t.call(e))?void 0:t[0])||e.target)&&s(!1)},u=R(n);u.addEventListener("mousedown",e,!0),u.addEventListener("contextmenu",e,!0);var c=(0,h.A)(r);return c&&(c.addEventListener("mousedown",e,!0),c.addEventListener("contextmenu",e,!0)),function(){u.removeEventListener("mousedown",e,!0),u.removeEventListener("contextmenu",e,!0),c&&(c.removeEventListener("mousedown",e,!0),c.removeEventListener("contextmenu",e,!0))}}},[t,r,n,i,o])}r(28740);var W=["prefixCls","children","action","showAction","hideAction","popupVisible","defaultPopupVisible","onPopupVisibleChange","afterPopupVisibleChange","mouseEnterDelay","mouseLeaveDelay","focusDelay","blurDelay","mask","maskClosable","getPopupContainer","forceRender","autoDestroy","destroyPopupOnHide","popup","popupClassName","popupStyle","popupPlacement","builtinPlacements","popupAlign","zIndex","stretch","getPopupClassNameFromAlign","fresh","alignPoint","onPopupClick","onPopupAlign","arrow","popupMotion","maskMotion","popupTransitionName","popupAnimation","maskTransitionName","maskAnimation","className","getTriggerDOMNode"];let q=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a.Z;return g.forwardRef(function(t,r){var a,s,y=t.prefixCls,v=void 0===y?"rc-trigger-popup":y,b=t.children,_=t.action,w=void 0===_?"hover":_,x=t.showAction,A=t.hideAction,O=t.popupVisible,T=t.defaultPopupVisible,R=t.onPopupVisibleChange,M=t.afterPopupVisibleChange,$=t.mouseEnterDelay,N=t.mouseLeaveDelay,j=void 0===N?.1:N,B=t.focusDelay,L=t.blurDelay,F=t.mask,D=t.maskClosable,z=void 0===D||D,Z=t.getPopupContainer,q=t.forceRender,V=t.autoDestroy,X=t.destroyPopupOnHide,Y=t.popup,K=t.popupClassName,J=t.popupStyle,Q=t.popupPlacement,ee=t.builtinPlacements,et=void 0===ee?{}:ee,er=t.popupAlign,en=t.zIndex,ei=t.stretch,eo=t.getPopupClassNameFromAlign,ea=t.fresh,es=t.alignPoint,el=t.onPopupClick,eu=t.onPopupAlign,ec=t.arrow,eh=t.popupMotion,ef=t.maskMotion,ed=t.popupTransitionName,ep=t.popupAnimation,em=t.maskTransitionName,eg=t.maskAnimation,ey=t.className,ev=t.getTriggerDOMNode,eb=(0,o.Z)(t,W),e_=V||X||!1,ew=g.useState(!1),ex=(0,i.Z)(ew,2),eS=ex[0],eE=ex[1];(0,p.Z)(function(){eE((0,m.Z)())},[]);var eC=g.useRef({}),eA=g.useContext(C),ek=g.useMemo(function(){return{registerSubPopup:function(e,t){eC.current[e]=t,null==eA||eA.registerSubPopup(e,t)}}},[eA]),eO=(0,d.Z)(),eT=g.useState(null),eI=(0,i.Z)(eT,2),eP=eI[0],eR=eI[1],eM=g.useRef(null),e$=(0,f.Z)(function(e){eM.current=e,(0,c.Sh)(e)&&eP!==e&&eR(e),null==eA||eA.registerSubPopup(eO,e)}),eN=g.useState(null),ej=(0,i.Z)(eN,2),eB=ej[0],eL=ej[1],eF=g.useRef(null),eD=(0,f.Z)(function(e){(0,c.Sh)(e)&&eB!==e&&(eL(e),eF.current=e)}),ez=g.Children.only(b),eU=(null==ez?void 0:ez.props)||{},eZ={},eH=(0,f.Z)(function(e){var t,r,n=eB;return(null==n?void 0:n.contains(e))||(null==(t=(0,h.A)(n))?void 0:t.host)===e||e===n||(null==eP?void 0:eP.contains(e))||(null==(r=(0,h.A)(eP))?void 0:r.host)===e||e===eP||Object.values(eC.current).some(function(t){return(null==t?void 0:t.contains(e))||e===t})}),eG=P(v,eh,ep,ed),eW=P(v,ef,eg,em),eq=g.useState(T||!1),eV=(0,i.Z)(eq,2),eX=eV[0],eY=eV[1],eK=null!=O?O:eX,eJ=(0,f.Z)(function(e){void 0===O&&eY(e)});(0,p.Z)(function(){eY(O||!1)},[O]);var eQ=g.useRef(eK);eQ.current=eK;var e0=g.useRef([]);e0.current=[];var e1=(0,f.Z)(function(e){var t;eJ(e),(null!=(t=e0.current[e0.current.length-1])?t:eK)!==e&&(e0.current.push(e),null==R||R(e))}),e2=g.useRef(),e3=function(){clearTimeout(e2.current)},e5=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;e3(),0===t?e1(e):e2.current=setTimeout(function(){e1(e)},1e3*t)};g.useEffect(function(){return e3},[]);var e4=g.useState(!1),e6=(0,i.Z)(e4,2),e8=e6[0],e9=e6[1];(0,p.Z)(function(e){(!e||eK)&&e9(!0)},[eK]);var e7=g.useState(null),te=(0,i.Z)(e7,2),tt=te[0],tr=te[1],tn=g.useState(null),ti=(0,i.Z)(tn,2),to=ti[0],ta=ti[1],ts=function(e){ta([e.clientX,e.clientY])},tl=U(eK,eP,es&&null!==to?to:eB,Q,et,er,eu),tu=(0,i.Z)(tl,11),tc=tu[0],th=tu[1],tf=tu[2],td=tu[3],tp=tu[4],tm=tu[5],tg=tu[6],ty=tu[7],tv=tu[8],tb=tu[9],t_=tu[10],tw=k(eS,w,x,A),tx=(0,i.Z)(tw,2),tS=tx[0],tE=tx[1],tC=tS.has("click"),tA=tE.has("click")||tE.has("contextMenu"),tk=(0,f.Z)(function(){e8||t_()});H(eK,eB,eP,tk,function(){eQ.current&&es&&tA&&e5(!1)}),(0,p.Z)(function(){tk()},[to,Q]),(0,p.Z)(function(){eK&&!(null!=et&&et[Q])&&tk()},[JSON.stringify(er)]);var tO=g.useMemo(function(){var e=I(et,v,tb,es);return l()(e,null==eo?void 0:eo(tb))},[tb,eo,et,v,es]);g.useImperativeHandle(r,function(){return{nativeElement:eF.current,popupElement:eM.current,forceAlign:tk}});var tT=g.useState(0),tI=(0,i.Z)(tT,2),tP=tI[0],tR=tI[1],tM=g.useState(0),t$=(0,i.Z)(tM,2),tN=t$[0],tj=t$[1],tB=function(){if(ei&&eB){var e=eB.getBoundingClientRect();tR(e.width),tj(e.height)}},tL=function(){tB(),tk()},tF=function(e){e9(!1),t_(),null==M||M(e)},tD=function(){return new Promise(function(e){tB(),tr(function(){return e})})};function tz(e,t,r,n){eZ[e]=function(i){var o;null==n||n(i),e5(t,r);for(var a=arguments.length,s=Array(a>1?a-1:0),l=1;l<a;l++)s[l-1]=arguments[l];null==(o=eU[e])||o.call.apply(o,[eU,i].concat(s))}}(0,p.Z)(function(){tt&&(t_(),tt(),tr(null))},[tt]),(tC||tA)&&(eZ.onClick=function(e){var t;eQ.current&&tA?e5(!1):!eQ.current&&tC&&(ts(e),e5(!0));for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];null==(t=eU.onClick)||t.call.apply(t,[eU,e].concat(n))}),G(eK,tA,eB,eP,F,z,eH,e5);var tU=tS.has("hover"),tZ=tE.has("hover");tU&&(tz("onMouseEnter",!0,$,function(e){ts(e)}),tz("onPointerEnter",!0,$,function(e){ts(e)}),a=function(e){(eK||e8)&&null!=eP&&eP.contains(e.target)&&e5(!0,$)},es&&(eZ.onMouseMove=function(e){var t;null==(t=eU.onMouseMove)||t.call(eU,e)})),tZ&&(tz("onMouseLeave",!1,j),tz("onPointerLeave",!1,j),s=function(){e5(!1,j)}),tS.has("focus")&&tz("onFocus",!0,B),tE.has("focus")&&tz("onBlur",!1,L),tS.has("contextMenu")&&(eZ.onContextMenu=function(e){var t;eQ.current&&tE.has("contextMenu")?e5(!1):(ts(e),e5(!0)),e.preventDefault();for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];null==(t=eU.onContextMenu)||t.call.apply(t,[eU,e].concat(n))}),ey&&(eZ.className=l()(eU.className,ey));var tH=(0,n.Z)((0,n.Z)({},eU),eZ),tG={};["onContextMenu","onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"].forEach(function(e){eb[e]&&(tG[e]=function(){for(var t,r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];null==(t=tH[e])||t.call.apply(t,[tH].concat(n)),eb[e].apply(eb,n)})});var tW=g.cloneElement(ez,(0,n.Z)((0,n.Z)({},tH),tG)),tq={x:tm,y:tg},tV=ec?(0,n.Z)({},!0!==ec?ec:{}):null;return g.createElement(g.Fragment,null,g.createElement(u.Z,{disabled:!eK,ref:eD,onResize:tL},g.createElement(E,{getTriggerDOMNode:ev},tW)),g.createElement(C.Provider,{value:ek},g.createElement(S,{portal:e,ref:e$,prefixCls:v,popup:Y,className:l()(K,tO),style:J,target:eB,onMouseEnter:a,onMouseLeave:s,onPointerEnter:a,zIndex:en,open:eK,keepDom:e8,fresh:ea,onClick:el,mask:F,motion:eG,maskMotion:eW,onVisibleChanged:tF,onPrepare:tD,forceRender:q,autoDestroy:e_,getPopupContainer:Z,align:tb,arrow:tV,arrowPos:tq,ready:tc,offsetX:th,offsetY:tf,offsetR:td,offsetB:tp,onAlign:tk,stretch:ei,targetWidth:tP/ty,targetHeight:tN/tv})))})}(a.Z)},98536:function(e,t,r){"use strict";var n=r(57861).Buffer,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.req=t.json=t.toBuffer=void 0;let s=a(r(66046)),l=a(r(2904));async function u(e){let t=0,r=[];for await(let n of e)t+=n.length,r.push(n);return n.concat(r,t)}t.toBuffer=u,t.json=async function(e){let t=(await u(e)).toString("utf8");try{return JSON.parse(t)}catch(r){let e=r;throw e.message+=` (input: ${t})`,e}},t.req=function(e,t={}){let r=(("string"==typeof e?e:e.href).startsWith("https:")?l:s).request(e,t),n=new Promise((e,t)=>{r.once("response",e).once("error",t).end()});return r.then=n.then.bind(n),r}},32313:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t},a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.Agent=void 0;let s=o(r(86110)),l=o(r(66046)),u=r(2904);a(r(98536),t);let c=Symbol("AgentBaseInternalState");class h extends l.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}let{stack:t}=Error();return"string"==typeof t&&t.split("\n").some(e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:"))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new s.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;let r=this.sockets[e],n=r.indexOf(t);-1!==n&&(r.splice(n,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return("boolean"==typeof e.secureEndpoint?e.secureEndpoint:this.isSecureEndpoint(e))?u.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){let n={...t,secureEndpoint:this.isSecureEndpoint(t)},i=this.getName(n),o=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,n)).then(a=>{if(this.decrementSockets(i,o),a instanceof l.Agent)try{return a.addRequest(e,n)}catch(e){return r(e)}this[c].currentSocket=a,super.createSocket(e,t,r)},e=>{this.decrementSockets(i,o),r(e)})}createConnection(){let e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}}t.Agent=h},8300:function(e,t,r){"use strict";e=r.nmd(e);let n=10,i=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,o=(e=0)=>(t,r,n)=>`\u001B[${38+e};2;${t};${r};${n}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};for(let[r,n]of(t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright,Object.entries(t))){for(let[r,i]of Object.entries(n))t[r]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},n[r]=t[r],e.set(i[0],i[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1b[39m",t.bgColor.close="\x1b[49m",t.color.ansi256=i(),t.color.ansi16m=o(),t.bgColor.ansi256=i(n),t.bgColor.ansi16m=o(n),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map(e=>e+e).join(""));let n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},49619:function(e,t,r){"use strict";r.d(t,{Z:()=>a});var n=r(44194),i=r(89258),o=r(64841);let a=e=>{let{space:t,form:r,children:a}=e;if(null==a)return null;let s=a;return r&&(s=n.createElement(i.Ux,{override:!0,status:!0},s)),t&&(s=n.createElement(o.BR,null,s)),s}},92708:function(e,t,r){"use strict";r.d(t,{Z:()=>l,i:()=>s});var n=r(44194),i=r(66744),o=r(16327),a=r(97266);function s(e){return t=>n.createElement(o.ZP,{theme:{token:{motion:!1,zIndexPopupBase:0}}},n.createElement(e,Object.assign({},t)))}let l=(e,t,r,o)=>s(s=>{let{prefixCls:l,style:u}=s,c=n.useRef(null),[h,f]=n.useState(0),[d,p]=n.useState(0),[m,g]=(0,i.Z)(!1,{value:s.open}),{getPrefixCls:y}=n.useContext(a.E_),v=y(t||"select",l);n.useEffect(()=>{if(g(!0),"undefined"!=typeof ResizeObserver){let e=new ResizeObserver(e=>{let t=e[0].target;f(t.offsetHeight+8),p(t.offsetWidth)}),t=setInterval(()=>{var n;let i=r?`.${r(v)}`:`.${v}-dropdown`,o=null==(n=c.current)?void 0:n.querySelector(i);o&&(clearInterval(t),e.observe(o))},10);return()=>{clearInterval(t),e.disconnect()}}},[]);let b=Object.assign(Object.assign({},s),{style:Object.assign(Object.assign({},u),{margin:0}),open:m,visible:m,getPopupContainer:()=>c.current});o&&(b=o(b));let _={paddingBottom:h,position:"relative",minWidth:d};return n.createElement("div",{ref:c,style:_},n.createElement(e,Object.assign({},b)))})},29514:function(e,t,r){"use strict";r.d(t,{Z:()=>o});var n=r(44194),i=r(55655);let o=e=>{let t;return"object"==typeof e&&(null==e?void 0:e.clearIcon)?t=e:e&&(t={clearIcon:n.createElement(i.Z,null)}),t}},28175:function(e,t,r){"use strict";r.d(t,{Cn:()=>c,u6:()=>a});var n=r(44194),i=r(23248),o=r(97715);let a=1e3,s={Modal:100,Drawer:100,Popover:100,Popconfirm:100,Tooltip:100,Tour:100,FloatButton:100},l={SelectLike:50,Dropdown:50,DatePicker:50,Menu:50,ImagePreview:1};function u(e){return e in s}let c=(e,t)=>{let r,[,a]=(0,i.ZP)(),c=n.useContext(o.Z),h=u(e);if(void 0!==t)r=[t,t];else{let n=null!=c?c:0;h?n+=(c?0:a.zIndexPopupBase)+s[e]:n+=l[e],r=[void 0===c?t:n,n]}return r}},19150:function(e,t,r){"use strict";r.d(t,{Z:()=>u,m:()=>l});var n=r(97266);let i=()=>({height:0,opacity:0}),o=e=>{let{scrollHeight:t}=e;return{height:t,opacity:1}},a=e=>({height:e?e.offsetHeight:0}),s=(e,t)=>(null==t?void 0:t.deadline)===!0||"height"===t.propertyName,l=(e,t,r)=>void 0!==r?r:`${e}-${t}`,u=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.Rf;return{motionName:`${e}-motion-collapse`,onAppearStart:i,onEnterStart:i,onAppearActive:o,onEnterActive:o,onLeaveStart:a,onLeaveActive:i,onAppearEnd:s,onEnterEnd:s,onLeaveEnd:s,motionDeadline:500}}},19481:function(e,t,r){"use strict";r.d(t,{Z:()=>l});var n=r(79898);function i(e,t,r,n){if(!1===n)return{adjustX:!1,adjustY:!1};let i=n&&"object"==typeof n?n:{},o={};switch(e){case"top":case"bottom":o.shiftX=2*t.arrowOffsetHorizontal+r,o.shiftY=!0,o.adjustY=!0;break;case"left":case"right":o.shiftY=2*t.arrowOffsetVertical+r,o.shiftX=!0,o.adjustX=!0}let a=Object.assign(Object.assign({},o),i);return a.shiftX||(a.adjustX=!0),a.shiftY||(a.adjustY=!0),a}let o={left:{points:["cr","cl"]},right:{points:["cl","cr"]},top:{points:["bc","tc"]},bottom:{points:["tc","bc"]},topLeft:{points:["bl","tl"]},leftTop:{points:["tr","tl"]},topRight:{points:["br","tr"]},rightTop:{points:["tl","tr"]},bottomRight:{points:["tr","br"]},rightBottom:{points:["bl","br"]},bottomLeft:{points:["tl","bl"]},leftBottom:{points:["br","bl"]}},a={topLeft:{points:["bl","tc"]},leftTop:{points:["tr","cl"]},topRight:{points:["br","tc"]},rightTop:{points:["tl","cr"]},bottomRight:{points:["tr","bc"]},rightBottom:{points:["bl","cr"]},bottomLeft:{points:["tl","bc"]},leftBottom:{points:["br","cl"]}},s=new Set(["topLeft","topRight","bottomLeft","bottomRight","leftTop","leftBottom","rightTop","rightBottom"]);function l(e){let{arrowWidth:t,autoAdjustOverflow:r,arrowPointAtCenter:l,offset:u,borderRadius:c,visibleFirst:h}=e,f=t/2,d={};return Object.keys(o).forEach(e=>{let p=Object.assign(Object.assign({},l&&a[e]||o[e]),{offset:[0,0],dynamicInset:!0});switch(d[e]=p,s.has(e)&&(p.autoArrow=!1),e){case"top":case"topLeft":case"topRight":p.offset[1]=-f-u;break;case"bottom":case"bottomLeft":case"bottomRight":p.offset[1]=f+u;break;case"left":case"leftTop":case"leftBottom":p.offset[0]=-f-u;break;case"right":case"rightTop":case"rightBottom":p.offset[0]=f+u}let m=(0,n.wZ)({contentRadius:c,limitVerticalRadius:!0});if(l)switch(e){case"topLeft":case"bottomLeft":p.offset[0]=-m.arrowOffsetHorizontal-f;break;case"topRight":case"bottomRight":p.offset[0]=m.arrowOffsetHorizontal+f;break;case"leftTop":case"rightTop":p.offset[1]=-(2*m.arrowOffsetHorizontal)+f;break;case"leftBottom":case"rightBottom":p.offset[1]=2*m.arrowOffsetHorizontal-f}p.overflow=i(e,m,t,r),h&&(p.htmlRegion="visibleFirst")}),d}},33174:function(e,t,r){"use strict";r.d(t,{M2:()=>i,Tm:()=>a,wm:()=>o});var n=r(44194);function i(e){return e&&n.isValidElement(e)&&e.type===n.Fragment}let o=(e,t,r)=>n.isValidElement(e)?n.cloneElement(e,"function"==typeof r?r(e.props||{}):r):t;function a(e,t){return o(e,e,t)}},28706:function(e,t,r){"use strict";r.d(t,{F:()=>a,Z:()=>o});var n=r(41229),i=r.n(n);function o(e,t,r){return i()({[`${e}-status-success`]:"success"===t,[`${e}-status-warning`]:"warning"===t,[`${e}-status-error`]:"error"===t,[`${e}-status-validating`]:"validating"===t,[`${e}-has-feedback`]:r})}let a=(e,t)=>t||e},24402:function(e,t,r){"use strict";r.d(t,{G8:()=>o,ln:()=>a});var n=r(44194);function i(){}r(28740);let o=n.createContext({}),a=()=>{let e=()=>{};return e.deprecated=i,e}},48142:function(e,t,r){"use strict";r.d(t,{Z:()=>C});var n=r(44194),i=r(41229),o=r.n(i),a=r(19014),s=r(38726),l=r(97266),u=r(33174),c=r(15022);let h=e=>{let{componentCls:t,colorPrimary:r}=e;return{[t]:{position:"absolute",background:"transparent",pointerEvents:"none",boxSizing:"border-box",color:`var(--wave-color, ${r})`,boxShadow:"0 0 0 0 currentcolor",opacity:.2,"&.wave-motion-appear":{transition:`box-shadow 0.4s ${e.motionEaseOutCirc},opacity 2s ${e.motionEaseOutCirc}`,"&-active":{boxShadow:"0 0 0 6px currentcolor",opacity:0},"&.wave-quick":{transition:`box-shadow ${e.motionDurationSlow} ${e.motionEaseInOut},opacity ${e.motionDurationSlow} ${e.motionEaseInOut}`}}}}},f=(0,c.A1)("Wave",e=>[h(e)]);var d=r(81446),p=r(2281),m=r(23248),g=r(85864),y=r(55940),v=r(41309);function b(e){return e&&"#fff"!==e&&"#ffffff"!==e&&"rgb(255, 255, 255)"!==e&&"rgba(255, 255, 255, 1)"!==e&&!/rgba\((?:\d*, ){3}0\)/.test(e)&&"transparent"!==e}function _(e){let{borderTopColor:t,borderColor:r,backgroundColor:n}=getComputedStyle(e);return b(t)?t:b(r)?r:b(n)?n:null}function w(e){return Number.isNaN(e)?0:e}let x=e=>{let{className:t,target:r,component:i}=e,a=n.useRef(null),[l,u]=n.useState(null),[c,h]=n.useState([]),[f,d]=n.useState(0),[m,b]=n.useState(0),[x,S]=n.useState(0),[E,C]=n.useState(0),[A,k]=n.useState(!1),O={left:f,top:m,width:x,height:E,borderRadius:c.map(e=>`${e}px`).join(" ")};function T(){let e=getComputedStyle(r);u(_(r));let t="static"===e.position,{borderLeftWidth:n,borderTopWidth:i}=e;d(t?r.offsetLeft:w(-parseFloat(n))),b(t?r.offsetTop:w(-parseFloat(i))),S(r.offsetWidth),C(r.offsetHeight);let{borderTopLeftRadius:o,borderTopRightRadius:a,borderBottomLeftRadius:s,borderBottomRightRadius:l}=e;h([o,a,l,s].map(e=>w(parseFloat(e))))}if(l&&(O["--wave-color"]=l),n.useEffect(()=>{if(r){let e,t=(0,p.Z)(()=>{T(),k(!0)});return"undefined"!=typeof ResizeObserver&&(e=new ResizeObserver(T)).observe(r),()=>{p.Z.cancel(t),null==e||e.disconnect()}}},[]),!A)return null;let I=("Checkbox"===i||"Radio"===i)&&(null==r?void 0:r.classList.contains(g.A));return n.createElement(y.ZP,{visible:!0,motionAppear:!0,motionName:"wave-motion",motionDeadline:5e3,onAppearEnd:(e,t)=>{var r;if(t.deadline||"opacity"===t.propertyName){let e=null==(r=a.current)?void 0:r.parentElement;(0,v.v)(e).then(()=>{null==e||e.remove()})}return!1}},(e,r)=>{let{className:i}=e;return n.createElement("div",{ref:(0,s.sQ)(a,r),className:o()(t,i,{"wave-quick":I}),style:O})})},S=(e,t)=>{var r;let{component:i}=t;if("Checkbox"===i&&!(null==(r=e.querySelector("input"))?void 0:r.checked))return;let o=document.createElement("div");o.style.position="absolute",o.style.left="0px",o.style.top="0px",null==e||e.insertBefore(o,null==e?void 0:e.firstChild),(0,v.s)(n.createElement(x,Object.assign({},t,{target:e})),o)},E=(e,t,r)=>{let{wave:i}=n.useContext(l.E_),[,o,a]=(0,m.ZP)(),s=(0,d.Z)(n=>{let s=e.current;if((null==i?void 0:i.disabled)||!s)return;let l=s.querySelector(`.${g.A}`)||s,{showEffect:u}=i||{};(u||S)(l,{className:t,token:o,component:r,event:n,hashId:a})}),u=n.useRef();return e=>{p.Z.cancel(u.current),u.current=(0,p.Z)(()=>{s(e)})}},C=e=>{let{children:t,disabled:r,component:i}=e,{getPrefixCls:c}=(0,n.useContext)(l.E_),h=(0,n.useRef)(null),d=c("wave"),[,p]=f(d),m=E(h,o()(d,p),i);if(n.useEffect(()=>{let e=h.current;if(!e||1!==e.nodeType||r)return;let t=t=>{!(0,a.Z)(t.target)||!e.getAttribute||e.getAttribute("disabled")||e.disabled||e.className.includes("disabled")||e.className.includes("-leave")||m(t)};return e.addEventListener("click",t,!0),()=>{e.removeEventListener("click",t,!0)}},[r]),!n.isValidElement(t))return null!=t?t:null;let g=(0,s.Yr)(t)?(0,s.sQ)(t.ref,h):h;return(0,u.Tm)(t,{ref:g})}},85864:function(e,t,r){"use strict";r.d(t,{A:()=>i});var n=r(97266);let i=`${n.Rf}-wave-target`},97715:function(e,t,r){"use strict";r.d(t,{Z:()=>n});let n=r(44194).createContext(void 0)},99598:function(e,t,r){"use strict";r.d(t,{Z:()=>F});var n=r(44194),i=r(4007),o=r(55655),a=r(32110),s=r(73654),l=r(24452),u=r(41229),c=r.n(u),h=r(55940),f=r(24758),d=r(38726),p=r(33174),m=r(97266),g=r(99607),y=r(46324),v=r(15022);let b=(e,t,r,n,i)=>({background:e,border:`${(0,g.bf)(n.lineWidth)} ${n.lineType} ${t}`,[`${i}-icon`]:{color:r}}),_=e=>{let{componentCls:t,motionDurationSlow:r,marginXS:n,marginSM:i,fontSize:o,fontSizeLG:a,lineHeight:s,borderRadiusLG:l,motionEaseInOutCirc:u,withDescriptionIconSize:c,colorText:h,colorTextHeading:f,withDescriptionPadding:d,defaultPadding:p}=e;return{[t]:Object.assign(Object.assign({},(0,y.Wf)(e)),{position:"relative",display:"flex",alignItems:"center",padding:p,wordWrap:"break-word",borderRadius:l,[`&${t}-rtl`]:{direction:"rtl"},[`${t}-content`]:{flex:1,minWidth:0},[`${t}-icon`]:{marginInlineEnd:n,lineHeight:0},"&-description":{display:"none",fontSize:o,lineHeight:s},"&-message":{color:f},[`&${t}-motion-leave`]:{overflow:"hidden",opacity:1,transition:`max-height ${r} ${u}, opacity ${r} ${u},
@@ -234,51 +234,51 @@ Right ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Arra
234
234
  Left ${e}
235
235
  Right ${t}`)}class h extends s{}function f(e){return"string"==typeof e.role}function d(e){return"function"==typeof e?._getType}},65711:function(e,t,r){"use strict";r.d(t,{J:()=>i});var n=r(44441);class i extends n.ku{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return i}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return"generic"===e._getType()}get _printableFields(){return{...super._printableFields,role:this.role}}}class o extends n.$k{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new o({content:(0,n.Wf)(this.content,e.content),additional_kwargs:(0,n.wv)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.wv)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}},47301:function(e,t,r){"use strict";r(44441).ku},14849:function(e,t,r){"use strict";r.d(t,{xk:()=>i});var n=r(44441);class i extends n.ku{static lc_name(){return"HumanMessage"}_getType(){return"human"}}},53951:function(e,t,r){"use strict";r.d(t,{jN:()=>i});var n=r(44441);class i extends n.ku{static lc_name(){return"SystemMessage"}_getType(){return"system"}}},85077:function(e,t,r){"use strict";r.d(t,{Cq:()=>i,jC:()=>a});var n=r(44441);class i extends n.ku{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class o extends n.$k{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new o({content:(0,n.Wf)(this.content,e.content),additional_kwargs:(0,n.wv)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.wv)(this.response_metadata,e.response_metadata),artifact:(0,n.x)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,n.n4)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function a(e){let t=[],r=[];for(let n of e)if(!n.function)continue;else{let e=n.function.name;try{let r=JSON.parse(n.function.arguments),i={name:e||"",args:r||{},id:n.id};t.push(i)}catch(t){r.push({name:e,args:n.function.arguments,id:n.id,error:"Malformed args."})}}return[t,r]}},16769:function(e,t,r){"use strict";r.d(t,{E1:()=>d,zs:()=>p});var n=r(12024),i=r(71033),o=r(37149),a=r(44441);r(65711),r(47301);var s=r(14849),l=r(53951),u=r(85077);function c(e){return(0,i.u)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function h(e){return"object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs}function f(e){let t,r;if(h(e)){let n=e.id.at(-1);t="HumanMessage"===n||"HumanMessageChunk"===n?"user":"AIMessage"===n||"AIMessageChunk"===n?"assistant":"SystemMessage"===n||"SystemMessageChunk"===n?"system":"unknown",r=e.kwargs}else{let{type:n,...i}=e;t=n,r=i}if("human"===t||"user"===t)return new s.xk(r);if("ai"===t||"assistant"===t){let{tool_calls:e,...t}=r;if(!Array.isArray(e))return new o.gY(r);let n=e.map(c);return new o.gY({...t,tool_calls:n})}if("system"===t)return new l.jN(r);if("developer"===t)return new l.jN({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new u.Cq({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});throw(0,n.r)(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
236
236
 
237
- Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function d(e){if("string"==typeof e)return new s.xk(e);if((0,a.QW)(e))return e;if(Array.isArray(e)){let[t,r]=e;return f({type:t,content:r})}if(!(0,a.gQ)(e))return f(e);{let{role:t,...r}=e;return f({...r,type:t})}}function p(e,t="Human",r="AI"){let n=[];for(let i of e){let e;if("human"===i._getType())e=t;else if("ai"===i._getType())e=r;else if("system"===i._getType())e="System";else if("function"===i._getType())e="Function";else if("tool"===i._getType())e="Tool";else if("generic"===i._getType())e=i.role;else throw Error(`Got unsupported message type: ${i._getType()}`);let o=i.name?`${i.name}, `:"",a="string"==typeof i.content?i.content:JSON.stringify(i.content,null,2);n.push(`${e}: ${o}${a}`)}return n.join("\n")}},16069:function(e,t,r){"use strict";r.d(t,{GU:()=>l,Nn:()=>u,nw:()=>s});var n=r(59975),i=r(14849),o=r(16769);class a extends n.i{}class s extends a{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new i.xk(this.value)]}}class l extends a{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return(0,o.zs)(this.messages)}toChatMessages(){return this.messages}}class u extends a{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new i.xk({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}},70505:function(e,t,r){"use strict";r.d(t,{d:()=>i});var n=r(70682);class i extends n.eq{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{inputVariables:t}=e;if(t.includes("stop"))throw Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[e,n]of Object.entries(t))"string"==typeof n?r[e]=n:r[e]=await n();return{...r,...e}}async invoke(e,t){return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,runType:"prompt"})}serialize(){throw Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,34367));return t.deserialize(e)}case void 0:{let{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,34367));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:t}=await Promise.resolve().then(r.bind(r,63882));return t.deserialize(e)}default:throw Error(`Invalid prompt type in config: ${e._type}`)}}}},18524:function(e,t,r){"use strict";r.d(t,{ks:()=>T,S:()=>_});var n=r(37149),i=r(44441),o=r(65711);r(47301);var a=r(14849),s=r(53951),l=r(16769),u=r(70682);i.ku,r(85077);var c=r(16069),h=r(88357),f=r(70505),d=r(34367),p=r(35304),m=r(82188),g=r(12024);class y extends u.eq{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:"prompt"})}}class v extends y{static lc_name(){return"MessagesPlaceholder"}constructor(e){"string"==typeof e&&(e={variableName:e}),super(e),Object.defineProperty(this,"variableName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optional",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t,r=e[this.variableName];if(this.optional&&!r)return[];if(!r){let e=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name="InputFormatError",e}try{t=Array.isArray(r)?r.map(l.E1):[(0,l.E1)(r)]}catch(n){let e="string"==typeof r?r:JSON.stringify(r,null,2),t=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.
237
+ Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function d(e){if("string"==typeof e)return new s.xk(e);if((0,a.QW)(e))return e;if(Array.isArray(e)){let[t,r]=e;return f({type:t,content:r})}if(!(0,a.gQ)(e))return f(e);{let{role:t,...r}=e;return f({...r,type:t})}}function p(e,t="Human",r="AI"){let n=[];for(let i of e){let e;if("human"===i._getType())e=t;else if("ai"===i._getType())e=r;else if("system"===i._getType())e="System";else if("function"===i._getType())e="Function";else if("tool"===i._getType())e="Tool";else if("generic"===i._getType())e=i.role;else throw Error(`Got unsupported message type: ${i._getType()}`);let o=i.name?`${i.name}, `:"",a="string"==typeof i.content?i.content:JSON.stringify(i.content,null,2);n.push(`${e}: ${o}${a}`)}return n.join("\n")}},16069:function(e,t,r){"use strict";r.d(t,{GU:()=>l,Nn:()=>u,nw:()=>s});var n=r(59975),i=r(14849),o=r(16769);class a extends n.i{}class s extends a{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new i.xk(this.value)]}}class l extends a{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return(0,o.zs)(this.messages)}toChatMessages(){return this.messages}}class u extends a{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new i.xk({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}},70505:function(e,t,r){"use strict";r.d(t,{d:()=>i});var n=r(79097);class i extends n.eq{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{inputVariables:t}=e;if(t.includes("stop"))throw Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[e,n]of Object.entries(t))"string"==typeof n?r[e]=n:r[e]=await n();return{...r,...e}}async invoke(e,t){return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,runType:"prompt"})}serialize(){throw Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,34367));return t.deserialize(e)}case void 0:{let{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,34367));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:t}=await Promise.resolve().then(r.bind(r,63882));return t.deserialize(e)}default:throw Error(`Invalid prompt type in config: ${e._type}`)}}}},18524:function(e,t,r){"use strict";r.d(t,{ks:()=>T,S:()=>_});var n=r(37149),i=r(44441),o=r(65711);r(47301);var a=r(14849),s=r(53951),l=r(16769),u=r(79097);i.ku,r(85077);var c=r(16069),h=r(88357),f=r(70505),d=r(34367),p=r(35304),m=r(82188),g=r(12024);class y extends u.eq{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:"prompt"})}}class v extends y{static lc_name(){return"MessagesPlaceholder"}constructor(e){"string"==typeof e&&(e={variableName:e}),super(e),Object.defineProperty(this,"variableName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optional",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t,r=e[this.variableName];if(this.optional&&!r)return[];if(!r){let e=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name="InputFormatError",e}try{t=Array.isArray(r)?r.map(l.E1):[(0,l.E1)(r)]}catch(n){let e="string"==typeof r?r:JSON.stringify(r,null,2),t=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.
238
238
 
239
239
  Received value: ${e}
240
240
 
241
241
  Additional message: ${n.message}`);throw t.name="InputFormatError",t.lc_error_code=n.lc_error_code,t}return t}}class b extends y{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}}class _ extends f.d{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let t=await this.formatMessages(e);return new c.GU(t)}}class w extends b{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new o.J(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(d.PromptTemplate.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}}class x extends y{static _messageClass(){throw Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach(t=>{"inputVariables"in t&&(e=e.concat(t.inputVariables))}),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}throw Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw Error("Invalid message class name")}}static fromTemplate(e,t){if("string"==typeof e)return new this(d.PromptTemplate.fromTemplate(e,t));let r=[];for(let n of e)if("string"==typeof n||"object"==typeof n&&"text"in n){let e="";"string"==typeof n?e=n:"string"==typeof n.text&&(e=n.text??"");let i={...t,..."string"!=typeof n?{additionalContentFields:n}:{}};r.push(d.PromptTemplate.fromTemplate(e,i))}else if("object"==typeof n&&"image_url"in n){let e,i=n.image_url??"",o=[];if("string"==typeof i){let r,a=(r=t?.templateFormat==="mustache"?(0,m.PZ)(i):(0,m._O)(i)).flatMap(e=>"variable"===e.type?[e.name]:[]);if((a?.length??0)>0){if(a.length>1)throw Error(`Only one format variable allowed per image template.
242
242
  Got: ${a}
243
243
  From: ${i}`);o=[a[0]]}else o=[];i={url:i},e=new p.r({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else if("object"==typeof i){if("url"in i){let e;o=(e=t?.templateFormat==="mustache"?(0,m.PZ)(i.url):(0,m._O)(i.url)).flatMap(e=>"variable"===e.type?[e.name]:[])}else o=[];e=new p.r({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw Error("Invalid image template");r.push(e)}return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof h.A){let t=await this.prompt.format(e);return this.createMessage(t)}{let t=[];for(let r of this.prompt){let n={};if(!("inputVariables"in r))throw Error(`Prompt ${r} does not have inputVariables defined.`);for(let t of r.inputVariables)n||(n={[t]:e[t]}),n={...n,[t]:e[t]};if(r instanceof h.A){let e,i=await r.format(n);"additionalContentFields"in r&&(e=r.additionalContentFields),t.push({...e,type:"text",text:i})}else if(r instanceof p.r){let e,i=await r.format(n);"additionalContentFields"in r&&(e=r.additionalContentFields),t.push({...e,type:"image_url",image_url:i})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}}class S extends x{static _messageClass(){return a.xk}static lc_name(){return"HumanMessagePromptTemplate"}}class E extends x{static _messageClass(){return n.gY}static lc_name(){return"AIMessagePromptTemplate"}}class C extends x{static _messageClass(){return s.jN}static lc_name(){return"SystemMessagePromptTemplate"}}function A(e){return"function"==typeof e.formatMessages}function k(e,t){let r;if(A(e)||(0,i.QW)(e))return e;if(Array.isArray(e)&&"placeholder"===e[0]){let t=e[1];if("string"!=typeof t||"{"!==t[0]||"}"!==t[t.length-1])throw Error(`Invalid placeholder template: "${e[1]}". Expected a variable name surrounded by curly braces.`);return new v({variableName:t.slice(1,-1),optional:!0})}let n=(0,l.E1)(e);if(r="string"==typeof n.content?n.content:n.content.map(e=>"text"in e?{...e,text:e.text}:"image_url"in e?{...e,image_url:e.image_url}:e),"human"===n._getType())return S.fromTemplate(r,t);if("ai"===n._getType())return E.fromTemplate(r,t);if("system"===n._getType())return C.fromTemplate(r,t);if(o.J.isInstance(n))return w.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function O(e){return"MessagesPlaceholder"===e.constructor.lc_name()}class T extends _{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let e=new Set;for(let t of this.promptMessages)if(!(t instanceof i.ku))for(let r of t.inputVariables)e.add(r);let t=this.inputVariables,r=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),n=new Set([...r].filter(t=>!e.has(t)));if(n.size>0)throw Error(`Input variables \`${[...n]}\` are not used in any of the prompt messages.`);let o=new Set([...e].filter(e=>!r.has(e)));if(o.size>0)throw Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,t){if("string"==typeof e.content)return e;let r=await Promise.all(e.content.map(async e=>{if("image_url"!==e.type)return e;let r="";r="string"==typeof e.image_url?e.image_url:e.image_url.url;let n=d.PromptTemplate.fromTemplate(r,{templateFormat:this.templateFormat}),i=await n.format(t);return"string"!=typeof e.image_url&&"url"in e.image_url?e.image_url.url=i:e.image_url=i,e}));return e.content=r,e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),r=[];for(let e of this.promptMessages)if(e instanceof i.ku)r.push(await this._parseImagePrompts(e,t));else{let n=e.inputVariables.reduce((r,n)=>{if(!(n in t)&&!(O(e)&&e.optional))throw(0,g.r)(Error(`Missing value for input variable \`${n.toString()}\``),"INVALID_PROMPT_INPUT");return r[n]=t[n],r},{}),i=await e.formatMessages(n);r=r.concat(i)}return r}async partial(e){let t=this.inputVariables.filter(t=>!(t in e)),r={...this.partialVariables??{},...e};return new T({...this,inputVariables:t,partialVariables:r})}static fromTemplate(e,t){let r=new S({prompt:d.PromptTemplate.fromTemplate(e,t)});return this.fromMessages([r])}static fromMessages(e,t){let r=e.reduce((e,r)=>e.concat(r instanceof T?r.promptMessages:[k(r,t)]),[]),n=e.reduce((e,t)=>t instanceof T?Object.assign(e,t.partialVariables):e,Object.create(null)),o=new Set;for(let e of r)if(!(e instanceof i.ku))for(let t of e.inputVariables)t in n||o.add(t);return new this({...t,inputVariables:[...o],promptMessages:r,partialVariables:n,templateFormat:t?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}},63882:function(e,t,r){"use strict";r.d(t,{FewShotPromptTemplate:()=>s});var n=r(88357),i=r(82188),o=r(34367),a=r(18524);class s extends n.A{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),void 0!==this.examples&&void 0!==this.exampleSelector)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,i.af)(this.prefix+this.suffix,this.templateFormat,e)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let t=this.inputVariables.filter(t=>!(t in e)),r={...this.partialVariables??{},...e};return new s({...this,inputVariables:t,partialVariables:r})}async format(e){let t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=await Promise.all(r.map(e=>this.examplePrompt.format(e))),o=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,i.SM)(o,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw Error("Serializing an example selector is not currently supported");if(void 0!==this.outputParser)throw Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){let t,{example_prompt:r}=e;if(!r)throw Error("Missing example prompt");let n=await o.PromptTemplate.deserialize(r);if(Array.isArray(e.examples))t=e.examples;else throw Error("Invalid examples format. Only list or string are supported.");return new s({inputVariables:e.input_variables,examplePrompt:n,examples:t,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}}class l extends a.S{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??"\n\n",this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,void 0!==this.examples&&void 0!==this.exampleSelector)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,i.af)(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t);r=r.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(r=>{t[r]=e[r]}),t});let n=[];for(let e of r){let t=await this.examplePrompt.formatMessages(e);n.push(...t)}return n}async format(e){let t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=(await Promise.all(r.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content),o=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,i.SM)(o,this.templateFormat,t)}async partial(e){let t=this.inputVariables.filter(t=>!(t in e)),r={...this.partialVariables??{},...e};return new l({...this,inputVariables:t,partialVariables:r})}}},35304:function(e,t,r){"use strict";r.d(t,{r:()=>a});var n=r(16069),i=r(70505),o=r(82188);class a extends i.d{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,o.af)([{type:"image_url",image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return"prompt"}async partial(e){let t=this.inputVariables.filter(t=>!(t in e)),r={...this.partialVariables??{},...e};return new a({...this,inputVariables:t,partialVariables:r})}async format(e){let t={};for(let[r,n]of Object.entries(this.template))"string"==typeof n?t[r]=(0,o.SM)(n,this.templateFormat,e):t[r]=n;let r=e.url||t.url,n=e.detail||t.detail;if(!r)throw Error("Must provide either an image URL.");if("string"!=typeof r)throw Error("url must be a string.");let i={url:r};return n&&(i.detail=n),i}async formatPromptValue(e){let t=await this.format(e);return new n.Nn(t)}}},34367:function(e,t,r){"use strict";r.d(t,{PromptTemplate:()=>o});var n=r(88357),i=r(82188);class o extends n.A{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if("mustache"===this.templateFormat)throw Error("Mustache templates cannot be validated.");let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,i.af)(this.template,this.templateFormat,e)}}_getPromptType(){return"prompt"}async format(e){let t=await this.mergePartialAndUserVariables(e);return(0,i.SM)(this.template,this.templateFormat,t)}static fromExamples(e,t,r,n="\n\n",i=""){return new o({inputVariables:r,template:[i,...e,t].join(n)})}static fromTemplate(e,t){let{templateFormat:r="f-string",...n}=t??{},a=new Set;return(0,i.$M)(e,r).forEach(e=>{"variable"===e.type&&a.add(e.name)}),new o({inputVariables:[...a],templateFormat:r,template:e,...n})}async partial(e){let t=this.inputVariables.filter(t=>!(t in e)),r={...this.partialVariables??{},...e};return new o({...this,inputVariables:t,partialVariables:r})}serialize(){if(void 0!==this.outputParser)throw Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw Error("Prompt template must have a template");return new o({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}},88357:function(e,t,r){"use strict";r.d(t,{A:()=>o});var n=r(16069),i=r(70505);class o extends i.d{async formatPromptValue(e){let t=await this.format(e);return new n.nw(t)}}},82188:function(e,t,r){"use strict";r.d(t,{af:()=>F,_O:()=>R,$M:()=>L,SM:()=>B,PZ:()=>$});var n=Object.prototype.toString,i=Array.isArray||function(e){return"[object Array]"===n.call(e)};function o(e){return"function"==typeof e}function a(e){return i(e)?"array":typeof e}function s(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function l(e,t){return null!=e&&"object"==typeof e&&t in e}function u(e,t){return null!=e&&"object"!=typeof e&&e.hasOwnProperty&&e.hasOwnProperty(t)}var c=RegExp.prototype.test;function h(e,t){return c.call(e,t)}var f=/\S/;function d(e){return!h(f,e)}var p={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function m(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return p[e]})}var g=/\s*/,y=/\s+/,v=/\s*=/,b=/\s*\}/,_=/#|\^|\/|>|\{|&|=|!/;function w(e,t){if(!e)return[];var r,n,o,a,l,u,c,h,f,p=!1,m=[],w=[],C=[],A=!1,O=!1,T="",I=0;function P(){if(A&&!O)for(;C.length;)delete w[C.pop()];else C=[];A=!1,O=!1}function R(e){if("string"==typeof e&&(e=e.split(y,2)),!i(e)||2!==e.length)throw Error("Invalid tags: "+e);r=RegExp(s(e[0])+"\\s*"),n=RegExp("\\s*"+s(e[1])),o=RegExp("\\s*"+s("}"+e[1]))}R(t||k.tags);for(var M=new E(e);!M.eos();){if(a=M.pos,u=M.scanUntil(r))for(var $=0,N=u.length;$<N;++$)d(c=u.charAt($))?(C.push(w.length),T+=c):(O=!0,p=!0,T+=" "),w.push(["text",c,a,a+1]),a+=1,"\n"===c&&(P(),T="",I=0,p=!1);if(!M.scan(r))break;if(A=!0,l=M.scan(_)||"name",M.scan(g),"="===l?(u=M.scanUntil(v),M.scan(v),M.scanUntil(n)):"{"===l?(u=M.scanUntil(o),M.scan(b),M.scanUntil(n),l="&"):u=M.scanUntil(n),!M.scan(n))throw Error("Unclosed tag at "+M.pos);if(h=">"==l?[l,u,a,M.pos,T,I,p]:[l,u,a,M.pos],I++,w.push(h),"#"===l||"^"===l)m.push(h);else if("/"===l){if(!(f=m.pop()))throw Error('Unopened section "'+u+'" at '+a);if(f[1]!==u)throw Error('Unclosed section "'+f[1]+'" at '+a)}else"name"===l||"{"===l||"&"===l?O=!0:"="===l&&R(u)}if(P(),f=m.pop())throw Error('Unclosed section "'+f[1]+'" at '+M.pos);return S(x(w))}function x(e){for(var t,r,n=[],i=0,o=e.length;i<o;++i)(t=e[i])&&("text"===t[0]&&r&&"text"===r[0]?(r[1]+=t[1],r[3]=t[3]):(n.push(t),r=t));return n}function S(e){for(var t,r=[],n=r,i=[],o=0,a=e.length;o<a;++o)switch((t=e[o])[0]){case"#":case"^":n.push(t),i.push(t),n=t[4]=[];break;case"/":i.pop()[5]=t[2],n=i.length>0?i[i.length-1][4]:r;break;default:n.push(t)}return r}function E(e){this.string=e,this.tail=e,this.pos=0}function C(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function A(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}E.prototype.eos=function(){return""===this.tail},E.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},E.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case -1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=t.length,t},C.prototype.push=function(e){return new C(e,this)},C.prototype.lookup=function(e){var t=this.cache;if(t.hasOwnProperty(e))r=t[e];else{for(var r,n,i,a,s=this,c=!1;s;){if(e.indexOf(".")>0)for(n=s.view,i=e.split("."),a=0;null!=n&&a<i.length;)a===i.length-1&&(c=l(n,i[a])||u(n,i[a])),n=n[i[a++]];else n=s.view[e],c=l(s.view,e);if(c){r=n;break}s=s.parent}t[e]=r}return o(r)&&(r=r.call(this.view)),r},A.prototype.clearCache=function(){void 0!==this.templateCache&&this.templateCache.clear()},A.prototype.parse=function(e,t){var r=this.templateCache,n=e+":"+(t||k.tags).join(":"),i=void 0!==r,o=i?r.get(n):void 0;return void 0==o&&(o=w(e,t),i&&r.set(n,o)),o},A.prototype.render=function(e,t,r,n){var i=this.getConfigTags(n),o=this.parse(e,i),a=t instanceof C?t:new C(t,void 0);return this.renderTokens(o,a,r,e,n)},A.prototype.renderTokens=function(e,t,r,n,i){for(var o,a,s,l="",u=0,c=e.length;u<c;++u)s=void 0,"#"===(a=(o=e[u])[0])?s=this.renderSection(o,t,r,n,i):"^"===a?s=this.renderInverted(o,t,r,n,i):">"===a?s=this.renderPartial(o,t,r,i):"&"===a?s=this.unescapedValue(o,t):"name"===a?s=this.escapedValue(o,t,i):"text"===a&&(s=this.rawValue(o)),void 0!==s&&(l+=s);return l},A.prototype.renderSection=function(e,t,r,n,a){var s=this,l="",u=t.lookup(e[1]);function c(e){return s.render(e,t,r,a)}if(u){if(i(u))for(var h=0,f=u.length;h<f;++h)l+=this.renderTokens(e[4],t.push(u[h]),r,n,a);else if("object"==typeof u||"string"==typeof u||"number"==typeof u)l+=this.renderTokens(e[4],t.push(u),r,n,a);else if(o(u)){if("string"!=typeof n)throw Error("Cannot use higher-order sections without the original template");null!=(u=u.call(t.view,n.slice(e[3],e[5]),c))&&(l+=u)}else l+=this.renderTokens(e[4],t,r,n,a);return l}},A.prototype.renderInverted=function(e,t,r,n,o){var a=t.lookup(e[1]);if(!a||i(a)&&0===a.length)return this.renderTokens(e[4],t,r,n,o)},A.prototype.indentPartial=function(e,t,r){for(var n=t.replace(/[^ \t]/g,""),i=e.split("\n"),o=0;o<i.length;o++)i[o].length&&(o>0||!r)&&(i[o]=n+i[o]);return i.join("\n")},A.prototype.renderPartial=function(e,t,r,n){if(r){var i=this.getConfigTags(n),a=o(r)?r(e[1]):r[e[1]];if(null!=a){var s=e[6],l=e[5],u=e[4],c=a;0==l&&u&&(c=this.indentPartial(a,u,s));var h=this.parse(c,i);return this.renderTokens(h,t,r,c,n)}}},A.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},A.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||k.escape,i=t.lookup(e[1]);if(null!=i)return"number"==typeof i&&n===k.escape?String(i):n(i)},A.prototype.rawValue=function(e){return e[1]},A.prototype.getConfigTags=function(e){return i(e)?e:e&&"object"==typeof e?e.tags:void 0},A.prototype.getConfigEscape=function(e){return e&&"object"==typeof e&&!i(e)?e.escape:void 0};var k={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){O.templateCache=cache},get templateCache(){return O.templateCache}},O=new A;k.clearCache=function(){return O.clearCache()},k.parse=function(e,t){return O.parse(e,t)},k.render=function(e,t,r,n){if("string"!=typeof e)throw TypeError('Invalid template! Template should be a "string" but "'+a(e)+'" was given as the first argument for mustache#render(template, view, partials)');return O.render(e,t,r,n)},k.escape=m,k.Scanner=E,k.Context=C,k.Writer=A;let T=k;var I=r(12024);function P(){T.escape=e=>e}let R=e=>{let t=e.split(""),r=[],n=(e,r)=>{for(let n=r;n<t.length;n+=1)if(e.includes(t[n]))return n;return -1},i=0;for(;i<t.length;)if("{"===t[i]&&i+1<t.length&&"{"===t[i+1])r.push({type:"literal",text:"{"}),i+=2;else if("}"===t[i]&&i+1<t.length&&"}"===t[i+1])r.push({type:"literal",text:"}"}),i+=2;else if("{"===t[i]){let e=n("}",i);if(e<0)throw Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(i+1,e).join("")}),i=e+1}else if("}"===t[i])throw Error("Single '}' in template.");else{let e=n("{}",i),o=(e<0?t.slice(i):t.slice(i,e)).join("");r.push({type:"literal",text:o}),i=e<0?t.length:e}return r},M=e=>e.map(e=>"name"===e[0]?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]}),$=e=>(P(),M(T.parse(e))),N={"f-string":(e,t)=>R(e).reduce((e,r)=>{if("variable"===r.type){if(r.name in t)return e+("string"==typeof t[r.name]?t[r.name]:JSON.stringify(t[r.name]));throw Error(`(f-string) Missing value for input ${r.name}`)}return e+r.text},""),mustache:(e,t)=>(P(),T.render(e,t))},j={"f-string":R,mustache:$},B=(e,t,r)=>{try{return N[t](e,r)}catch(e){throw(0,I.r)(e,"INVALID_PROMPT_INPUT")}},L=(e,t)=>j[t](e),F=(e,t,r)=>{if(!(t in N)){let e=Object.keys(N);throw Error(`Invalid template format. Got \`${t}\`;
244
- should be one of ${e}`)}try{let n=r.reduce((e,t)=>(e[t]="foo",e),{});Array.isArray(e)?e.forEach(e=>{if("text"===e.type)B(e.text,t,n);else if("image_url"===e.type)if("string"==typeof e.image_url)B(e.image_url,t,n);else{let r=e.image_url.url;B(r,t,n)}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):B(e,t,n)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}}},70682:function(e,t,r){"use strict";let n,i,o,a,s,l,u,c;r.d(t,{eq:()=>oC});var h,f,d,p,m,g,y={};r.r(y),r.d(y,{JsonPatchError:()=>rX,_areEquals:()=>r4,applyOperation:()=>r0,applyPatch:()=>r1,applyReducer:()=>r2,deepClone:()=>rY,getValueByPointer:()=>rQ,validate:()=>r5,validator:()=>r3}),function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(let e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(h||(h={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(f||(f={}));let v=h.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),b=e=>{switch(typeof e){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(e)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":if(Array.isArray(e))return v.array;if(null===e)return v.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return v.promise;if("undefined"!=typeof Map&&e instanceof Map)return v.map;if("undefined"!=typeof Set&&e instanceof Set)return v.set;if("undefined"!=typeof Date&&e instanceof Date)return v.date;return v.object;default:return v.unknown}},_=h.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"]),w=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class x extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){let r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof x))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,h.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}x.create=e=>new x(e);let S=(e,t)=>{let r;switch(e.code){case _.invalid_type:r=e.received===v.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case _.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,h.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:r=`Unrecognized key(s) in object: ${h.joinValues(e.keys,", ")}`;break;case _.invalid_union:r="Invalid input";break;case _.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${h.joinValues(e.options)}`;break;case _.invalid_enum_value:r=`Invalid enum value. Expected ${h.joinValues(e.options)}, received '${e.received}'`;break;case _.invalid_arguments:r="Invalid function arguments";break;case _.invalid_return_type:r="Invalid function return type";break;case _.invalid_date:r="Invalid date";break;case _.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(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}"`:h.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case _.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case _.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case _.custom:r="Invalid input";break;case _.invalid_intersection_types:r="Intersection results could not be merged";break;case _.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case _.not_finite:r="Number must be finite";break;default:r=t.defaultError,h.assertNever(e)}return{message:r}},E=S;function C(e){E=e}function A(){return E}let k=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(void 0!==i.message)return{...i,path:o,message:i.message};let s="";for(let e of n.filter(e=>!!e).slice().reverse())s=e(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}},O=[];function T(e,t){let r=A(),n=k({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===S?void 0:S].filter(e=>!!e)});e.common.issues.push(n)}class I{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if("aborted"===n.status)return P;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return I.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:t,value:i}=n;if("aborted"===t.status||"aborted"===i.status)return P;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||n.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let P=Object.freeze({status:"aborted"}),R=e=>({status:"dirty",value:e}),M=e=>({status:"valid",value:e}),$=e=>"aborted"===e.status,N=e=>"dirty"===e.status,j=e=>"valid"===e.status,B=e=>"undefined"!=typeof Promise&&e instanceof Promise;function L(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function F(e,t,r,n,i){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r}"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(d||(d={}));class D{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let z=(e,t)=>{if(j(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new x(e.common.issues);return this._error=t,this._error}}};function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{var o,a;let{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:i.defaultError}:void 0===i.data?{message:null!=(o=null!=s?s:n)?o:i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:null!=(a=null!=s?s:r)?a:i.defaultError}},description:i}}class Z{get description(){return this._def.description}_getType(e){return b(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:b(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:b(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(B(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let n={common:{issues:[],async:null!=(r=null==t?void 0:t.async)&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)},i=this._parseSync({data:e,path:n.path,parent:n});return z(n,i)}"~validate"(e){var t,r;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)};if(!this["~standard"].async)try{let t=this._parseSync({data:e,path:[],parent:n});return j(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null==(r=null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(e=>j(e)?{value:e.value}:{issues:n.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)},n=this._parse({data:e,path:r.path,parent:r});return z(r,await (B(n)?n:Promise.resolve(n)))}refine(e,t){let r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{let i=e(t),o=()=>n.addIssue({code:_.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(o(),!1)):!!i||(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new eG({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eW.create(this,this._def)}nullable(){return eq.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return eA.create(this)}promise(){return eH.create(this,this._def)}or(e){return eT.create([this,e],this._def)}and(e){return eM.create(this,e,this._def)}transform(e){return new eG({...U(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t="function"==typeof e?e:()=>e;return new eV({...U(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new eJ({typeName:g.ZodBranded,type:this,...U(this._def)})}catch(e){let t="function"==typeof e?e:()=>e;return new eX({...U(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eQ.create(this,e)}readonly(){return e0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let H=/^c[^\s-]{8,}$/i,G=/^[0-9a-z]+$/,W=/^[0-9A-HJKMNP-TV-Z]{26}$/i,q=/^[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,V=/^[a-z0-9_-]{21}$/i,X=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Y=/^[-+]?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)?)??$/,K=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Q=/^(?:(?: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])$/,ee=/^(?:(?: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])$/,et=/^(([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]))$/,er=/^(([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])$/,en=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ei=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eo="((\\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])))",ea=RegExp(`^${eo}$`);function es(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function el(e){return RegExp(`^${es(e)}$`)}function eu(e){let t=`${eo}T${es(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)}function ec(e,t){return!!(("v4"===t||!t)&&Q.test(e)||("v6"===t||!t)&&et.test(e))}function eh(e,t){if(!X.test(e))return!1;try{let[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));if("object"!=typeof i||null===i||!i.typ||!i.alg||t&&i.alg!==t)return!1;return!0}catch(e){return!1}}function ef(e,t){return!!(("v4"===t||!t)&&ee.test(e)||("v6"===t||!t)&&er.test(e))}class ed extends Z{_parse(e){let t;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.string,received:t.parsedType}),P}let r=new I;for(let i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("max"===i.kind)e.data.length>i.value&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("length"===i.kind){let n=e.data.length>i.value,o=e.data.length<i.value;(n||o)&&(t=this._getOrReturnCtx(e,t),n?T(t,{code:_.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&T(t,{code:_.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if("email"===i.kind)K.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"email",code:_.invalid_string,message:i.message}),r.dirty());else if("emoji"===i.kind)n||(n=RegExp(J,"u")),n.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"emoji",code:_.invalid_string,message:i.message}),r.dirty());else if("uuid"===i.kind)q.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"uuid",code:_.invalid_string,message:i.message}),r.dirty());else if("nanoid"===i.kind)V.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"nanoid",code:_.invalid_string,message:i.message}),r.dirty());else if("cuid"===i.kind)H.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"cuid",code:_.invalid_string,message:i.message}),r.dirty());else if("cuid2"===i.kind)G.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"cuid2",code:_.invalid_string,message:i.message}),r.dirty());else if("ulid"===i.kind)W.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"ulid",code:_.invalid_string,message:i.message}),r.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(n){T(t=this._getOrReturnCtx(e,t),{validation:"url",code:_.invalid_string,message:i.message}),r.dirty()}else"regex"===i.kind?(i.regex.lastIndex=0,i.regex.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"regex",code:_.invalid_string,message:i.message}),r.dirty())):"trim"===i.kind?e.data=e.data.trim():"includes"===i.kind?e.data.includes(i.value,i.position)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):"toLowerCase"===i.kind?e.data=e.data.toLowerCase():"toUpperCase"===i.kind?e.data=e.data.toUpperCase():"startsWith"===i.kind?e.data.startsWith(i.value)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):"endsWith"===i.kind?e.data.endsWith(i.value)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):"datetime"===i.kind?eu(i).test(e.data)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:"datetime",message:i.message}),r.dirty()):"date"===i.kind?ea.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:"date",message:i.message}),r.dirty()):"time"===i.kind?el(i).test(e.data)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_string,validation:"time",message:i.message}),r.dirty()):"duration"===i.kind?Y.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"duration",code:_.invalid_string,message:i.message}),r.dirty()):"ip"===i.kind?ec(e.data,i.version)||(T(t=this._getOrReturnCtx(e,t),{validation:"ip",code:_.invalid_string,message:i.message}),r.dirty()):"jwt"===i.kind?eh(e.data,i.alg)||(T(t=this._getOrReturnCtx(e,t),{validation:"jwt",code:_.invalid_string,message:i.message}),r.dirty()):"cidr"===i.kind?ef(e.data,i.version)||(T(t=this._getOrReturnCtx(e,t),{validation:"cidr",code:_.invalid_string,message:i.message}),r.dirty()):"base64"===i.kind?en.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"base64",code:_.invalid_string,message:i.message}),r.dirty()):"base64url"===i.kind?ei.test(e.data)||(T(t=this._getOrReturnCtx(e,t),{validation:"base64url",code:_.invalid_string,message:i.message}),r.dirty()):h.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:_.invalid_string,...d.errToObj(r)})}_addCheck(e){return new ed({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...d.errToObj(e)})}url(e){return this._addCheck({kind:"url",...d.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...d.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...d.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...d.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...d.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...d.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...d.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...d.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...d.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...d.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...d.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...d.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!=(t=null==e?void 0:e.offset)&&t,local:null!=(r=null==e?void 0:e.local)&&r,...d.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...d.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...d.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...d.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...d.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...d.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...d.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...d.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...d.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...d.errToObj(t)})}nonempty(e){return this.min(1,d.errToObj(e))}trim(){return new ed({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ed({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ed({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function ep(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return parseInt(e.toFixed(i).replace(".",""))%parseInt(t.toFixed(i).replace(".",""))/Math.pow(10,i)}ed.create=e=>{var t;return new ed({checks:[],typeName:g.ZodString,coerce:null!=(t=null==e?void 0:e.coerce)&&t,...U(e)})};class em extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.number,received:t.parsedType}),P}let r=new I;for(let n of this._def.checks)"int"===n.kind?h.isInteger(e.data)||(T(t=this._getOrReturnCtx(e,t),{code:_.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==ep(e.data,n.value)&&(T(t=this._getOrReturnCtx(e,t),{code:_.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(T(t=this._getOrReturnCtx(e,t),{code:_.not_finite,message:n.message}),r.dirty()):h.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,r,n){return new em({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:d.toString(n)}]})}_addCheck(e){return new em({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:d.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:d.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&h.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}em.create=e=>new em({checks:[],typeName:g.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...U(e)});class eg extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==v.bigint)return this._getInvalidInput(e);let r=new I;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(T(t=this._getOrReturnCtx(e,t),{code:_.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):h.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.bigint,received:t.parsedType}),P}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,r,n){return new eg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:d.toString(n)}]})}_addCheck(e){return new eg({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}eg.create=e=>{var t;return new eg({checks:[],typeName:g.ZodBigInt,coerce:null!=(t=null==e?void 0:e.coerce)&&t,...U(e)})};class ey extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.boolean,received:t.parsedType}),P}return M(e.data)}}ey.create=e=>new ey({typeName:g.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...U(e)});class ev extends Z{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.date,received:t.parsedType}),P}if(isNaN(e.data.getTime()))return T(this._getOrReturnCtx(e),{code:_.invalid_date}),P;let r=new I;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(T(t=this._getOrReturnCtx(e,t),{code:_.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):h.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ev({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:d.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:d.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ev.create=e=>new ev({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:g.ZodDate,...U(e)});class eb extends Z{_parse(e){if(this._getType(e)!==v.symbol){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.symbol,received:t.parsedType}),P}return M(e.data)}}eb.create=e=>new eb({typeName:g.ZodSymbol,...U(e)});class e_ extends Z{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.undefined,received:t.parsedType}),P}return M(e.data)}}e_.create=e=>new e_({typeName:g.ZodUndefined,...U(e)});class ew extends Z{_parse(e){if(this._getType(e)!==v.null){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.null,received:t.parsedType}),P}return M(e.data)}}ew.create=e=>new ew({typeName:g.ZodNull,...U(e)});class ex extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}}ex.create=e=>new ex({typeName:g.ZodAny,...U(e)});class eS extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}}eS.create=e=>new eS({typeName:g.ZodUnknown,...U(e)});class eE extends Z{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.never,received:t.parsedType}),P}}eE.create=e=>new eE({typeName:g.ZodNever,...U(e)});class eC extends Z{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.void,received:t.parsedType}),P}return M(e.data)}}eC.create=e=>new eC({typeName:g.ZodVoid,...U(e)});class eA extends Z{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==v.array)return T(t,{code:_.invalid_type,expected:v.array,received:t.parsedType}),P;if(null!==n.exactLength){let e=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;(e||i)&&(T(t,{code:e?_.too_big:_.too_small,minimum:i?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(T(t,{code:_.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(T(t,{code:_.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new D(t,e,t.path,r)))).then(e=>I.mergeArray(r,e));let i=[...t.data].map((e,r)=>n.type._parseSync(new D(t,e,t.path,r)));return I.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new eA({...this._def,minLength:{value:e,message:d.toString(t)}})}max(e,t){return new eA({...this._def,maxLength:{value:e,message:d.toString(t)}})}length(e,t){return new eA({...this._def,exactLength:{value:e,message:d.toString(t)}})}nonempty(e){return this.min(1,e)}}function ek(e){if(e instanceof eO){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=eW.create(ek(n))}return new eO({...e._def,shape:()=>t})}if(e instanceof eA)return new eA({...e._def,type:ek(e.element)});if(e instanceof eW)return eW.create(ek(e.unwrap()));if(e instanceof eq)return eq.create(ek(e.unwrap()));if(e instanceof e$)return e$.create(e.items.map(e=>ek(e)));else return e}eA.create=(e,t)=>new eA({type:e,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...U(t)});class eO extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=h.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==v.object){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.object,received:t.parsedType}),P}let{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof eE&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||o.push(e);let a=[];for(let e of i){let t=n[e],i=r.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new D(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof eE){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of o)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(T(r,{code:_.unrecognized_keys,keys:o}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of o){let n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new D(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of a){let r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>I.mergeObjectSync(t,e)):I.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return d.errToObj,new eO({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,i,o,a;let s=null!=(o=null==(i=(n=this._def).errorMap)?void 0:i.call(n,t,r).message)?o:r.defaultError;return"unrecognized_keys"===t.code?{message:null!=(a=d.errToObj(e).message)?a:s}:{message:s}}}:{}})}strip(){return new eO({...this._def,unknownKeys:"strip"})}passthrough(){return new eO({...this._def,unknownKeys:"passthrough"})}extend(e){return new eO({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new eO({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new eO({...this._def,catchall:e})}pick(e){let t={};return h.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new eO({...this._def,shape:()=>t})}omit(e){let t={};return h.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new eO({...this._def,shape:()=>t})}deepPartial(){return ek(this)}partial(e){let t={};return h.objectKeys(this.shape).forEach(r=>{let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new eO({...this._def,shape:()=>t})}required(e){let t={};return h.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eW;)e=e._def.innerType;t[r]=e}}),new eO({...this._def,shape:()=>t})}keyof(){return ez(h.objectKeys(this.shape))}}eO.create=(e,t)=>new eO({shape:()=>e,unknownKeys:"strip",catchall:eE.create(),typeName:g.ZodObject,...U(t)}),eO.strictCreate=(e,t)=>new eO({shape:()=>e,unknownKeys:"strict",catchall:eE.create(),typeName:g.ZodObject,...U(t)}),eO.lazycreate=(e,t)=>new eO({shape:e,unknownKeys:"strip",catchall:eE.create(),typeName:g.ZodObject,...U(t)});class eT extends Z{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new x(e.ctx.common.issues));return T(t,{code:_.invalid_union,unionErrors:r}),P}if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(n);{let e,n=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=n.map(e=>new x(e));return T(t,{code:_.invalid_union,unionErrors:i}),P}}get options(){return this._def.options}}eT.create=(e,t)=>new eT({options:e,typeName:g.ZodUnion,...U(t)});let eI=e=>{if(e instanceof eF)return eI(e.schema);if(e instanceof eG)return eI(e.innerType());if(e instanceof eD)return[e.value];if(e instanceof eU)return e.options;if(e instanceof eZ)return h.objectValues(e.enum);else if(e instanceof eV)return eI(e._def.innerType);else if(e instanceof e_)return[void 0];else if(e instanceof ew)return[null];else if(e instanceof eW)return[void 0,...eI(e.unwrap())];else if(e instanceof eq)return[null,...eI(e.unwrap())];else if(e instanceof eJ)return eI(e.unwrap());else if(e instanceof e0)return eI(e.unwrap());else if(e instanceof eX)return eI(e._def.innerType);else return[]};class eP extends Z{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return T(t,{code:_.invalid_type,expected:v.object,received:t.parsedType}),P;let r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(T(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let r of t){let t=eI(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(n.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,r)}}return new eP({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...U(r)})}}function eR(e,t){let r=b(e),n=b(t);if(e===t)return{valid:!0,data:e};if(r===v.object&&n===v.object){let r=h.objectKeys(t),n=h.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(let r of n){let n=eR(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===v.array&&n===v.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let n=0;n<e.length;n++){let i=eR(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}if(r===v.date&&n===v.date&&+e==+t)return{valid:!0,data:e};return{valid:!1}}class eM extends Z{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if($(e)||$(n))return P;let i=eR(e.value,n.value);return i.valid?((N(e)||N(n))&&t.dirty(),{status:t.value,value:i.data}):(T(r,{code:_.invalid_intersection_types}),P)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}eM.create=(e,t,r)=>new eM({left:e,right:t,typeName:g.ZodIntersection,...U(r)});class e$ extends Z{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.array)return T(r,{code:_.invalid_type,expected:v.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return T(r,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(T(r,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let n=[...r.data].map((e,t)=>{let n=this._def.items[t]||this._def.rest;return n?n._parse(new D(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>I.mergeArray(t,e)):I.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new e$({...this._def,rest:e})}}e$.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new e$({items:e,typeName:g.ZodTuple,rest:null,...U(t)})};class eN extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return T(r,{code:_.invalid_type,expected:v.object,received:r.parsedType}),P;let n=[],i=this._def.keyType,o=this._def.valueType;for(let e in r.data)n.push({key:i._parse(new D(r,e,r.path,e)),value:o._parse(new D(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?I.mergeObjectAsync(t,n):I.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new eN(t instanceof Z?{keyType:e,valueType:t,typeName:g.ZodRecord,...U(r)}:{keyType:ed.create(),valueType:e,typeName:g.ZodRecord,...U(t)})}}class ej extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.map)return T(r,{code:_.invalid_type,expected:v.map,received:r.parsedType}),P;let n=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:n._parse(new D(r,e,r.path,[o,"key"])),value:i._parse(new D(r,t,r.path,[o,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of o){let n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return P;("dirty"===n.status||"dirty"===i.status)&&t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of o){let n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return P;("dirty"===n.status||"dirty"===i.status)&&t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}ej.create=(e,t,r)=>new ej({valueType:t,keyType:e,typeName:g.ZodMap,...U(r)});class eB extends Z{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.set)return T(r,{code:_.invalid_type,expected:v.set,received:r.parsedType}),P;let n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(T(r,{code:_.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(T(r,{code:_.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let i=this._def.valueType;function o(e){let r=new Set;for(let n of e){if("aborted"===n.status)return P;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}let a=[...r.data.values()].map((e,t)=>i._parse(new D(r,e,r.path,t)));return r.common.async?Promise.all(a).then(e=>o(e)):o(a)}min(e,t){return new eB({...this._def,minSize:{value:e,message:d.toString(t)}})}max(e,t){return new eB({...this._def,maxSize:{value:e,message:d.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}eB.create=(e,t)=>new eB({valueType:e,minSize:null,maxSize:null,typeName:g.ZodSet,...U(t)});class eL extends Z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return T(t,{code:_.invalid_type,expected:v.function,received:t.parsedType}),P;function r(e,r){return k({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),S].filter(e=>!!e),issueData:{code:_.invalid_arguments,argumentsError:r}})}function n(e,r){return k({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,A(),S].filter(e=>!!e),issueData:{code:_.invalid_return_type,returnTypeError:r}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof eH){let e=this;return M(async function(...t){let a=new x([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw a.addIssue(r(t,e)),a}),l=await Reflect.apply(o,this,s);return await e._def.returns._def.type.parseAsync(l,i).catch(e=>{throw a.addIssue(n(l,e)),a})})}{let e=this;return M(function(...t){let a=e._def.args.safeParse(t,i);if(!a.success)throw new x([r(t,a.error)]);let s=Reflect.apply(o,this,a.data),l=e._def.returns.safeParse(s,i);if(!l.success)throw new x([n(s,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new eL({...this._def,args:e$.create(e).rest(eS.create())})}returns(e){return new eL({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new eL({args:e||e$.create([]).rest(eS.create()),returns:t||eS.create(),typeName:g.ZodFunction,...U(r)})}}class eF extends Z{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}eF.create=(e,t)=>new eF({getter:e,typeName:g.ZodLazy,...U(t)});class eD extends Z{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ez(e,t){return new eU({values:e,typeName:g.ZodEnum,...U(t)})}eD.create=(e,t)=>new eD({value:e,typeName:g.ZodLiteral,...U(t)});class eU extends Z{constructor(){super(...arguments),p.set(this,void 0)}_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return T(t,{expected:h.joinValues(r),received:t.parsedType,code:_.invalid_type}),P}if(L(this,p,"f")||F(this,p,new Set(this._def.values),"f"),!L(this,p,"f").has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return T(t,{received:t.data,code:_.invalid_enum_value,options:r}),P}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return eU.create(e,{...this._def,...t})}exclude(e,t=this._def){return eU.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}p=new WeakMap,eU.create=ez;class eZ extends Z{constructor(){super(...arguments),m.set(this,void 0)}_parse(e){let t=h.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==v.string&&r.parsedType!==v.number){let e=h.objectValues(t);return T(r,{expected:h.joinValues(e),received:r.parsedType,code:_.invalid_type}),P}if(L(this,m,"f")||F(this,m,new Set(h.getValidEnumValues(this._def.values)),"f"),!L(this,m,"f").has(e.data)){let e=h.objectValues(t);return T(r,{received:r.data,code:_.invalid_enum_value,options:e}),P}return M(e.data)}get enum(){return this._def.values}}m=new WeakMap,eZ.create=(e,t)=>new eZ({values:e,typeName:g.ZodNativeEnum,...U(t)});class eH extends Z{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==v.promise&&!1===t.common.async?(T(t,{code:_.invalid_type,expected:v.promise,received:t.parsedType}),P):M((t.parsedType===v.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eH.create=(e,t)=>new eH({type:e,typeName:g.ZodPromise,...U(t)});class eG extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{T(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){let e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return P;let n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?P:"dirty"===n.status||"dirty"===t.value?R(n.value):n});{if("aborted"===t.value)return P;let n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?P:"dirty"===n.status||"dirty"===t.value?R(n.value):n}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?P:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?P:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}}if("transform"===n.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>j(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):e);else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!j(e))return e;let o=n.transform(e.value,i);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}h.assertNever(n)}}eG.create=(e,t,r)=>new eG({schema:e,typeName:g.ZodEffects,effect:t,...U(r)}),eG.createWithPreprocess=(e,t,r)=>new eG({schema:t,effect:{type:"preprocess",transform:e},typeName:g.ZodEffects,...U(r)});class eW extends Z{_parse(e){return this._getType(e)===v.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eW.create=(e,t)=>new eW({innerType:e,typeName:g.ZodOptional,...U(t)});class eq extends Z{_parse(e){return this._getType(e)===v.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eq.create=(e,t)=>new eq({innerType:e,typeName:g.ZodNullable,...U(t)});class eV extends Z{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===v.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}eV.create=(e,t)=>new eV({innerType:e,typeName:g.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...U(t)});class eX extends Z{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return B(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new x(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new x(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}eX.create=(e,t)=>new eX({innerType:e,typeName:g.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...U(t)});class eY extends Z{_parse(e){if(this._getType(e)!==v.nan){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:v.nan,received:t.parsedType}),P}return{status:"valid",value:e.data}}}eY.create=e=>new eY({typeName:g.ZodNaN,...U(e)});let eK=Symbol("zod_brand");class eJ extends Z{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eQ extends Z{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?P:"dirty"===e.status?(t.dirty(),R(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?P:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eQ({in:e,out:t,typeName:g.ZodPipeline})}}class e0 extends Z{_parse(e){let t=this._def.innerType._parse(e),r=e=>(j(e)&&(e.value=Object.freeze(e.value)),e);return B(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function e1(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function e2(e,t={},r){return e?ex.create().superRefine((n,i)=>{var o,a;let s=e(n);if(s instanceof Promise)return s.then(e=>{var o,a;if(!e){let e=e1(t,n),s=null==(a=null!=(o=e.fatal)?o:r)||a;i.addIssue({code:"custom",...e,fatal:s})}});if(!s){let e=e1(t,n),s=null==(a=null!=(o=e.fatal)?o:r)||a;i.addIssue({code:"custom",...e,fatal:s})}}):ex.create()}e0.create=(e,t)=>new e0({innerType:e,typeName:g.ZodReadonly,...U(t)});let e3={object:eO.lazycreate};!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"}(g||(g={}));let e5=(e,t={message:`Input not instance of ${e.name}`})=>e2(t=>t instanceof e,t),e4=ed.create,e6=em.create,e8=eY.create,e9=eg.create,e7=ey.create,te=ev.create,tt=eb.create,tr=e_.create,tn=ew.create,ti=ex.create,to=eS.create,ta=eE.create,ts=eC.create,tl=eA.create,tu=eO.create,tc=eO.strictCreate,th=eT.create,tf=eP.create,td=eM.create,tp=e$.create,tm=eN.create,tg=ej.create,ty=eB.create,tv=eL.create,tb=eF.create,t_=eD.create,tw=eU.create,tx=eZ.create,tS=eH.create,tE=eG.create,tC=eW.create,tA=eq.create,tk=eG.createWithPreprocess,tO=eQ.create,tT=()=>e6().optional(),tI=()=>e7().optional(),tP={string:e=>ed.create({...e,coerce:!0}),number:e=>em.create({...e,coerce:!0}),boolean:e=>ey.create({...e,coerce:!0}),bigint:e=>eg.create({...e,coerce:!0}),date:e=>ev.create({...e,coerce:!0})},tR=P;var tM=Object.freeze({__proto__:null,defaultErrorMap:S,setErrorMap:C,getErrorMap:A,makeIssue:k,EMPTY_PATH:O,addIssueToContext:T,ParseStatus:I,INVALID:P,DIRTY:R,OK:M,isAborted:$,isDirty:N,isValid:j,isAsync:B,get util(){return h},get objectUtil(){return f},ZodParsedType:v,getParsedType:b,ZodType:Z,datetimeRegex:eu,ZodString:ed,ZodNumber:em,ZodBigInt:eg,ZodBoolean:ey,ZodDate:ev,ZodSymbol:eb,ZodUndefined:e_,ZodNull:ew,ZodAny:ex,ZodUnknown:eS,ZodNever:eE,ZodVoid:eC,ZodArray:eA,ZodObject:eO,ZodUnion:eT,ZodDiscriminatedUnion:eP,ZodIntersection:eM,ZodTuple:e$,ZodRecord:eN,ZodMap:ej,ZodSet:eB,ZodFunction:eL,ZodLazy:eF,ZodLiteral:eD,ZodEnum:eU,ZodNativeEnum:eZ,ZodPromise:eH,ZodEffects:eG,ZodTransformer:eG,ZodOptional:eW,ZodNullable:eq,ZodDefault:eV,ZodCatch:eX,ZodNaN:eY,BRAND:eK,ZodBranded:eJ,ZodPipeline:eQ,ZodReadonly:e0,custom:e2,Schema:Z,ZodSchema:Z,late:e3,get ZodFirstPartyTypeKind(){return g},coerce:tP,any:ti,array:tl,bigint:e9,boolean:e7,date:te,discriminatedUnion:tf,effect:tE,enum:tw,function:tv,instanceof:e5,intersection:td,lazy:tb,literal:t_,map:tg,nan:e8,nativeEnum:tx,never:ta,null:tn,nullable:tA,number:e6,object:tu,oboolean:tI,onumber:tT,optional:tC,ostring:()=>e4().optional(),pipeline:tO,preprocess:tk,promise:tS,record:tm,set:ty,strictObject:tc,string:e4,symbol:tt,transformer:tE,tuple:tp,undefined:tr,union:th,unknown:to,void:ts,NEVER:tR,ZodIssueCode:_,quotelessJson:w,ZodError:x}),t$=r(32656),tN=r(67774),tj=r(88464);let tB=(...e)=>fetch(...e),tL=Symbol.for("ls:fetch_implementation"),tF=()=>globalThis[tL]??tB,tD=[400,401,403,404,405,406,407,408],tz=[409];class tU{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in tj?this.queue=new tj.default({concurrency:this.maxConcurrency}):this.queue=new tj({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let r=this.onFailedResponseHook;return this.queue.add(()=>t$(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError")||e?.code==="ECONNABORTED")throw e;let t=e?.response,n=t?.status;if(n){if(tD.includes(+n))throw e;if(tz.includes(+n))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>tF()(...e).then(e=>e.ok?e:Promise.reject(e)))}}function tZ(e){return"function"==typeof e?._getType}function tH(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var tG=r(46633);function tW(e,t){if(!tG.Z(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}let tq={};function tV(e){tq[e]||(console.warn(e),tq[e]=!0)}function tX(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[r,i]=t.split("/",2);if(!r||!i)throw Error(`Invalid identifier format: ${e}`);return[r,i,n]}if(!t)throw Error(`Invalid identifier format: ${e}`);return["-",t,n]}r(7968);class tY extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function tK(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}n=await e.text();let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;if(409===e.status)throw new tY(i);throw Error(i)}var tJ="[...]",tQ={result:"[Circular]"},t0=[],t1=[];function t2(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function t3(e,t,r,n){try{return JSON.stringify(e,t,r)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),"[Unserializable]";console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===n&&(n=t2()),t4(e,"",0,[],void 0,0,n);try{i=0===t1.length?JSON.stringify(e,t,r):JSON.stringify(e,t6(t),r)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==t0.length;){var i,o=t0.pop();4===o.length?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return i}}function t5(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);void 0!==i.get?i.configurable?(Object.defineProperty(n,r,{value:e}),t0.push([n,r,t,i])):t1.push([t,r,e]):(n[r]=e,t0.push([n,r,t]))}function t4(e,t,r,n,i,o,a){if(o+=1,"object"==typeof e&&null!==e){for(s=0;s<n.length;s++)if(n[s]===e)return void t5(tQ,e,t,i);if(void 0!==a.depthLimit&&o>a.depthLimit||void 0!==a.edgesLimit&&r+1>a.edgesLimit)return void t5(tJ,e,t,i);if(n.push(e),Array.isArray(e))for(s=0;s<e.length;s++)t4(e[s],s,s,n,e,o,a);else{var s,l=Object.keys(e);for(s=0;s<l.length;s++){var u=l[s];t4(e[u],u,s,n,e,o,a)}}n.pop()}}function t6(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(t1.length>0)for(var n=0;n<t1.length;n++){var i=t1[n];if(i[1]===t&&i[0]===r){r=i[2],t1.splice(n,1);break}}return e.call(this,t,r)}}function t8(e){let t=rm(),r=rg(),n=e.extra??{},i=n.metadata;return e.extra={...n,runtime:{...t,...n?.runtime},metadata:{...r,...r.revision_id||e.revision_id?{revision_id:e.revision_id??r.revision_id}:{},...i}},e}let t9=()=>{let e=rb("TRACING_SAMPLING_RATE");if(void 0===e)return;let t=parseFloat(e);if(t<0||t>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},t7=e=>{let t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t};async function re(e){let t=[];for await(let r of e)t.push(r);return t}function rt(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let rr=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};class rn{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t,r=new Promise(e=>{t=e}),n=t3(e.item).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:n}),this.sizeBytes+=n,r}pop(e){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let t=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0;){let e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){let e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map(e=>({action:e.action,item:e.payload})),()=>t.forEach(e=>e.itemPromiseResolve())]}}let ri=0x1400000,ro=2500;class ra{constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new rn}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===rv("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});let t=ra.getDefaultClientConfig();if(this.tracingSampleRate=t9(),this.apiUrl=rt(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=rt(e.apiKey??t.apiKey),this.webUrl=rt(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new tU(e.callerOptions??{}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new tU({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:rr}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let e=rb("API_KEY"),t=rb("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:"true"===rb("HIDE_INPUTS"),hideOutputs:"true"===rb("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if(t7(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let e={"User-Agent":`langsmith-js/${rs}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=this.processOutputs(t.outputs)),t}async _getResponse(e,t){let r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`,i=await this.caller.call(tF(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(i,`Failed to fetch ${e}`),i}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let n=Number(t.get("offset"))||0,i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(i));let o=`${this.apiUrl}${e}?${t}`,a=await this.caller.call(tF(),o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(a,`Failed to fetch ${e}`);let s=r?r(await a.json()):await a.json();if(0===s.length||(yield s,s.length<i))break;n+=s.length}}async *_getCursorPaginatedList(e,t=null,r="POST",n="runs"){let i=t?{...t}:{};for(;;){let t=await this.caller.call(tF(),`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)}),o=await t.json();if(!o||!o[n])break;yield o[n];let a=o.cursors;if(!a||!a.next)break;i.cursor=a.next}}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){let t=[];for(let r of e)this.filteredPostUuids.has(r.id)?this.filteredPostUuids.delete(r.id):t.push(r);return t}{let t=[];for(let r of e)r.id!==r.trace_id&&!this.filteredPostUuids.has(r.trace_id)||Math.random()<this.tracingSampleRate?t.push(r):this.filteredPostUuids.add(r.id);return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??ri}async _getMultiPartSupport(){let e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue(e){let t=[];for(;this.autoBatchQueue.items.length>0;){let[r,n]=this.autoBatchQueue.pop(e);if(!r.length){n();break}let i=this._processBatch(r,n).catch(console.error);t.push(i)}return Promise.all(t)}async _processBatch(e,t){if(!e.length)return void t();try{let t={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=t8(e.item));let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await tF()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(ro),...this.fetchOptions});return await tK(e,"get server info"),e.json()}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;let n=this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order)return void this.processRunOperation({action:"create",item:n}).catch(console.error);let i=t8(n),o=await this.caller.call(tF(),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:t3(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(o,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[],n=t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[];if(r.length>0&&n.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),n=t}let i={post:this._filterForSampling(r),patch:this._filterForSampling(n,!0)};if(!i.post.length&&!i.patch.length)return;let o={post:[],patch:[]};for(let e of["post","patch"]){let t=e,r=i[t].reverse(),n=r.pop();for(;void 0!==n;)o[t].push(n),n=r.pop()}(o.post.length>0||o.patch.length>0)&&await this._postBatchIngestRuns(t3(o))}async _postBatchIngestRuns(e){let t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call(tF(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r={},n=[];for(let t of e??[]){let e=this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,n.push(e)}let i=[];for(let e of t??[])i.push(this.prepareRunCreateOrUpdateInputs(e));if(void 0!==n.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(n.length>0&&i.length>0){let e=n.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),i=t}if(0===n.length&&0===i.length)return;let o=[],a=[];for(let[e,t]of[["post",n],["patch",i]])for(let n of t){let{inputs:t,outputs:i,events:s,attachments:l,...u}=n,c={inputs:t,outputs:i,events:s},h=t3(u);for(let[t,r]of(a.push({name:`${e}.${u.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})}),Object.entries(c))){if(void 0===r)continue;let n=t3(r);a.push({name:`${e}.${u.id}.${t}`,payload:new Blob([n],{type:`application/json; length=${n.length}`})})}if(void 0!==u.id){let e=r[u.id];if(e)for(let[t,n]of(delete r[u.id],Object.entries(e))){let e,r;if(Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${u.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}a.push({name:`attachment.${u.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}o.push(`trace=${u.trace_id},id=${u.id}`)}await this._sendMultipartRequest(a,o.join("; "))}async _sendMultipartRequest(e,t){try{let t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=[];for(let n of e)r.push(new Blob([`--${t}\r
244
+ should be one of ${e}`)}try{let n=r.reduce((e,t)=>(e[t]="foo",e),{});Array.isArray(e)?e.forEach(e=>{if("text"===e.type)B(e.text,t,n);else if("image_url"===e.type)if("string"==typeof e.image_url)B(e.image_url,t,n);else{let r=e.image_url.url;B(r,t,n)}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):B(e,t,n)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}}},79097:function(e,t,r){"use strict";let n,i,o,a,s,l,u;r.d(t,{eq:()=>nh});var c={};r.r(c),r.d(c,{JsonPatchError:()=>eB,_areEquals:()=>eq,applyOperation:()=>eU,applyPatch:()=>eZ,applyReducer:()=>eH,deepClone:()=>eL,getValueByPointer:()=>ez,validate:()=>eW,validator:()=>eG});var h=r(43427),f=r(32656),d=r(67774),p=r(88464);let m=(...e)=>fetch(...e),g=Symbol.for("ls:fetch_implementation"),y=()=>globalThis[g]??m,v=[400,401,403,404,405,406,407,408],b=[409];class _{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in p?this.queue=new p.default({concurrency:this.maxConcurrency}):this.queue=new p({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let r=this.onFailedResponseHook;return this.queue.add(()=>f(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError")||e?.code==="ECONNABORTED")throw e;let t=e?.response,n=t?.status;if(n){if(v.includes(+n))throw e;if(b.includes(+n))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>y()(...e).then(e=>e.ok?e:Promise.reject(e)))}}function w(e){return"function"==typeof e?._getType}function x(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var S=r(46633);function E(e,t){if(!S.Z(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}let C={};function A(e){C[e]||(console.warn(e),C[e]=!0)}function k(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[r,i]=t.split("/",2);if(!r||!i)throw Error(`Invalid identifier format: ${e}`);return[r,i,n]}if(!t)throw Error(`Invalid identifier format: ${e}`);return["-",t,n]}r(7968);class O extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function T(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}n=await e.text();let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;if(409===e.status)throw new O(i);throw Error(i)}var I="[...]",P={result:"[Circular]"},R=[],M=[];function $(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function N(e,t,r,n){try{return JSON.stringify(e,t,r)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),"[Unserializable]";console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===n&&(n=$()),B(e,"",0,[],void 0,0,n);try{i=0===M.length?JSON.stringify(e,t,r):JSON.stringify(e,L(t),r)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==R.length;){var i,o=R.pop();4===o.length?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return i}}function j(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);void 0!==i.get?i.configurable?(Object.defineProperty(n,r,{value:e}),R.push([n,r,t,i])):M.push([t,r,e]):(n[r]=e,R.push([n,r,t]))}function B(e,t,r,n,i,o,a){if(o+=1,"object"==typeof e&&null!==e){for(s=0;s<n.length;s++)if(n[s]===e)return void j(P,e,t,i);if(void 0!==a.depthLimit&&o>a.depthLimit||void 0!==a.edgesLimit&&r+1>a.edgesLimit)return void j(I,e,t,i);if(n.push(e),Array.isArray(e))for(s=0;s<e.length;s++)B(e[s],s,s,n,e,o,a);else{var s,l=Object.keys(e);for(s=0;s<l.length;s++){var u=l[s];B(e[u],u,s,n,e,o,a)}}n.pop()}}function L(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(M.length>0)for(var n=0;n<M.length;n++){var i=M[n];if(i[1]===t&&i[0]===r){r=i[2],M.splice(n,1);break}}return e.call(this,t,r)}}function F(e){let t=en(),r=ei(),n=e.extra??{},i=n.metadata;return e.extra={...n,runtime:{...t,...n?.runtime},metadata:{...r,...r.revision_id||e.revision_id?{revision_id:e.revision_id??r.revision_id}:{},...i}},e}let D=()=>{let e=es("TRACING_SAMPLING_RATE");if(void 0===e)return;let t=parseFloat(e);if(t<0||t>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},z=e=>{let t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t};async function U(e){let t=[];for await(let r of e)t.push(r);return t}function Z(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let H=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};class G{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t,r=new Promise(e=>{t=e}),n=N(e.item).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:n}),this.sizeBytes+=n,r}pop(e){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let t=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0;){let e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){let e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map(e=>({action:e.action,item:e.payload})),()=>t.forEach(e=>e.itemPromiseResolve())]}}let W=0x1400000,q=2500;class V{constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new G}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===ea("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});let t=V.getDefaultClientConfig();if(this.tracingSampleRate=D(),this.apiUrl=Z(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Z(e.apiKey??t.apiKey),this.webUrl=Z(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new _(e.callerOptions??{}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new _({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:H}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let e=es("API_KEY"),t=es("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:"true"===es("HIDE_INPUTS"),hideOutputs:"true"===es("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if(z(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let e={"User-Agent":`langsmith-js/${X}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=this.processOutputs(t.outputs)),t}async _getResponse(e,t){let r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`,i=await this.caller.call(y(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(i,`Failed to fetch ${e}`),i}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let n=Number(t.get("offset"))||0,i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(i));let o=`${this.apiUrl}${e}?${t}`,a=await this.caller.call(y(),o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(a,`Failed to fetch ${e}`);let s=r?r(await a.json()):await a.json();if(0===s.length||(yield s,s.length<i))break;n+=s.length}}async *_getCursorPaginatedList(e,t=null,r="POST",n="runs"){let i=t?{...t}:{};for(;;){let t=await this.caller.call(y(),`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)}),o=await t.json();if(!o||!o[n])break;yield o[n];let a=o.cursors;if(!a||!a.next)break;i.cursor=a.next}}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){let t=[];for(let r of e)this.filteredPostUuids.has(r.id)?this.filteredPostUuids.delete(r.id):t.push(r);return t}{let t=[];for(let r of e)r.id!==r.trace_id&&!this.filteredPostUuids.has(r.trace_id)||Math.random()<this.tracingSampleRate?t.push(r):this.filteredPostUuids.add(r.id);return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??W}async _getMultiPartSupport(){let e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue(e){let t=[];for(;this.autoBatchQueue.items.length>0;){let[r,n]=this.autoBatchQueue.pop(e);if(!r.length){n();break}let i=this._processBatch(r,n).catch(console.error);t.push(i)}return Promise.all(t)}async _processBatch(e,t){if(!e.length)return void t();try{let t={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=F(e.item));let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await y()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(q),...this.fetchOptions});return await T(e,"get server info"),e.json()}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;let n=this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order)return void this.processRunOperation({action:"create",item:n}).catch(console.error);let i=F(n),o=await this.caller.call(y(),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:N(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(o,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[],n=t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[];if(r.length>0&&n.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),n=t}let i={post:this._filterForSampling(r),patch:this._filterForSampling(n,!0)};if(!i.post.length&&!i.patch.length)return;let o={post:[],patch:[]};for(let e of["post","patch"]){let t=e,r=i[t].reverse(),n=r.pop();for(;void 0!==n;)o[t].push(n),n=r.pop()}(o.post.length>0||o.patch.length>0)&&await this._postBatchIngestRuns(N(o))}async _postBatchIngestRuns(e){let t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call(y(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r={},n=[];for(let t of e??[]){let e=this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,n.push(e)}let i=[];for(let e of t??[])i.push(this.prepareRunCreateOrUpdateInputs(e));if(void 0!==n.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(n.length>0&&i.length>0){let e=n.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),i=t}if(0===n.length&&0===i.length)return;let o=[],a=[];for(let[e,t]of[["post",n],["patch",i]])for(let n of t){let{inputs:t,outputs:i,events:s,attachments:l,...u}=n,c={inputs:t,outputs:i,events:s},h=N(u);for(let[t,r]of(a.push({name:`${e}.${u.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})}),Object.entries(c))){if(void 0===r)continue;let n=N(r);a.push({name:`${e}.${u.id}.${t}`,payload:new Blob([n],{type:`application/json; length=${n.length}`})})}if(void 0!==u.id){let e=r[u.id];if(e)for(let[t,n]of(delete r[u.id],Object.entries(e))){let e,r;if(Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${u.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}a.push({name:`attachment.${u.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}o.push(`trace=${u.trace_id},id=${u.id}`)}await this._sendMultipartRequest(a,o.join("; "))}async _sendMultipartRequest(e,t){try{let t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=[];for(let n of e)r.push(new Blob([`--${t}\r
245
245
  `])),r.push(new Blob([`Content-Disposition: form-data; name="${n.name}"\r
246
246
  `,`Content-Type: ${n.payload.type}\r
247
247
  \r
248
248
  `])),r.push(n.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r
249
- `]));let n=new Blob(r),i=await n.arrayBuffer(),o=await this.batchIngestCaller.call(tF(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(o,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()}
249
+ `]));let n=new Blob(r),i=await n.arrayBuffer(),o=await this.batchIngestCaller.call(y(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(o,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()}
250
250
 
251
- Context: ${t}`)}}async updateRun(e,t){tW(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order)return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r}).catch(console.error):void this.processRunOperation({action:"update",item:r}).catch(console.error);let n={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(tF(),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,body:t3(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(i,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){tW(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:rb("PROJECT")||"default"})).id;let n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await re(this.listRuns({id:e.child_run_ids})),r={},n={};for(let e of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===e.parent_run_id||void 0===e.parent_run_id)throw Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),n[e.id]=e}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(n[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:n,traceId:i,referenceExampleId:o,startTime:a,executionOrder:s,isRoot:l,runType:u,error:c,id:h,query:f,filter:d,traceFilter:p,treeFilter:m,limit:g,select:y}=e,v=[];if(t&&(v=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));v.push(...t)}let b=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],_={session:v.length?v:null,run_type:u,reference_example:o,query:f,filter:d,trace_filter:p,tree_filter:m,execution_order:s,parent_run:n,start_time:a?a.toISOString():null,error:c,id:h,limit:g,trace:i,select:y||b,is_root:l},w=0;for await(let e of this._getCursorPaginatedList("/runs/query",_))if(g){if(w>=g)break;if(e.length+w>g){let t=e.slice(0,g-w);yield*t;break}w+=e.length,yield*e}else yield*e}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:i,projectIds:o,referenceExampleIds:a,startTime:s,endTime:l,error:u,query:c,filter:h,traceFilter:f,treeFilter:d,isRoot:p,dataSourceType:m}){let g=o||[];i&&(g=[...o||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let y=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:n,session:g,reference_example:a,start_time:s,end_time:l,error:u,query:c,filter:h,trace_filter:f,tree_filter:d,is_root:p,data_source_type:m}).filter(([e,t])=>void 0!==t)),v=await this.caller.call(tF(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(y),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v.json()}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||tN.Z()};tW(e);let n=await this.caller.call(tF(),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await n.json();if(null===i||!("share_token"in i))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){tW(e);let t=await this.caller.call(tF(),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(t,"unshare run",!0)}async readRunSharedLink(e){tW(e);let t=await this.caller.call(tF(),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);tW(e);let n=await this.caller.call(tF(),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),tW(e);let r=await this.caller.call(tF(),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};tW(e);let n=await this.caller.call(tF(),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await n.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){tW(e);let t=await this.caller.call(tF(),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(t,"unshare dataset",!0)}async readSharedDataset(e){tW(e);let t=await this.caller.call(tF(),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){let r={};t?.exampleIds&&(r.id=t.exampleIds);let n=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.append(e,t)):n.append(e,t)});let i=await this.caller.call(tF(),`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),o=await i.json();if(!i.ok){if("detail"in o)throw Error(`Failed to list shared examples.
251
+ Context: ${t}`)}}async updateRun(e,t){E(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order)return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r}).catch(console.error):void this.processRunOperation({action:"update",item:r}).catch(console.error);let n={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(y(),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,body:N(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(i,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){E(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:es("PROJECT")||"default"})).id;let n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await U(this.listRuns({id:e.child_run_ids})),r={},n={};for(let e of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===e.parent_run_id||void 0===e.parent_run_id)throw Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),n[e.id]=e}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(n[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:n,traceId:i,referenceExampleId:o,startTime:a,executionOrder:s,isRoot:l,runType:u,error:c,id:h,query:f,filter:d,traceFilter:p,treeFilter:m,limit:g,select:y}=e,v=[];if(t&&(v=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));v.push(...t)}let b=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],_={session:v.length?v:null,run_type:u,reference_example:o,query:f,filter:d,trace_filter:p,tree_filter:m,execution_order:s,parent_run:n,start_time:a?a.toISOString():null,error:c,id:h,limit:g,trace:i,select:y||b,is_root:l},w=0;for await(let e of this._getCursorPaginatedList("/runs/query",_))if(g){if(w>=g)break;if(e.length+w>g){let t=e.slice(0,g-w);yield*t;break}w+=e.length,yield*e}else yield*e}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:i,projectIds:o,referenceExampleIds:a,startTime:s,endTime:l,error:u,query:c,filter:h,traceFilter:f,treeFilter:d,isRoot:p,dataSourceType:m}){let g=o||[];i&&(g=[...o||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let v=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:n,session:g,reference_example:a,start_time:s,end_time:l,error:u,query:c,filter:h,trace_filter:f,tree_filter:d,is_root:p,data_source_type:m}).filter(([e,t])=>void 0!==t)),b=await this.caller.call(y(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(v),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await b.json()}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||d.Z()};E(e);let n=await this.caller.call(y(),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await n.json();if(null===i||!("share_token"in i))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){E(e);let t=await this.caller.call(y(),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(t,"unshare run",!0)}async readRunSharedLink(e){E(e);let t=await this.caller.call(y(),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);E(e);let n=await this.caller.call(y(),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),E(e);let r=await this.caller.call(y(),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};E(e);let n=await this.caller.call(y(),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await n.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){E(e);let t=await this.caller.call(y(),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(t,"unshare dataset",!0)}async readSharedDataset(e){E(e);let t=await this.caller.call(y(),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){let r={};t?.exampleIds&&(r.id=t.exampleIds);let n=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.append(e,t)):n.append(e,t)});let i=await this.caller.call(y(),`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),o=await i.json();if(!i.ok){if("detail"in o)throw Error(`Failed to list shared examples.
252
252
  Status: ${i.status}
253
- Message: ${o.detail.join("\n")}`);throw Error(`Failed to list shared examples: ${i.status} ${i.statusText}`)}return o.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:i=null,referenceDatasetId:o=null}){let a=n?"?upsert=true":"",s=`${this.apiUrl}/sessions${a}`,l=i||{};r&&(l.metadata=r);let u={name:e,extra:l,description:t};null!==o&&(u.reference_dataset_id=o);let c=await this.caller.call(tF(),s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(c,"create project"),await c.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:i=null,endTime:o=null}){let a=`${this.apiUrl}/sessions/${e}`,s=i;n&&(s={...s||{},metadata:n});let l={name:t,extra:s,description:r,end_time:o?new Date(o).toISOString():null},u=await this.caller.call(tF(),a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(u,"update project"),await u.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions",n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)tW(e),r+=`/${e}`;else if(void 0!==t)n.append("name",t);else throw Error("Must provide projectName or projectId");let i=await this.caller.call(tF(),`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let e=await i.json();if(!i.ok)return!1;if(Array.isArray(e))return e.length>0;return!0}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n,i="/sessions",o=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)tW(e),i+=`/${e}`;else if(void 0!==t)o.append("name",t);else throw Error("Must provide projectName or projectId");void 0!==r&&o.append("include_stats",r.toString());let a=await this._get(i,o);if(Array.isArray(a)){if(0===a.length)throw Error(`Project[id=${e}, name=${t}] not found`);n=a[0]}else n=a;return n}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:n,referenceDatasetName:i,referenceFree:o,metadata:a}={}){let s=new URLSearchParams;if(void 0!==e)for(let t of e)s.append("id",t);if(void 0!==t&&s.append("name",t),void 0!==r&&s.append("name_contains",r),void 0!==n)s.append("reference_dataset",n);else if(void 0!==i){let e=await this.readDataset({datasetName:i});s.append("reference_dataset",e.id)}for await(let e of(void 0!==o&&s.append("reference_free",o.toString()),void 0!==a&&s.append("metadata",JSON.stringify(a)),this._getPaginated("/sessions",s)))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");tW(r=void 0===e?(await this.readProject({projectName:t})).id:e);let n=await this.caller.call(tF(),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(n,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:i,dataType:o,name:a}){let s=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),r.forEach(e=>{l.append("input_keys",e)}),n.forEach(e=>{l.append("output_keys",e)}),i&&l.append("description",i),o&&l.append("data_type",o),a&&l.append("name",a);let u=await this.caller.call(tF(),s,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(u,"upload CSV"),await u.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:i,metadata:o}={}){let a={name:e,description:t,extra:o?{metadata:o}:void 0};r&&(a.data_type=r),n&&(a.inputs_schema_definition=n),i&&(a.outputs_schema_definition=i);let s=await this.caller.call(tF(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(s,"create dataset"),await s.json()}async readDataset({datasetId:e,datasetName:t}){let r,n="/datasets",i=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)tW(e),n+=`/${e}`;else if(void 0!==t)i.append("name",t);else throw Error("Must provide datasetName or datasetId");let o=await this._get(n,i);if(Array.isArray(o)){if(0===o.length)throw Error(`Dataset[id=${e}, name=${t}] not found`);r=o[0]}else r=o;return r}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:n}){let i=e;if(void 0===i&&void 0===t)throw Error("Must provide either datasetName or datasetId");if(void 0!==i&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");void 0===i&&(i=(await this.readDataset({datasetName:t})).id);let o=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof n?n:n.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let r="/datasets";if(void 0!==e);else if(void 0!==t)e=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide datasetName or datasetId");let n=await this._getResponse(`${r}/${e}/openai_ft`);return(await n.text()).trim().split("\n").map(e=>JSON.parse(e))}async *listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:i,metadata:o}={}){let a="/datasets",s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(let e of r)s.append("id",e);for await(let e of(void 0!==n&&s.append("name",n),void 0!==i&&s.append("name_contains",i),void 0!==o&&s.append("metadata",JSON.stringify(o)),this._getPaginated(a,s)))yield*e}async updateDataset(e){let{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let i=t??(await this.readDataset({datasetName:r})).id;tW(i);let o=await this.caller.call(tF(),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(o,"update dataset"),await o.json()}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(n=(await this.readDataset({datasetName:t})).id),void 0!==n)tW(n),r+=`/${n}`;else throw Error("Must provide datasetName or datasetId");let i=await this.caller.call(tF(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(i,`delete ${r}`),await i.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(n||t)if(n&&t)throw Error("Must provide either datasetName or datasetId, not both");else n||(n=(await this.readDataset({datasetName:t})).id);else throw Error("Must provide either datasetName or datasetId");tW(n);let i={tag:r},o=await this.caller.call(tF(),`${this.apiUrl}/datasets/${n}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(o,"index dataset"),await o.json()}async similarExamples(e,t,r,{filter:n}={}){let i={limit:r,inputs:e};void 0!==n&&(i.filter=n),tW(t);let o=await this.caller.call(tF(),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(o,"fetch similar examples"),(await o.json()).examples}async createExample(e,t,{datasetId:r,datasetName:n,createdAt:i,exampleId:o,metadata:a,split:s,sourceRunId:l}){let u=r;if(void 0===u&&void 0===n)throw Error("Must provide either datasetName or datasetId");if(void 0!==u&&void 0!==n)throw Error("Must provide either datasetName or datasetId, not both");void 0===u&&(u=(await this.readDataset({datasetName:n})).id);let c=i||new Date,h={dataset_id:u,inputs:e,outputs:t,created_at:c?.toISOString(),id:o,metadata:a,split:s,source_run_id:l},f=await this.caller.call(tF(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(f,"create example"),await f.json()}async createExamples(e){let{inputs:t,outputs:r,metadata:n,sourceRunIds:i,exampleIds:o,datasetId:a,datasetName:s}=e,l=a;if(void 0===l&&void 0===s)throw Error("Must provide either datasetName or datasetId");if(void 0!==l&&void 0!==s)throw Error("Must provide either datasetName or datasetId, not both");void 0===l&&(l=(await this.readDataset({datasetName:s})).id);let u=t.map((t,a)=>({dataset_id:l,inputs:t,outputs:r?r[a]:void 0,metadata:n?n[a]:void 0,split:e.splits?e.splits[a]:void 0,id:o?o[a]:void 0,source_run_id:i?i[a]:void 0})),c=await this.caller.call(tF(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(c,"create examples"),await c.json()}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){let n=e.map(e=>tZ(e)?tH(e):e),i=tZ(t)?tH(t):t;return this.createExample({input:n},{output:i},r)}async readExample(e){tW(e);let t=`/examples/${e}`,{attachment_urls:r,...n}=await this._get(t),i=n;return r&&(i.attachments=Object.entries(r).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url},e),{})),i}async *listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:i,inlineS3Urls:o,metadata:a,limit:s,offset:l,filter:u,includeAttachments:c}={}){let h;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)h=e;else if(void 0!==t)h=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide a datasetName or datasetId");let f=new URLSearchParams({dataset:h}),d=n?"string"==typeof n?n:n?.toISOString():void 0;d&&f.append("as_of",d);let p=o??!0;if(f.append("inline_s3_urls",p.toString()),void 0!==r)for(let e of r)f.append("id",e);if(void 0!==i)for(let e of i)f.append("splits",e);if(void 0!==a){let e=JSON.stringify(a);f.append("metadata",e)}void 0!==s&&f.append("limit",s.toString()),void 0!==l&&f.append("offset",l.toString()),void 0!==u&&f.append("filter",u),!0===c&&["attachment_urls","outputs","metadata"].forEach(e=>f.append("select",e));let m=0;for await(let e of this._getPaginated("/examples",f)){for(let t of e){let{attachment_urls:e,...r}=t,n=r;e&&(n.attachments=Object.entries(e).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url},e),{})),yield n,m++}if(void 0!==s&&m>=s)break}}async deleteExample(e){tW(e);let t=`/examples/${e}`,r=await this.caller.call(tF(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(r,`delete ${t}`),await r.json()}async updateExample(e,t){tW(e);let r=await this.caller.call(tF(),`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(r,"update example"),await r.json()}async updateExamples(e){let t=await this.caller.call(tF(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(t,"update examples"),await t.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");tW(n=void 0===e?(await this.readDataset({datasetName:t})).id:e);let i=new URLSearchParams,o=r?"string"==typeof r?r:r?.toISOString():void 0;return o&&i.append("as_of",o),await this._get(`/datasets/${n}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:i=!1}){let o;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");tW(o=void 0===e?(await this.readDataset({datasetName:t})).id:e);let a={split_name:r,examples:n.map(e=>(tW(e),e)),remove:i},s=await this.caller.call(tF(),`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(s,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:i}={loadChildRuns:!1}){let o;if(tV("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)o=await this.readRun(e,{loadChildRuns:n});else if("object"==typeof e&&"id"in e)o=e;else throw Error(`Invalid run type: ${typeof e}`);null!==o.reference_example_id&&void 0!==o.reference_example_id&&(i=await this.readExample(o.reference_example_id));let a=await t.evaluateRun(o,i),[s,l]=await this._logEvaluationFeedback(a,o,r);return l[0]}async createFeedback(e,t,{score:r,value:n,correction:i,comment:o,sourceInfo:a,feedbackSourceType:s="api",sourceRunId:l,feedbackId:u,feedbackConfig:c,projectId:h,comparativeExperimentId:f}){if(!e&&!h)throw Error("One of runId or projectId must be provided");if(e&&h)throw Error("Only one of runId or projectId can be provided");let d={type:s??"api",metadata:a??{}};void 0===l||d?.metadata===void 0||d.metadata.__run||(d.metadata.__run={run_id:l}),d?.metadata!==void 0&&d.metadata.__run?.run_id!==void 0&&tW(d.metadata.__run.run_id);let p={id:u??tN.Z(),run_id:e,key:t,score:r,value:n,correction:i,comment:o,feedback_source:d,comparative_experiment_id:f,feedbackConfig:c,session_id:h},m=`${this.apiUrl}/feedback`,g=await this.caller.call(tF(),m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(g,"create feedback",!0),p}async updateFeedback(e,{score:t,value:r,correction:n,comment:i}){let o={};null!=t&&(o.score=t),null!=r&&(o.value=r),null!=n&&(o.correction=n),null!=i&&(o.comment=i),tW(e);let a=await this.caller.call(tF(),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(a,"update feedback",!0)}async readFeedback(e){tW(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){tW(e);let t=`/feedback/${e}`,r=await this.caller.call(tF(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(r,`delete ${t}`),await r.json()}async *listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){let n=new URLSearchParams;if(e&&n.append("run",e.join(",")),t)for(let e of t)n.append("key",e);if(r)for(let e of r)n.append("source",e);for await(let e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){let i={run_id:e,feedback_key:t,feedback_config:n};r?"string"==typeof r?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let o=await this.caller.call(tF(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await o.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:i,metadata:o,id:a}){if(0===t.length)throw Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw Error("A reference dataset is required");let s={id:a,name:e,experiment_ids:t,reference_dataset_id:r,description:i,created_at:(n??new Date)?.toISOString(),extra:{}};o&&(s.extra.metadata=o);let l=await this.caller.call(tF(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async *listPresignedFeedbackTokens(e){tW(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return"results"in e?e.results:[e]}async _logEvaluationFeedback(e,t,r){let n=this._selectEvalResults(e),i=[];for(let e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let o=null;e.targetRunId?o=e.targetRunId:t&&(o=t.id),i.push(await this.createFeedback(o,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:n,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[n,i]}async logEvaluationFeedback(e,t,r){let[n]=await this._logEvaluationFeedback(e,t,r);return n}async *listAnnotationQueues(e={}){let{queueIds:t,name:r,nameContains:n,limit:i}=e,o=new URLSearchParams;t&&t.forEach((e,t)=>{tW(e,`queueIds[${t}]`),o.append("ids",e)}),r&&o.append("name",r),n&&o.append("name_contains",n),o.append("limit",(void 0!==i?Math.min(i,100):100).toString());let a=0;for await(let e of this._getPaginated("/annotation-queues",o))if(yield*e,a++,void 0!==i&&a>=i)break}async createAnnotationQueue(e){let{name:t,description:r,queueId:n}=e,i={name:t,description:r,id:n||tN.Z()},o=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(i).filter(([e,t])=>void 0!==t))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(o,"create annotation queue"),await o.json()}async readAnnotationQueue(e){let t=await this.listAnnotationQueues({queueIds:[e]}).next();if(t.done)throw Error(`Annotation queue with ID ${e} not found`);return t.value}async updateAnnotationQueue(e,t){let{name:r,description:n}=t,i=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues/${tW(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:n}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(i,"update annotation queue")}async deleteAnnotationQueue(e){let t=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues/${tW(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){let r=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues/${tW(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map((e,t)=>tW(e,`runIds[${t}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){let r=`/annotation-queues/${tW(e,"queueId")}/run`,n=await this.caller.call(tF(),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(n,"get run from annotation queue"),await n.json()}async deleteRunFromAnnotationQueue(e,t){let r=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues/${tW(e,"queueId")}/runs/${tW(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){let t=await this.caller.call(tF(),`${this.apiUrl}/annotation-queues/${tW(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){let r=await this._getSettings();return Error(`Cannot ${e} for another tenant.
253
+ Message: ${o.detail.join("\n")}`);throw Error(`Failed to list shared examples: ${i.status} ${i.statusText}`)}return o.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:i=null,referenceDatasetId:o=null}){let a=n?"?upsert=true":"",s=`${this.apiUrl}/sessions${a}`,l=i||{};r&&(l.metadata=r);let u={name:e,extra:l,description:t};null!==o&&(u.reference_dataset_id=o);let c=await this.caller.call(y(),s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(c,"create project"),await c.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:i=null,endTime:o=null}){let a=`${this.apiUrl}/sessions/${e}`,s=i;n&&(s={...s||{},metadata:n});let l={name:t,extra:s,description:r,end_time:o?new Date(o).toISOString():null},u=await this.caller.call(y(),a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(u,"update project"),await u.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions",n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)E(e),r+=`/${e}`;else if(void 0!==t)n.append("name",t);else throw Error("Must provide projectName or projectId");let i=await this.caller.call(y(),`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let e=await i.json();if(!i.ok)return!1;if(Array.isArray(e))return e.length>0;return!0}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n,i="/sessions",o=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)E(e),i+=`/${e}`;else if(void 0!==t)o.append("name",t);else throw Error("Must provide projectName or projectId");void 0!==r&&o.append("include_stats",r.toString());let a=await this._get(i,o);if(Array.isArray(a)){if(0===a.length)throw Error(`Project[id=${e}, name=${t}] not found`);n=a[0]}else n=a;return n}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:n,referenceDatasetName:i,referenceFree:o,metadata:a}={}){let s=new URLSearchParams;if(void 0!==e)for(let t of e)s.append("id",t);if(void 0!==t&&s.append("name",t),void 0!==r&&s.append("name_contains",r),void 0!==n)s.append("reference_dataset",n);else if(void 0!==i){let e=await this.readDataset({datasetName:i});s.append("reference_dataset",e.id)}for await(let e of(void 0!==o&&s.append("reference_free",o.toString()),void 0!==a&&s.append("metadata",JSON.stringify(a)),this._getPaginated("/sessions",s)))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");E(r=void 0===e?(await this.readProject({projectName:t})).id:e);let n=await this.caller.call(y(),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(n,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:i,dataType:o,name:a}){let s=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),r.forEach(e=>{l.append("input_keys",e)}),n.forEach(e=>{l.append("output_keys",e)}),i&&l.append("description",i),o&&l.append("data_type",o),a&&l.append("name",a);let u=await this.caller.call(y(),s,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(u,"upload CSV"),await u.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:i,metadata:o}={}){let a={name:e,description:t,extra:o?{metadata:o}:void 0};r&&(a.data_type=r),n&&(a.inputs_schema_definition=n),i&&(a.outputs_schema_definition=i);let s=await this.caller.call(y(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(s,"create dataset"),await s.json()}async readDataset({datasetId:e,datasetName:t}){let r,n="/datasets",i=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)E(e),n+=`/${e}`;else if(void 0!==t)i.append("name",t);else throw Error("Must provide datasetName or datasetId");let o=await this._get(n,i);if(Array.isArray(o)){if(0===o.length)throw Error(`Dataset[id=${e}, name=${t}] not found`);r=o[0]}else r=o;return r}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:n}){let i=e;if(void 0===i&&void 0===t)throw Error("Must provide either datasetName or datasetId");if(void 0!==i&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");void 0===i&&(i=(await this.readDataset({datasetName:t})).id);let o=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof n?n:n.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let r="/datasets";if(void 0!==e);else if(void 0!==t)e=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide datasetName or datasetId");let n=await this._getResponse(`${r}/${e}/openai_ft`);return(await n.text()).trim().split("\n").map(e=>JSON.parse(e))}async *listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:i,metadata:o}={}){let a="/datasets",s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(let e of r)s.append("id",e);for await(let e of(void 0!==n&&s.append("name",n),void 0!==i&&s.append("name_contains",i),void 0!==o&&s.append("metadata",JSON.stringify(o)),this._getPaginated(a,s)))yield*e}async updateDataset(e){let{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let i=t??(await this.readDataset({datasetName:r})).id;E(i);let o=await this.caller.call(y(),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(o,"update dataset"),await o.json()}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(n=(await this.readDataset({datasetName:t})).id),void 0!==n)E(n),r+=`/${n}`;else throw Error("Must provide datasetName or datasetId");let i=await this.caller.call(y(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(i,`delete ${r}`),await i.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(n||t)if(n&&t)throw Error("Must provide either datasetName or datasetId, not both");else n||(n=(await this.readDataset({datasetName:t})).id);else throw Error("Must provide either datasetName or datasetId");E(n);let i={tag:r},o=await this.caller.call(y(),`${this.apiUrl}/datasets/${n}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(o,"index dataset"),await o.json()}async similarExamples(e,t,r,{filter:n}={}){let i={limit:r,inputs:e};void 0!==n&&(i.filter=n),E(t);let o=await this.caller.call(y(),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(o,"fetch similar examples"),(await o.json()).examples}async createExample(e,t,{datasetId:r,datasetName:n,createdAt:i,exampleId:o,metadata:a,split:s,sourceRunId:l}){let u=r;if(void 0===u&&void 0===n)throw Error("Must provide either datasetName or datasetId");if(void 0!==u&&void 0!==n)throw Error("Must provide either datasetName or datasetId, not both");void 0===u&&(u=(await this.readDataset({datasetName:n})).id);let c=i||new Date,h={dataset_id:u,inputs:e,outputs:t,created_at:c?.toISOString(),id:o,metadata:a,split:s,source_run_id:l},f=await this.caller.call(y(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(f,"create example"),await f.json()}async createExamples(e){let{inputs:t,outputs:r,metadata:n,sourceRunIds:i,exampleIds:o,datasetId:a,datasetName:s}=e,l=a;if(void 0===l&&void 0===s)throw Error("Must provide either datasetName or datasetId");if(void 0!==l&&void 0!==s)throw Error("Must provide either datasetName or datasetId, not both");void 0===l&&(l=(await this.readDataset({datasetName:s})).id);let u=t.map((t,a)=>({dataset_id:l,inputs:t,outputs:r?r[a]:void 0,metadata:n?n[a]:void 0,split:e.splits?e.splits[a]:void 0,id:o?o[a]:void 0,source_run_id:i?i[a]:void 0})),c=await this.caller.call(y(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(c,"create examples"),await c.json()}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){let n=e.map(e=>w(e)?x(e):e),i=w(t)?x(t):t;return this.createExample({input:n},{output:i},r)}async readExample(e){E(e);let t=`/examples/${e}`,{attachment_urls:r,...n}=await this._get(t),i=n;return r&&(i.attachments=Object.entries(r).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url},e),{})),i}async *listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:i,inlineS3Urls:o,metadata:a,limit:s,offset:l,filter:u,includeAttachments:c}={}){let h;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)h=e;else if(void 0!==t)h=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide a datasetName or datasetId");let f=new URLSearchParams({dataset:h}),d=n?"string"==typeof n?n:n?.toISOString():void 0;d&&f.append("as_of",d);let p=o??!0;if(f.append("inline_s3_urls",p.toString()),void 0!==r)for(let e of r)f.append("id",e);if(void 0!==i)for(let e of i)f.append("splits",e);if(void 0!==a){let e=JSON.stringify(a);f.append("metadata",e)}void 0!==s&&f.append("limit",s.toString()),void 0!==l&&f.append("offset",l.toString()),void 0!==u&&f.append("filter",u),!0===c&&["attachment_urls","outputs","metadata"].forEach(e=>f.append("select",e));let m=0;for await(let e of this._getPaginated("/examples",f)){for(let t of e){let{attachment_urls:e,...r}=t,n=r;e&&(n.attachments=Object.entries(e).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url},e),{})),yield n,m++}if(void 0!==s&&m>=s)break}}async deleteExample(e){E(e);let t=`/examples/${e}`,r=await this.caller.call(y(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(r,`delete ${t}`),await r.json()}async updateExample(e,t){E(e);let r=await this.caller.call(y(),`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(r,"update example"),await r.json()}async updateExamples(e){let t=await this.caller.call(y(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(t,"update examples"),await t.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");E(n=void 0===e?(await this.readDataset({datasetName:t})).id:e);let i=new URLSearchParams,o=r?"string"==typeof r?r:r?.toISOString():void 0;return o&&i.append("as_of",o),await this._get(`/datasets/${n}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:i=!1}){let o;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");E(o=void 0===e?(await this.readDataset({datasetName:t})).id:e);let a={split_name:r,examples:n.map(e=>(E(e),e)),remove:i},s=await this.caller.call(y(),`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(s,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:i}={loadChildRuns:!1}){let o;if(A("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)o=await this.readRun(e,{loadChildRuns:n});else if("object"==typeof e&&"id"in e)o=e;else throw Error(`Invalid run type: ${typeof e}`);null!==o.reference_example_id&&void 0!==o.reference_example_id&&(i=await this.readExample(o.reference_example_id));let a=await t.evaluateRun(o,i),[s,l]=await this._logEvaluationFeedback(a,o,r);return l[0]}async createFeedback(e,t,{score:r,value:n,correction:i,comment:o,sourceInfo:a,feedbackSourceType:s="api",sourceRunId:l,feedbackId:u,feedbackConfig:c,projectId:h,comparativeExperimentId:f}){if(!e&&!h)throw Error("One of runId or projectId must be provided");if(e&&h)throw Error("Only one of runId or projectId can be provided");let p={type:s??"api",metadata:a??{}};void 0===l||p?.metadata===void 0||p.metadata.__run||(p.metadata.__run={run_id:l}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&E(p.metadata.__run.run_id);let m={id:u??d.Z(),run_id:e,key:t,score:r,value:n,correction:i,comment:o,feedback_source:p,comparative_experiment_id:f,feedbackConfig:c,session_id:h},g=`${this.apiUrl}/feedback`,v=await this.caller.call(y(),g,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(v,"create feedback",!0),m}async updateFeedback(e,{score:t,value:r,correction:n,comment:i}){let o={};null!=t&&(o.score=t),null!=r&&(o.value=r),null!=n&&(o.correction=n),null!=i&&(o.comment=i),E(e);let a=await this.caller.call(y(),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(a,"update feedback",!0)}async readFeedback(e){E(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){E(e);let t=`/feedback/${e}`,r=await this.caller.call(y(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(r,`delete ${t}`),await r.json()}async *listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){let n=new URLSearchParams;if(e&&n.append("run",e.join(",")),t)for(let e of t)n.append("key",e);if(r)for(let e of r)n.append("source",e);for await(let e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){let i={run_id:e,feedback_key:t,feedback_config:n};r?"string"==typeof r?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let o=await this.caller.call(y(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await o.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:i,metadata:o,id:a}){if(0===t.length)throw Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw Error("A reference dataset is required");let s={id:a,name:e,experiment_ids:t,reference_dataset_id:r,description:i,created_at:(n??new Date)?.toISOString(),extra:{}};o&&(s.extra.metadata=o);let l=await this.caller.call(y(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async *listPresignedFeedbackTokens(e){E(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return"results"in e?e.results:[e]}async _logEvaluationFeedback(e,t,r){let n=this._selectEvalResults(e),i=[];for(let e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let o=null;e.targetRunId?o=e.targetRunId:t&&(o=t.id),i.push(await this.createFeedback(o,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:n,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[n,i]}async logEvaluationFeedback(e,t,r){let[n]=await this._logEvaluationFeedback(e,t,r);return n}async *listAnnotationQueues(e={}){let{queueIds:t,name:r,nameContains:n,limit:i}=e,o=new URLSearchParams;t&&t.forEach((e,t)=>{E(e,`queueIds[${t}]`),o.append("ids",e)}),r&&o.append("name",r),n&&o.append("name_contains",n),o.append("limit",(void 0!==i?Math.min(i,100):100).toString());let a=0;for await(let e of this._getPaginated("/annotation-queues",o))if(yield*e,a++,void 0!==i&&a>=i)break}async createAnnotationQueue(e){let{name:t,description:r,queueId:n}=e,i={name:t,description:r,id:n||d.Z()},o=await this.caller.call(y(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(i).filter(([e,t])=>void 0!==t))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(o,"create annotation queue"),await o.json()}async readAnnotationQueue(e){let t=await this.listAnnotationQueues({queueIds:[e]}).next();if(t.done)throw Error(`Annotation queue with ID ${e} not found`);return t.value}async updateAnnotationQueue(e,t){let{name:r,description:n}=t,i=await this.caller.call(y(),`${this.apiUrl}/annotation-queues/${E(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:n}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(i,"update annotation queue")}async deleteAnnotationQueue(e){let t=await this.caller.call(y(),`${this.apiUrl}/annotation-queues/${E(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){let r=await this.caller.call(y(),`${this.apiUrl}/annotation-queues/${E(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map((e,t)=>E(e,`runIds[${t}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){let r=`/annotation-queues/${E(e,"queueId")}/run`,n=await this.caller.call(y(),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(n,"get run from annotation queue"),await n.json()}async deleteRunFromAnnotationQueue(e,t){let r=await this.caller.call(y(),`${this.apiUrl}/annotation-queues/${E(e,"queueId")}/runs/${E(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){let t=await this.caller.call(y(),`${this.apiUrl}/annotation-queues/${E(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){let r=await this._getSettings();return Error(`Cannot ${e} for another tenant.
254
254
 
255
255
  Current tenant: ${r.tenant_handle}
256
256
 
257
- Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await this.caller.call(tF(),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){let e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),n=Error(`Error ${t.status}: ${t.statusText}
258
- ${e}`);throw n.statusCode=t.status,n}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[r,n,i]=tX(e),o=await this.caller.call(tF(),`${this.apiUrl}/likes/${r}/${n}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(o,`${t?"like":"unlike"} prompt`),await o.json()}async _getPromptUrl(e){let[t,r,n]=tX(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return"latest"!==n?`${this.getHostUrl()}/prompts/${r}/${n.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==n?`${this.getHostUrl()}/hub/${t}/${r}/${n.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async *listCommits(e){for await(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async *listPrompts(e){let t=new URLSearchParams;for await(let r of(t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query),this._getPaginated("/repos",t,e=>e.repos)))yield*r}async getPrompt(e){let[t,r,n]=tX(e),i=await this.caller.call(tF(),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===i.status)return null;await tK(i,"get prompt");let o=await i.json();return o.repo?o.repo:null}async createPrompt(e,t){let r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw Error(`Cannot create a public prompt without first
257
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await this.caller.call(y(),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){let e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),n=Error(`Error ${t.status}: ${t.statusText}
258
+ ${e}`);throw n.statusCode=t.status,n}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[r,n,i]=k(e),o=await this.caller.call(y(),`${this.apiUrl}/likes/${r}/${n}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(o,`${t?"like":"unlike"} prompt`),await o.json()}async _getPromptUrl(e){let[t,r,n]=k(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return"latest"!==n?`${this.getHostUrl()}/prompts/${r}/${n.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==n?`${this.getHostUrl()}/hub/${t}/${r}/${n.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async *listCommits(e){for await(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async *listPrompts(e){let t=new URLSearchParams;for await(let r of(t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query),this._getPaginated("/repos",t,e=>e.repos)))yield*r}async getPrompt(e){let[t,r,n]=k(e),i=await this.caller.call(y(),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===i.status)return null;await T(i,"get prompt");let o=await i.json();return o.repo?o.repo:null}async createPrompt(e,t){let r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw Error(`Cannot create a public prompt without first
259
259
 
260
260
  creating a LangChain Hub handle.
261
261
  You can add a handle by creating a public prompt at:
262
262
 
263
- https://smith.langchain.com/prompts`);let[n,i,o]=tX(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);let a={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=await this.caller.call(tF(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(s,"create prompt");let{repo:l}=await s.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[n,i,o]=tX(e),a=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${i}`),s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:a},l=await this.caller.call(tF(),`${this.apiUrl}/commits/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(l,"create commit");let u=await l.json();return this._getPromptUrl(`${n}/${i}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=e.id,n=new Blob([t3({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}})],{type:"application/json"});if(r.append(t,n),e.inputs){let n=new Blob([t3(e.inputs)],{type:"application/json"});r.append(`${t}.inputs`,n)}if(e.outputs){let n=new Blob([t3(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(let[n,i]of Object.entries(e.attachments)){let e,o;Array.isArray(i)?[e,o]=i:(e=i.mimeType,o=i.data);let a=new Blob([o],{type:`${e}; length=${o.byteLength}`});r.append(`${t}.attachment.${n}`,a)}if(e.attachments_operations){let n=new Blob([t3(e.attachments_operations)],{type:"application/json"});r.append(`${t}.attachments_operations`,n)}}let n=await this.caller.call(tF(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"PATCH",headers:this.headers,body:r});return await n.json()}async uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=(e.id??tN.Z()).toString(),n=new Blob([t3({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}})],{type:"application/json"});r.append(t,n);let i=new Blob([t3(e.inputs)],{type:"application/json"});if(r.append(`${t}.inputs`,i),e.outputs){let n=new Blob([t3(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(let[n,i]of Object.entries(e.attachments)){let e,o;Array.isArray(i)?[e,o]=i:(e=i.mimeType,o=i.data);let a=new Blob([o],{type:`${e}; length=${o.byteLength}`});r.append(`${t}.attachment.${n}`,a)}}let n=await this.caller.call(tF(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});return await n.json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,n]=tX(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw Error("No valid update options provided");let o=await this.caller.call(tF(),`${this.apiUrl}/repos/${r}/${n}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tK(o,"update prompt"),o.json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,n]=tX(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);let i=await this.caller.call(tF(),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async pullPromptCommit(e,t){let[r,n,i]=tX(e),o=await this.caller.call(tF(),`${this.apiUrl}/commits/${r}/${n}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await tK(o,"pull prompt commit");let a=await o.json();return{owner:r,repo:n,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[i,o]=this.parseTokenOrUrl(e,r),a=new ra({apiUrl:i,apiKey:"placeholder"}),s=await a.readSharedDataset(o),l=n||s.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(e){}let u=await a.listSharedExamples(o),c=await this.createDataset(l,{description:s.description,dataType:s.data_type||"kv",inputsSchema:s.inputs_schema_definition??void 0,outputsSchema:s.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:c.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return tW(e),[t,e]}catch(e){}try{let i=new URL(e).pathname.split("/").filter(e=>""!==e);if(i.length>=r){let e=i[i.length-r];return[t,e]}throw Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw Error(`Invalid public ${n} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()])}}let rs="0.2.15";var rl=r(73656);let ru=()=>"undefined"!=typeof window&&void 0!==window.document,rc=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,rh=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),rf=()=>"undefined"!=typeof Deno,rd=()=>void 0!==rl&&void 0!==rl.versions&&void 0!==rl.versions.node&&!rf(),rp=()=>i||(i=ru()?"browser":rd()?"node":rc()?"webworker":rh()?"jsdom":rf()?"deno":"other");function rm(){return void 0===o&&(o={library:"langsmith",runtime:rp(),sdk:"langsmith-js",sdk_version:rs,...r_()}),o}function rg(){let e=ry()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(e))(n.startsWith("LANGCHAIN_")||n.startsWith("LANGSMITH_"))&&"string"==typeof i&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&("LANGCHAIN_REVISION_ID"===n?t.revision_id=i:t[n]=i);return t}function ry(){try{if(void 0!==rl&&rl.env)return Object.entries(rl.env).reduce((e,[t,r])=>(e[t]=String(r),e),{});return}catch(e){return}}function rv(e){try{return void 0!==rl?rl.env?.[e]:void 0}catch(e){return}}function rb(e){return rv(`LANGSMITH_${e}`)||rv(`LANGCHAIN_${e}`)}function r_(){if(void 0!==a)return a;let e={};for(let t of["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"]){let r=rv(t);void 0!==r&&(e[t]=r)}return a=e,e}let rw=e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find(e=>"true"===rb(e)),rx=Symbol.for("lc:context_variables");function rS(e){return e.replace(/[-:.]/g,"")}function rE(e,t,r=1){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return rS(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}class rC{constructor(e,t){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t}static fromHeader(e){let t=e.split(","),r={},n=[];for(let e of t){let[t,i]=e.split("="),o=decodeURIComponent(i);"langsmith-metadata"===t?r=JSON.parse(o):"langsmith-tags"===t&&(n=o.split(","))}return new rC(r,n)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),e.join(",")}}class rA{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),rk(e))return void Object.assign(this,{...e});let t=rA.getDefaultConfig(),{metadata:r,...n}=e,i=n.client??rA.getSharedClient(),o={...r,...n?.extra?.metadata};if(n.extra={...n.extra,metadata:o},Object.assign(this,{...t,...n,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let e=rE(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:tN.Z(),run_type:"chain",project_name:rv("LANGCHAIN_PROJECT")??rv("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:rv("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:rv("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return rA.sharedClient||(rA.sharedClient=new ra),rA.sharedClient}createChild(e){let t=this.child_execution_order+1,r=new rA({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});rx in this&&(r[rx]=this[rx]);let n=Symbol.for("lc:child_config"),i=e.extra?.[n]??this.extra[n];if(rP(i)){let e={...i},t=rI(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(rO)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}let o=new Set,a=this;for(;null!=a&&!o.has(a.id);)o.add(a.id),a.child_execution_order=Math.max(a.child_execution_order,t),a=a.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),n){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,n&&Object.keys(n).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...n}}:{metadata:n})}_convertToCreate(e,t,r=!0){let n,i,o=e.extra??{};if(o.runtime||(o.runtime={}),t)for(let[e,r]of Object.entries(t))o.runtime[e]||(o.runtime[e]=r);return r?(i=e.parent_run?.id,n=[]):(n=e.child_runs.map(e=>this._convertToCreate(e,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:o,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:n,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{let t=rm(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e)for(let e of(tV("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1)}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{let e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(e,t){let r,n,i,o=e?.callbacks,a=rw();if(o){let e=o?.getParentRunId?.()??"",t=o?.handlers?.find(e=>e?.name=="langchain_tracer");r=t?.getRun?.(e),n=t?.projectName,i=t?.client,a=a||!!t}return r?new rA({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:a,project_name:n,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new rA({...t,client:i,tracingEnabled:a,project_name:n})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,n=r["langsmith-trace"];if(!n||"string"!=typeof n)return;let i=n.trim(),o=i.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),a=o[0].uuid,s={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:a,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){let e=rC.fromHeader(r.baggage);s.metadata=e.metadata,s.tags=e.tags}return new rA(s)}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new rC(this.extra?.metadata,this.tags).toHeader()};if(e)for(let[r,n]of Object.entries(t))e.set(r,n);return t}}function rk(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function rO(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function rT(e){return Array.isArray(e)&&e.some(e=>rO(e))}function rI(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}function rP(e){return void 0!==e&&"object"==typeof e.callbacks&&(rT(e.callbacks?.handlers)||rT(e.callbacks))}Object.defineProperty(rA,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});class rR{getStore(){}run(e,t){return t()}}let rM=Symbol.for("ls:tracing_async_local_storage"),r$=new rR;class rN{getInstance(){return globalThis[rM]??r$}initializeGlobalInstance(e){void 0===globalThis[rM]&&(globalThis[rM]=e)}}let rj=new rN,rB=()=>{let e=rj.getInstance().getStore();if(!rk(e))throw Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function or the tracing is enabled.");return e};function rL(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root");let rF=Object.prototype.hasOwnProperty;function rD(e,t){return rF.call(e,t)}function rz(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)rD(e,r)&&t.push(r);return t}function rU(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function rZ(e){let t,r=0,n=e.length;for(;r<n;){if((t=e.charCodeAt(r))>=48&&t<=57){r++;continue}return!1}return!0}function rH(e){return -1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function rG(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function rW(e){if(void 0===e)return!0;if(e){if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(rW(e[t]))return!0}else if("object"==typeof e){let r=rz(e),n=r.length;for(var t=0;t<n;t++)if(rW(e[r[t]]))return!0}}return!1}function rq(e,t){let r=[e];for(let e in t){let n="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==n&&r.push(`${e}: ${n}`)}return r.join("\n")}class rV extends Error{constructor(e,t,r,n,i){super(rq(e,{name:t,index:r,operation:n,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=rq(e,{name:t,index:r,operation:n,tree:i})}}let rX=rV,rY=rU,rK={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=rQ(r,this.path);n&&(n=rU(n));let i=r0(r,{op:"remove",path:this.from}).removed;return r0(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=rQ(r,this.from);return r0(r,{op:"add",path:this.path,value:rU(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:r4(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var rJ={add:function(e,t,r){return rZ(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:rK.move,copy:rK.copy,test:rK.test,_get:rK._get};function rQ(e,t){if(""==t)return e;var r={op:"_get",path:t};return r0(e,r),r.value}function r0(e,t,r=!1,n=!0,i=!0,o=0){if(r&&("function"==typeof r?r(t,0,e,t.path):r3(t,0)),""===t.path){let n={newDocument:e};if("add"===t.op)return n.newDocument=t.value,n;if("replace"===t.op)return n.newDocument=t.value,n.removed=e,n;if("move"===t.op||"copy"===t.op)return n.newDocument=rQ(e,t.from),"move"===t.op&&(n.removed=e),n;else if("test"===t.op){if(n.test=r4(e,t.value),!1===n.test)throw new rX("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n.newDocument=e,n}else if("remove"===t.op)return n.removed=e,n.newDocument=null,n;else if("_get"===t.op)return t.value=e,n;else if(!r)return n;else throw new rX("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,t,e)}{let a,s,l;n||(e=rU(e));let u=(t.path||"").split("/"),c=e,h=1,f=u.length;for(s="function"==typeof r?r:r3;;){if((a=u[h])&&-1!=a.indexOf("~")&&(a=rG(a)),i&&("__proto__"==a||"prototype"==a&&h>0&&"constructor"==u[h-1]))throw 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&&void 0===l&&(void 0===c[a]?l=u.slice(0,h).join("/"):h==f-1&&(l=t.path),void 0!==l&&s(t,0,e,l)),h++,Array.isArray(c)){if("-"===a)a=c.length;else if(r&&!rZ(a))throw new rX("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",o,t,e);else rZ(a)&&(a=~~a);if(h>=f){if(r&&"add"===t.op&&a>c.length)throw new rX("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,t,e);let n=rJ[t.op].call(t,c,a,e);if(!1===n.test)throw new rX("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n}}else if(h>=f){let r=rK[t.op].call(t,c,a,e);if(!1===r.test)throw new rX("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r}if(c=c[a],r&&h<f&&(!c||"object"!=typeof c))throw new rX("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,t,e)}}}function r1(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new rX("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=rU(e));let o=Array(t.length);for(let n=0,a=t.length;n<a;n++)o[n]=r0(e,t[n],r,!0,i,n),e=o[n].newDocument;return o.newDocument=e,o}function r2(e,t,r){let n=r0(e,t);if(!1===n.test)throw new rX("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function r3(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new rX("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(rK[e.op]){if("string"!=typeof e.path)throw new rX("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);else if(0!==e.path.indexOf("/")&&e.path.length>0)throw new rX('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new rX("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new rX("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&rW(e.value))throw new rX("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new rX("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new rX("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var a=r5([{op:"_get",path:e.from,value:void 0}],r);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new rX("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new rX("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function r5(e,t,r){try{if(!Array.isArray(e))throw new rX("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)r1(rU(t),rU(e),r||!0);else{r=r||r3;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(e){if(e instanceof rX)return e;throw e}}function r4(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,n,i,o=Array.isArray(e),a=Array.isArray(t);if(o&&a){if((n=e.length)!=t.length)return!1;for(r=n;0!=r--;)if(!r4(e[r],t[r]))return!1;return!0}if(o!=a)return!1;var s=Object.keys(e);if((n=s.length)!==Object.keys(t).length)return!1;for(r=n;0!=r--;)if(!t.hasOwnProperty(s[r]))return!1;for(r=n;0!=r--;)if(!r4(e[i=s[r]],t[i]))return!1;return!0}return e!=e&&t!=t}new WeakMap;var r6=r(59975),r8=r(73656);let r9=()=>"undefined"!=typeof window&&void 0!==window.document,r7=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,ne=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),nt=()=>"undefined"!=typeof Deno,nr=()=>void 0!==r8&&void 0!==r8.versions&&void 0!==r8.versions.node&&!nt(),nn=()=>{let e;return r9()?"browser":nr()?"node":r7()?"webworker":ne()?"jsdom":nt()?"deno":"other"};async function ni(){return void 0===s&&(s={library:"langchain-js",runtime:nn()}),s}function no(e){try{if(void 0!==r8)return r8.env?.[e];if(nt())return Deno?.env.get(e);return}catch(e){return}}class na{}class ns extends na{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,(0,r6.j)(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:"false"===no("LANGCHAIN_CALLBACKS_BACKGROUND")}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return r6.i.prototype.toJSON.call(this)}toJSONNotImplemented(){return r6.i.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends ns{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:tN.Z()}),Object.assign(this,e)}}return new t}}let nl=e=>{let t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers};function nu(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function nc(e){return e.replace(/[-:.]/g,"")}function nh(e,t,r){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return nc(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}function nf(e){return"function"==typeof e._addRunToRunMap}class nd extends ns{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
263
+ https://smith.langchain.com/prompts`);let[n,i,o]=k(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);let a={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=await this.caller.call(y(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(s,"create prompt");let{repo:l}=await s.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[n,i,o]=k(e),a=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${i}`),s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:a},l=await this.caller.call(y(),`${this.apiUrl}/commits/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(l,"create commit");let u=await l.json();return this._getPromptUrl(`${n}/${i}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=e.id,n=new Blob([N({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}})],{type:"application/json"});if(r.append(t,n),e.inputs){let n=new Blob([N(e.inputs)],{type:"application/json"});r.append(`${t}.inputs`,n)}if(e.outputs){let n=new Blob([N(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(let[n,i]of Object.entries(e.attachments)){let e,o;Array.isArray(i)?[e,o]=i:(e=i.mimeType,o=i.data);let a=new Blob([o],{type:`${e}; length=${o.byteLength}`});r.append(`${t}.attachment.${n}`,a)}if(e.attachments_operations){let n=new Blob([N(e.attachments_operations)],{type:"application/json"});r.append(`${t}.attachments_operations`,n)}}let n=await this.caller.call(y(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"PATCH",headers:this.headers,body:r});return await n.json()}async uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=(e.id??d.Z()).toString(),n=new Blob([N({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}})],{type:"application/json"});r.append(t,n);let i=new Blob([N(e.inputs)],{type:"application/json"});if(r.append(`${t}.inputs`,i),e.outputs){let n=new Blob([N(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(let[n,i]of Object.entries(e.attachments)){let e,o;Array.isArray(i)?[e,o]=i:(e=i.mimeType,o=i.data);let a=new Blob([o],{type:`${e}; length=${o.byteLength}`});r.append(`${t}.attachment.${n}`,a)}}let n=await this.caller.call(y(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});return await n.json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,n]=k(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw Error("No valid update options provided");let o=await this.caller.call(y(),`${this.apiUrl}/repos/${r}/${n}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await T(o,"update prompt"),o.json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,n]=k(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);let i=await this.caller.call(y(),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async pullPromptCommit(e,t){let[r,n,i]=k(e),o=await this.caller.call(y(),`${this.apiUrl}/commits/${r}/${n}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await T(o,"pull prompt commit");let a=await o.json();return{owner:r,repo:n,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[i,o]=this.parseTokenOrUrl(e,r),a=new V({apiUrl:i,apiKey:"placeholder"}),s=await a.readSharedDataset(o),l=n||s.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(e){}let u=await a.listSharedExamples(o),c=await this.createDataset(l,{description:s.description,dataType:s.data_type||"kv",inputsSchema:s.inputs_schema_definition??void 0,outputsSchema:s.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:c.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return E(e),[t,e]}catch(e){}try{let i=new URL(e).pathname.split("/").filter(e=>""!==e);if(i.length>=r){let e=i[i.length-r];return[t,e]}throw Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw Error(`Invalid public ${n} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()])}}let X="0.2.15";var Y=r(73656);let K=()=>"undefined"!=typeof window&&void 0!==window.document,J=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,Q=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),ee=()=>"undefined"!=typeof Deno,et=()=>void 0!==Y&&void 0!==Y.versions&&void 0!==Y.versions.node&&!ee(),er=()=>n||(n=K()?"browser":et()?"node":J()?"webworker":Q()?"jsdom":ee()?"deno":"other");function en(){return void 0===i&&(i={library:"langsmith",runtime:er(),sdk:"langsmith-js",sdk_version:X,...el()}),i}function ei(){let e=eo()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(e))(n.startsWith("LANGCHAIN_")||n.startsWith("LANGSMITH_"))&&"string"==typeof i&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&("LANGCHAIN_REVISION_ID"===n?t.revision_id=i:t[n]=i);return t}function eo(){try{if(void 0!==Y&&Y.env)return Object.entries(Y.env).reduce((e,[t,r])=>(e[t]=String(r),e),{});return}catch(e){return}}function ea(e){try{return void 0!==Y?Y.env?.[e]:void 0}catch(e){return}}function es(e){return ea(`LANGSMITH_${e}`)||ea(`LANGCHAIN_${e}`)}function el(){if(void 0!==o)return o;let e={};for(let t of["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"]){let r=ea(t);void 0!==r&&(e[t]=r)}return o=e,e}let eu=e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find(e=>"true"===es(e)),ec=Symbol.for("lc:context_variables");function eh(e){return e.replace(/[-:.]/g,"")}function ef(e,t,r=1){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return eh(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}class ed{constructor(e,t){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t}static fromHeader(e){let t=e.split(","),r={},n=[];for(let e of t){let[t,i]=e.split("="),o=decodeURIComponent(i);"langsmith-metadata"===t?r=JSON.parse(o):"langsmith-tags"===t&&(n=o.split(","))}return new ed(r,n)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),e.join(",")}}class ep{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),em(e))return void Object.assign(this,{...e});let t=ep.getDefaultConfig(),{metadata:r,...n}=e,i=n.client??ep.getSharedClient(),o={...r,...n?.extra?.metadata};if(n.extra={...n.extra,metadata:o},Object.assign(this,{...t,...n,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let e=ef(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:d.Z(),run_type:"chain",project_name:ea("LANGCHAIN_PROJECT")??ea("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:ea("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ea("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ep.sharedClient||(ep.sharedClient=new V),ep.sharedClient}createChild(e){let t=this.child_execution_order+1,r=new ep({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});ec in this&&(r[ec]=this[ec]);let n=Symbol.for("lc:child_config"),i=e.extra?.[n]??this.extra[n];if(eb(i)){let e={...i},t=ev(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(eg)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}let o=new Set,a=this;for(;null!=a&&!o.has(a.id);)o.add(a.id),a.child_execution_order=Math.max(a.child_execution_order,t),a=a.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),n){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,n&&Object.keys(n).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...n}}:{metadata:n})}_convertToCreate(e,t,r=!0){let n,i,o=e.extra??{};if(o.runtime||(o.runtime={}),t)for(let[e,r]of Object.entries(t))o.runtime[e]||(o.runtime[e]=r);return r?(i=e.parent_run?.id,n=[]):(n=e.child_runs.map(e=>this._convertToCreate(e,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:o,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:n,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{let t=en(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e)for(let e of(A("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1)}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{let e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(e,t){let r,n,i,o=e?.callbacks,a=eu();if(o){let e=o?.getParentRunId?.()??"",t=o?.handlers?.find(e=>e?.name=="langchain_tracer");r=t?.getRun?.(e),n=t?.projectName,i=t?.client,a=a||!!t}return r?new ep({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:a,project_name:n,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new ep({...t,client:i,tracingEnabled:a,project_name:n})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,n=r["langsmith-trace"];if(!n||"string"!=typeof n)return;let i=n.trim(),o=i.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),a=o[0].uuid,s={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:a,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){let e=ed.fromHeader(r.baggage);s.metadata=e.metadata,s.tags=e.tags}return new ep(s)}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new ed(this.extra?.metadata,this.tags).toHeader()};if(e)for(let[r,n]of Object.entries(t))e.set(r,n);return t}}function em(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function eg(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function ey(e){return Array.isArray(e)&&e.some(e=>eg(e))}function ev(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}function eb(e){return void 0!==e&&"object"==typeof e.callbacks&&(ey(e.callbacks?.handlers)||ey(e.callbacks))}Object.defineProperty(ep,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});class e_{getStore(){}run(e,t){return t()}}let ew=Symbol.for("ls:tracing_async_local_storage"),ex=new e_;class eS{getInstance(){return globalThis[ew]??ex}initializeGlobalInstance(e){void 0===globalThis[ew]&&(globalThis[ew]=e)}}let eE=new eS,eC=()=>{let e=eE.getInstance().getStore();if(!em(e))throw Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function or the tracing is enabled.");return e};function eA(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root");let ek=Object.prototype.hasOwnProperty;function eO(e,t){return ek.call(e,t)}function eT(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)eO(e,r)&&t.push(r);return t}function eI(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function eP(e){let t,r=0,n=e.length;for(;r<n;){if((t=e.charCodeAt(r))>=48&&t<=57){r++;continue}return!1}return!0}function eR(e){return -1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function eM(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function e$(e){if(void 0===e)return!0;if(e){if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(e$(e[t]))return!0}else if("object"==typeof e){let r=eT(e),n=r.length;for(var t=0;t<n;t++)if(e$(e[r[t]]))return!0}}return!1}function eN(e,t){let r=[e];for(let e in t){let n="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==n&&r.push(`${e}: ${n}`)}return r.join("\n")}class ej extends Error{constructor(e,t,r,n,i){super(eN(e,{name:t,index:r,operation:n,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=eN(e,{name:t,index:r,operation:n,tree:i})}}let eB=ej,eL=eI,eF={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=ez(r,this.path);n&&(n=eI(n));let i=eU(r,{op:"remove",path:this.from}).removed;return eU(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=ez(r,this.from);return eU(r,{op:"add",path:this.path,value:eI(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:eq(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var eD={add:function(e,t,r){return eP(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:eF.move,copy:eF.copy,test:eF.test,_get:eF._get};function ez(e,t){if(""==t)return e;var r={op:"_get",path:t};return eU(e,r),r.value}function eU(e,t,r=!1,n=!0,i=!0,o=0){if(r&&("function"==typeof r?r(t,0,e,t.path):eG(t,0)),""===t.path){let n={newDocument:e};if("add"===t.op)return n.newDocument=t.value,n;if("replace"===t.op)return n.newDocument=t.value,n.removed=e,n;if("move"===t.op||"copy"===t.op)return n.newDocument=ez(e,t.from),"move"===t.op&&(n.removed=e),n;else if("test"===t.op){if(n.test=eq(e,t.value),!1===n.test)throw new eB("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n.newDocument=e,n}else if("remove"===t.op)return n.removed=e,n.newDocument=null,n;else if("_get"===t.op)return t.value=e,n;else if(!r)return n;else throw new eB("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,t,e)}{let a,s,l;n||(e=eI(e));let u=(t.path||"").split("/"),c=e,h=1,f=u.length;for(s="function"==typeof r?r:eG;;){if((a=u[h])&&-1!=a.indexOf("~")&&(a=eM(a)),i&&("__proto__"==a||"prototype"==a&&h>0&&"constructor"==u[h-1]))throw 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&&void 0===l&&(void 0===c[a]?l=u.slice(0,h).join("/"):h==f-1&&(l=t.path),void 0!==l&&s(t,0,e,l)),h++,Array.isArray(c)){if("-"===a)a=c.length;else if(r&&!eP(a))throw new eB("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",o,t,e);else eP(a)&&(a=~~a);if(h>=f){if(r&&"add"===t.op&&a>c.length)throw new eB("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,t,e);let n=eD[t.op].call(t,c,a,e);if(!1===n.test)throw new eB("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n}}else if(h>=f){let r=eF[t.op].call(t,c,a,e);if(!1===r.test)throw new eB("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r}if(c=c[a],r&&h<f&&(!c||"object"!=typeof c))throw new eB("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,t,e)}}}function eZ(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new eB("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=eI(e));let o=Array(t.length);for(let n=0,a=t.length;n<a;n++)o[n]=eU(e,t[n],r,!0,i,n),e=o[n].newDocument;return o.newDocument=e,o}function eH(e,t,r){let n=eU(e,t);if(!1===n.test)throw new eB("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function eG(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new eB("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(eF[e.op]){if("string"!=typeof e.path)throw new eB("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);else if(0!==e.path.indexOf("/")&&e.path.length>0)throw new eB('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new eB("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new eB("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&e$(e.value))throw new eB("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new eB("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new eB("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var a=eW([{op:"_get",path:e.from,value:void 0}],r);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new eB("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new eB("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function eW(e,t,r){try{if(!Array.isArray(e))throw new eB("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)eZ(eI(t),eI(e),r||!0);else{r=r||eG;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(e){if(e instanceof eB)return e;throw e}}function eq(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,n,i,o=Array.isArray(e),a=Array.isArray(t);if(o&&a){if((n=e.length)!=t.length)return!1;for(r=n;0!=r--;)if(!eq(e[r],t[r]))return!1;return!0}if(o!=a)return!1;var s=Object.keys(e);if((n=s.length)!==Object.keys(t).length)return!1;for(r=n;0!=r--;)if(!t.hasOwnProperty(s[r]))return!1;for(r=n;0!=r--;)if(!eq(e[i=s[r]],t[i]))return!1;return!0}return e!=e&&t!=t}new WeakMap;var eV=r(59975),eX=r(73656);let eY=()=>"undefined"!=typeof window&&void 0!==window.document,eK=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,eJ=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),eQ=()=>"undefined"!=typeof Deno,e0=()=>void 0!==eX&&void 0!==eX.versions&&void 0!==eX.versions.node&&!eQ(),e1=()=>{let e;return eY()?"browser":e0()?"node":eK()?"webworker":eJ()?"jsdom":eQ()?"deno":"other"};async function e2(){return void 0===a&&(a={library:"langchain-js",runtime:e1()}),a}function e3(e){try{if(void 0!==eX)return eX.env?.[e];if(eQ())return Deno?.env.get(e);return}catch(e){return}}class e5{}class e4 extends e5{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,(0,eV.j)(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:"false"===e3("LANGCHAIN_CALLBACKS_BACKGROUND")}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return eV.i.prototype.toJSON.call(this)}toJSONNotImplemented(){return eV.i.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends e4{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:d.Z()}),Object.assign(this,e)}}return new t}}let e6=e=>{let t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers};function e8(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function e9(e){return e.replace(/[-:.]/g,"")}function e7(e,t,r){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return e9(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}function te(e){return"function"==typeof e._addRunToRunMap}class tt extends e4{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
264
264
 
265
- ${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let t=nh(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){let e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c=a?{...i,metadata:a}:i,h={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:o||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c=a?{...i,metadata:a}:i,h={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:o||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM run to end.");return r.end_time=Date.now(),r.outputs=e,r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onLLMEnd?.(r),await this._endTrace(r),r}async handleLLMError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM run to end.");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onLLMError?.(r),await this._endTrace(r),r}_createRunForChainStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:a??"chain",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForChainStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,n,i){let o=this.runMap.get(t);if(!o)throw Error("No chain run to end.");return o.end_time=Date.now(),o.outputs=nu(e,"output"),o.events.push({name:"end",time:new Date(o.end_time).toISOString()}),i?.inputs!==void 0&&(o.inputs=nu(i.inputs,"input")),await this.onChainEnd?.(o),await this._endTrace(o),o}async handleChainError(e,t,r,n,i){let o=this.runMap.get(t);if(!o)throw Error("No chain run to end.");return o.end_time=Date.now(),o.error=this.stringifyError(e),o.events.push({name:"error",time:new Date(o.end_time).toISOString()}),i?.inputs!==void 0&&(o.inputs=nu(i.inputs,"input")),await this.onChainError?.(o),await this._endTrace(o),o}_createRunForToolStart(e,t,r,n,i,o,a){let s=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:"tool",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,n,i,o,a){let s=this.runMap.get(r)??this._createRunForToolStart(e,t,r,n,i,o,a);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.runMap.get(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,n,i,o,a){let s=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:"retriever",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,n,i,o,a){let s=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,n,i,o,a);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.runMap.get(t);r&&r?.run_type==="chain"&&(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,n,i,o){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:o?.chunk}}),await this.onLLMNewToken?.(a,e,{chunk:o?.chunk}),a}}var np=r(8300);function nm(e,t){return`${e.open}${t}${e.close}`}function ng(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function ny(e){return"string"==typeof e?e.trim():null==e?e:ng(e,e.toString())}function nv(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:nb}=np;class n_ extends nd{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let n=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?nm(np.bold,n):n}).join(" > ");return nm(nb.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.green,"[chain/start]")} [${t}] Entering Chain run with input: ${ng(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.cyan,"[chain/end]")} [${t}] [${nv(e)}] Exiting Chain run with output: ${ng(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.red,"[chain/error]")} [${t}] [${nv(e)}] Chain run errored with error: ${ng(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${nm(nb.green,"[llm/start]")} [${t}] Entering LLM run with input: ${ng(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.cyan,"[llm/end]")} [${t}] [${nv(e)}] Exiting LLM run with output: ${ng(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.red,"[llm/error]")} [${t}] [${nv(e)}] LLM run errored with error: ${ng(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.green,"[tool/start]")} [${t}] Entering Tool run with input: "${ny(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.cyan,"[tool/end]")} [${t}] [${nv(e)}] Exiting Tool run with output: "${ny(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.red,"[tool/error]")} [${t}] [${nv(e)}] Tool run errored with error: ${ng(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${ng(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.cyan,"[retriever/end]")} [${t}] [${nv(e)}] Exiting Retriever run with output: ${ng(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${nm(nb.red,"[retriever/error]")} [${t}] [${nv(e)}] Retriever run errored with error: ${ng(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${nm(nb.blue,"[agent/action]")} [${r}] Agent selected action: ${ng(t.actions[t.actions.length-1],"[action]")}`)}}var nw=r(16769);let nx=()=>(void 0===l&&(l=new ra("false"===no("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),l);class nS extends nd{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:t,projectName:r,client:n}=e;this.projectName=r??no("LANGCHAIN_PROJECT")??no("LANGCHAIN_SESSION"),this.exampleId=t,this.client=n??nx();let i=nS.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,t){return{...e,extra:{...e.extra,runtime:await ni()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){let t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){let t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){;t=t.parent_run}r.clear();let n=[t];for(;n.length>0;){let e=n.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&n.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let t={},r=[];for(let[e,n]of this.runMap){let i=new rA({...n,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=i,r.push([e,n.dotted_order])}for(let[e]of(r.sort((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0),r)){let r=this.runMap.get(e),n=t[e];if(r&&n&&r.parent_run_id){let e=t[r.parent_run_id];e&&(e.child_runs.push(n),n.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return rB()}catch{return}}}let nE=Symbol.for("ls:tracing_async_local_storage"),nC=Symbol.for("lc:context_variables"),nA=e=>{globalThis[nE]=e},nk=()=>globalThis[nE];function nO(){return new("default"in tj?tj.default:tj)({autoStart:!0,concurrency:1})}function nT(){return void 0===u&&(u=nO()),u}async function nI(e,t){if(!0===t){let t=nk();void 0!==t?await t.run(void 0,async()=>e()):await e()}else(u=nT()).add(async()=>{let t=nk();void 0!==t?await t.run(void 0,async()=>e()):await e()})}let nP=e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===no(e));function nR(e){let t=nk();if(void 0===t)return;let r=t.getStore();return r?.[nC]?.[e]}let nM=Symbol("lc:configure_hooks"),n$=()=>nR(nM)||[];class nN{setHandler(e){return this.setHandlers([e])}}class nj{constructor(e,t,r,n,i,o,a,s){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:s})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>nI(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(r=>nI(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}}class nB extends nj{getChild(e){let t=new nz(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}}class nL extends nj{async handleLLMNewToken(e,t,r,n,i,o){await Promise.all(this.handlers.map(r=>nI(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleLLMError(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class nF extends nj{getChild(e){let t=new nz(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,i){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class nD extends nj{getChild(e){let t=new nz(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>nI(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class nz extends nN{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r,n,i,o,a,s){return Promise.all(t.map(async(t,n)=>{let o=0===n&&r?r:(0,tN.Z)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return nf(r)&&r._createRunForLLMStart(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s),nI(async()=>{try{await r.handleLLMStart?.(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new nL(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,n,i,o,a,s){return Promise.all(t.map(async(t,n)=>{let o=0===n&&r?r:(0,tN.Z)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return nf(r)&&r._createRunForChatModelStart(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s),nI(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s);else if(r.handleLLMStart){let n=(0,nw.zs)(t);await r.handleLLMStart?.(e,[n],o,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new nL(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=(0,tN.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return nf(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,n,a),nI(async()=>{try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,n,a)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new nF(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,tN.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreAgent)return nf(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,a),nI(async()=>{try{await n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new nD(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,tN.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreRetriever)return nf(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,a),nI(async()=>{try{await n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new nB(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(n=>nI(async()=>{if(!n.ignoreCustomEvent)try{await n.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){for(let r of(this.handlers=[],this.inheritableHandlers=[],e))this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let r=new nz(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let n of e)r.handlers.filter(e=>"console_callback_handler"===e.name).some(e=>e.name===n.name)||r.addHandler(n,t);return r}static fromHandlers(e){class t extends ns{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:(0,tN.Z)()}),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,n,i,o,a){return this._configureSync(e,t,r,n,i,o,a)}static _configureSync(e,t,r,n,i,o,a){let s;(e||t)&&(Array.isArray(e)||!e?(s=new nz).setHandlers(e?.map(nU)??[],!0):s=e,s=s.copy(Array.isArray(t)?t.map(nU):t?.handlers,!1));let l="true"===no("LANGCHAIN_VERBOSE")||a?.verbose,u=nS.getTraceableRunTree()?.tracingEnabled||nP(),c=u||(no("LANGCHAIN_TRACING")??!1);if(l||c){if(s||(s=new nz),l&&!s.handlers.some(e=>e.name===n_.prototype.name)){let e=new n_;s.addHandler(e,!0)}if(c&&!s.handlers.some(e=>"langchain_tracer"===e.name)&&u){let e=new nS;s.addHandler(e,!0),s._parentRunId=nS.getTraceableRunTree()?.id??s._parentRunId}}for(let{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:n}of n$()){let i,o=n&&"true"===no(n)&&r,a=void 0!==e?nR(e):void 0;a&&nl(a)?i=a:o&&(i=new r({})),void 0!==i&&(s||(s=new nz),s.handlers.some(e=>e.name===i.name)||s.addHandler(i,t))}return(r||n)&&s&&(s.addTags(r??[]),s.addTags(n??[],!1)),(i||o)&&s&&(s.addMetadata(i??{}),s.addMetadata(o??{},!1)),s}}function nU(e){return"name"in e?e:ns.fromMethods(e)}class nZ{getStore(){}run(e,t){return t()}enterWith(e){}}let nH=new nZ,nG=Symbol.for("lc:child_config");class nW{getInstance(){return nk()??nH}getRunnableConfig(){let e=this.getInstance();return e.getStore()?.extra?.[nG]}runWithConfig(e,t,r){let n,i=nz._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),o=this.getInstance(),a=o.getStore(),s=i?.getParentRunId(),l=i?.handlers?.find(e=>e?.name==="langchain_tracer");return l&&s?n=l.convertToRunTree(s):r||(n=new rA({name:"<runnable_lambda>",tracingEnabled:!1})),n&&(n.extra={...n.extra,[nG]:e}),void 0!==a&&void 0!==a[nC]&&(n[nC]=a[nC]),o.run(n,t)}initializeGlobalInstance(e){void 0===nk()&&nA(e)}}let nq=new nW,nV=25;async function nX(e){return nz._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function nY(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{let r=e.copy();for(let e of n)r.addHandler(nU(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){let r=n.copy();for(let t of e)r.addHandler(nU(t),!0);t.callbacks=r}else t.callbacks=new nz(n._parentRunId,{handlers:e.handlers.concat(n.handlers),inheritableHandlers:e.inheritableHandlers.concat(n.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(n.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(n.inheritableTags))),metadata:{...e.metadata,...n.metadata}});else t.callbacks=n}else{let n=e;t[n]=r[n]??t[n]}return t}let nK=new Set(["string","number","boolean"]);function nJ(e){let t=nq.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:n,...i}=t;r=Object.entries(i).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable)for(let e of Object.keys(r.configurable))nK.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function nQ(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:o,runId:a}={}){let s=nJ(e);return void 0!==t&&(delete s.runName,s.callbacks=t),void 0!==n&&(s.recursionLimit=n),void 0!==r&&(s.maxConcurrency=r),void 0!==i&&(s.runName=i),void 0!==o&&(s.configurable={...s.configurable,...o}),void 0!==a&&delete s.runId,s}function n0(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function n1(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,n)=>{r=()=>{n(Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(Error("Aborted"))})]).finally(()=>t.removeEventListener("abort",r))}class n2 extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let t=e.getReader();return new n2({start(e){return r();function r(){return t.read().then(({done:t,value:n})=>t?void e.close():(e.enqueue(n),r()))}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new n2({async pull(t){let{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function n3(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function n5(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){let r={...e};for(let[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=n5(r[e],n):r[e]=n;return r}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}class n4{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{nq.runWithConfig(n0(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?nq.runWithConfig(n0(this.config),this.signal?async()=>n1(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 n6(e,t,r,n,...i){let o=new n4({generator:t,startSetup:r,signal:n}),a=await o.setup;return{output:e(o,a,...i),setup:a}}var n8=r(37149);class n9{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=r1({},t);return new n7({ops:t,state:r[r.length-1].newDocument})}}class n7 extends n9{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),r=r1(this.state,e.ops);return new n7({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){let t=r1({},e.ops);return new n7({ops:e.ops,state:t[t.length-1].newDocument})}}let ie=e=>"log_stream_tracer"===e.name;async function it(e,t){if("original"===t)throw 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;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function ir(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}function ii(e){return void 0!==e&&void 0!==e.message}class io extends nd{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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=n2.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=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new n9({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new n9({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?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};"streaming_events"===this._schemaFormat&&(r.inputs=await it(e,this._schemaFormat)),await this.writer.write(new n9({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await it(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await ir(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new n9({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new n9({ops:[{op:"replace",path:"/final_output",value:await ir(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n,i=this.keyMapByRunId[e.id];if(void 0===i)return;n=void 0!==e.inputs.messages?ii(r?.chunk)?r?.chunk:new n8.GC({id:`run-${e.id}`,content:t}):t;let o=new n9({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:n}]});await this.writer.write(o)}}class ia{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new ia({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function is({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}let il=e=>"event_stream_tracer"===e.name;class iu extends nd{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=n2.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new ia({text:t}):t}let o=this.tappedPromises.get(e);if(void 0===o){let a;o=new Promise(e=>{a=e}),this.tappedPromises.set(e,o);try{let o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};for await(let e of(await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value,t))"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...o,data:{chunk:i(n.runType,e)}},n),yield e}finally{a()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=is(e),r=void 0!==e.inputs.messages?"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 i=`on_${r}_start`;await this.send({event:i,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,i,o=this.runInfoMap.get(e.id);if(void 0===o)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===o.runType)i="on_chat_model_stream",n=r?.chunk===void 0?new n8.GC({content:t,id:`run-${e.id}`}):r.chunk.message;else if("llm"===o.runType)i="on_llm_stream",n=r?.chunk===void 0?new ia({text:t}):r.chunk;else throw Error(`Unexpected run type ${o.runType}`);await this.send({event:i,data:{chunk:n},run_id:e.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(e){let t,r,n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===n)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations;if("chat_model"===n.runType){for(let e of i??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===n.runType)r={generations:i?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){let t=is(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},n.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,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),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(i.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=is(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),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw 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 onRetrieverStart(e){let t=is(e),r="retriever",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw 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(void 0===n)throw 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(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}}let ic=[400,401,402,403,404,405,406,407,409],ih=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name||e?.code==="ECONNABORTED")throw e;let t=e?.response?.status??e?.status;if(t&&ic.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){let t=Error(e?.message);throw t.name="InsufficientQuotaError",t}};class id{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??ih;let t="default"in tj?tj.default:tj;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>t$(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}class ip extends nd{constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 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 im(e){return!!e&&e.lc_runnable}class ig{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 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}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every(e=>!this.excludeTags?.includes(e))),r}}let iy=Symbol("Let zodToJsonSchema decide on which parser to use"),iv={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ib=e=>"string"==typeof e?{...iv,name:e}:{...iv,...e},i_=e=>{let t=ib(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function iw(){return{}}function ix(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function iS(e,t,r,n,i){e[t]=r,ix(e,t,n,i)}function iE(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==g.ZodAny&&(r.items=ot(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&iS(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&iS(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(iS(r,"minItems",e.exactLength.value,e.exactLength.message,t),iS(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function iC(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?iS(r,"minimum",n.value,n.message,t):iS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),iS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?iS(r,"maximum",n.value,n.message,t):iS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),iS(r,"maximum",n.value,n.message,t));break;case"multipleOf":iS(r,"multipleOf",n.value,n.message,t)}return r}function iA(){return{type:"boolean"}}function ik(e,t){return ot(e.type._def,t)}let iO=(e,t)=>ot(e.innerType._def,t);function iT(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>iT(e,t,r))};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 iI(e,t)}}let iI=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let n of e.checks)switch(n.kind){case"min":iS(r,"minimum",n.value,n.message,t);break;case"max":iS(r,"maximum",n.value,n.message,t)}return r};function iP(e,t){return{...ot(e.innerType._def,t),default:e.defaultValue()}}function iR(e,t){return"input"===t.effectStrategy?ot(e.schema._def,t):{}}function iM(e){return{type:"string",enum:Array.from(e.values)}}let i$=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function iN(e,t){let r=[ot(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ot(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(e=>{if(i$(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}}),i.length?{allOf:i,...n}:void 0}function ij(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let iB={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:()=>(void 0===c&&(c=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),c),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])$/,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 iL(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":iS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":iS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":iU(r,"email",n.message,t);break;case"format:idn-email":iU(r,"idn-email",n.message,t);break;case"pattern:zod":iZ(r,iB.email,n.message,t)}break;case"url":iU(r,"uri",n.message,t);break;case"uuid":iU(r,"uuid",n.message,t);break;case"regex":iZ(r,n.regex,n.message,t);break;case"cuid":iZ(r,iB.cuid,n.message,t);break;case"cuid2":iZ(r,iB.cuid2,n.message,t);break;case"startsWith":iZ(r,RegExp(`^${iF(n.value,t)}`),n.message,t);break;case"endsWith":iZ(r,RegExp(`${iF(n.value,t)}$`),n.message,t);break;case"datetime":iU(r,"date-time",n.message,t);break;case"date":iU(r,"date",n.message,t);break;case"time":iU(r,"time",n.message,t);break;case"duration":iU(r,"duration",n.message,t);break;case"length":iS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),iS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":iZ(r,RegExp(iF(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&iU(r,"ipv4",n.message,t),"v4"!==n.version&&iU(r,"ipv6",n.message,t);break;case"base64url":iZ(r,iB.base64url,n.message,t);break;case"jwt":iZ(r,iB.jwt,n.message,t);break;case"cidr":"v6"!==n.version&&iZ(r,iB.ipv4Cidr,n.message,t),"v4"!==n.version&&iZ(r,iB.ipv6Cidr,n.message,t);break;case"emoji":iZ(r,iB.emoji(),n.message,t);break;case"ulid":iZ(r,iB.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":iU(r,"binary",n.message,t);break;case"contentEncoding:base64":iS(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":iZ(r,iB.base64,n.message,t)}break;case"nanoid":iZ(r,iB.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(e=>{})(0)}return r}function iF(e,t){return"escape"===t.patternStrategy?iz(e):e}let iD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iz(e){let t="";for(let r=0;r<e.length;r++)iD.has(e[r])||(t+="\\"),t+=e[r];return t}function iU(e,t,r,n){e.format||e.anyOf?.some(e=>e.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,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):iS(e,"format",t,r,n)}function iZ(e,t,r,n){e.pattern||e.allOf?.some(e=>e.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,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:iH(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):iS(e,"pattern",iH(t,n),r,n)}function iH(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,i="",o=!1,a=!1,s=!1;for(let e=0;e<n.length;e++){if(o){i+=n[e],o=!1;continue}if(r.i){if(a){if(n[e].match(/[a-z]/)){s?(i+=n[e],i+=`${n[e-2]}-${n[e]}`.toUpperCase(),s=!1):"-"===n[e+1]&&n[e+2]?.match(/[a-z]/)?(i+=n[e],s=!0):i+=`${n[e]}${n[e].toUpperCase()}`;continue}}else if(n[e].match(/[a-z]/)){i+=`[${n[e]}${n[e].toUpperCase()}]`;continue}}if(r.m){if("^"===n[e]){i+=`(^|(?<=[\r
265
+ ${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let t=e7(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){let e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c=a?{...i,metadata:a}:i,h={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:o||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c=a?{...i,metadata:a}:i,h={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:o||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM run to end.");return r.end_time=Date.now(),r.outputs=e,r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onLLMEnd?.(r),await this._endTrace(r),r}async handleLLMError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM run to end.");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onLLMError?.(r),await this._endTrace(r),r}_createRunForChainStart(e,t,r,n,i,o,a,s){let l=this._getExecutionOrder(n),u=Date.now(),c={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:a??"chain",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,n,i,o,a,s){let l=this.runMap.get(r)??this._createRunForChainStart(e,t,r,n,i,o,a,s);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,n,i){let o=this.runMap.get(t);if(!o)throw Error("No chain run to end.");return o.end_time=Date.now(),o.outputs=e8(e,"output"),o.events.push({name:"end",time:new Date(o.end_time).toISOString()}),i?.inputs!==void 0&&(o.inputs=e8(i.inputs,"input")),await this.onChainEnd?.(o),await this._endTrace(o),o}async handleChainError(e,t,r,n,i){let o=this.runMap.get(t);if(!o)throw Error("No chain run to end.");return o.end_time=Date.now(),o.error=this.stringifyError(e),o.events.push({name:"error",time:new Date(o.end_time).toISOString()}),i?.inputs!==void 0&&(o.inputs=e8(i.inputs,"input")),await this.onChainError?.(o),await this._endTrace(o),o}_createRunForToolStart(e,t,r,n,i,o,a){let s=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:"tool",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,n,i,o,a){let s=this.runMap.get(r)??this._createRunForToolStart(e,t,r,n,i,o,a);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.runMap.get(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,n,i,o,a){let s=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:"retriever",child_runs:[],extra:o?{metadata:o}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,n,i,o,a){let s=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,n,i,o,a);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.runMap.get(t);r&&r?.run_type==="chain"&&(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,n,i,o){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:o?.chunk}}),await this.onLLMNewToken?.(a,e,{chunk:o?.chunk}),a}}var tr=r(8300);function tn(e,t){return`${e.open}${t}${e.close}`}function ti(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function to(e){return"string"==typeof e?e.trim():null==e?e:ti(e,e.toString())}function ta(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:ts}=tr;class tl extends tt{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let n=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?tn(tr.bold,n):n}).join(" > ");return tn(ts.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.green,"[chain/start]")} [${t}] Entering Chain run with input: ${ti(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.cyan,"[chain/end]")} [${t}] [${ta(e)}] Exiting Chain run with output: ${ti(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.red,"[chain/error]")} [${t}] [${ta(e)}] Chain run errored with error: ${ti(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${tn(ts.green,"[llm/start]")} [${t}] Entering LLM run with input: ${ti(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.cyan,"[llm/end]")} [${t}] [${ta(e)}] Exiting LLM run with output: ${ti(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.red,"[llm/error]")} [${t}] [${ta(e)}] LLM run errored with error: ${ti(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.green,"[tool/start]")} [${t}] Entering Tool run with input: "${to(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.cyan,"[tool/end]")} [${t}] [${ta(e)}] Exiting Tool run with output: "${to(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.red,"[tool/error]")} [${t}] [${ta(e)}] Tool run errored with error: ${ti(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${ti(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.cyan,"[retriever/end]")} [${t}] [${ta(e)}] Exiting Retriever run with output: ${ti(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${tn(ts.red,"[retriever/error]")} [${t}] [${ta(e)}] Retriever run errored with error: ${ti(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${tn(ts.blue,"[agent/action]")} [${r}] Agent selected action: ${ti(t.actions[t.actions.length-1],"[action]")}`)}}var tu=r(16769);let tc=()=>(void 0===s&&(s=new V("false"===e3("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),s);class th extends tt{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:t,projectName:r,client:n}=e;this.projectName=r??e3("LANGCHAIN_PROJECT")??e3("LANGCHAIN_SESSION"),this.exampleId=t,this.client=n??tc();let i=th.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,t){return{...e,extra:{...e.extra,runtime:await e2()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){let t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){let t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){;t=t.parent_run}r.clear();let n=[t];for(;n.length>0;){let e=n.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&n.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let t={},r=[];for(let[e,n]of this.runMap){let i=new ep({...n,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=i,r.push([e,n.dotted_order])}for(let[e]of(r.sort((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0),r)){let r=this.runMap.get(e),n=t[e];if(r&&n&&r.parent_run_id){let e=t[r.parent_run_id];e&&(e.child_runs.push(n),n.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return eC()}catch{return}}}let tf=Symbol.for("ls:tracing_async_local_storage"),td=Symbol.for("lc:context_variables"),tp=e=>{globalThis[tf]=e},tm=()=>globalThis[tf];function tg(){return new("default"in p?p.default:p)({autoStart:!0,concurrency:1})}function ty(){return void 0===l&&(l=tg()),l}async function tv(e,t){if(!0===t){let t=tm();void 0!==t?await t.run(void 0,async()=>e()):await e()}else(l=ty()).add(async()=>{let t=tm();void 0!==t?await t.run(void 0,async()=>e()):await e()})}let tb=e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===e3(e));function t_(e){let t=tm();if(void 0===t)return;let r=t.getStore();return r?.[td]?.[e]}let tw=Symbol("lc:configure_hooks"),tx=()=>t_(tw)||[];class tS{setHandler(e){return this.setHandlers([e])}}class tE{constructor(e,t,r,n,i,o,a,s){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:s})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>tv(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(r=>tv(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}}class tC extends tE{getChild(e){let t=new tT(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}}class tA extends tE{async handleLLMNewToken(e,t,r,n,i,o){await Promise.all(this.handlers.map(r=>tv(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleLLMError(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class tk extends tE{getChild(e){let t=new tT(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,i){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class tO extends tE{getChild(e){let t=new tT(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>tv(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class tT extends tS{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r,n,i,o,a,s){return Promise.all(t.map(async(t,n)=>{let o=0===n&&r?r:(0,d.Z)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return te(r)&&r._createRunForLLMStart(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s),tv(async()=>{try{await r.handleLLMStart?.(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new tA(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,n,i,o,a,s){return Promise.all(t.map(async(t,n)=>{let o=0===n&&r?r:(0,d.Z)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return te(r)&&r._createRunForChatModelStart(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s),tv(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],o,this._parentRunId,i,this.tags,this.metadata,s);else if(r.handleLLMStart){let n=(0,tu.zs)(t);await r.handleLLMStart?.(e,[n],o,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new tA(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=(0,d.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return te(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,n,a),tv(async()=>{try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,n,a)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new tk(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,d.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreAgent)return te(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,a),tv(async()=>{try{await n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new tO(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,d.Z)(),n,i,o,a){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreRetriever)return te(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,a),tv(async()=>{try{await n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new tC(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(n=>tv(async()=>{if(!n.ignoreCustomEvent)try{await n.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){for(let r of(this.handlers=[],this.inheritableHandlers=[],e))this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let r=new tT(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let n of e)r.handlers.filter(e=>"console_callback_handler"===e.name).some(e=>e.name===n.name)||r.addHandler(n,t);return r}static fromHandlers(e){class t extends e4{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:(0,d.Z)()}),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,n,i,o,a){return this._configureSync(e,t,r,n,i,o,a)}static _configureSync(e,t,r,n,i,o,a){let s;(e||t)&&(Array.isArray(e)||!e?(s=new tT).setHandlers(e?.map(tI)??[],!0):s=e,s=s.copy(Array.isArray(t)?t.map(tI):t?.handlers,!1));let l="true"===e3("LANGCHAIN_VERBOSE")||a?.verbose,u=th.getTraceableRunTree()?.tracingEnabled||tb(),c=u||(e3("LANGCHAIN_TRACING")??!1);if(l||c){if(s||(s=new tT),l&&!s.handlers.some(e=>e.name===tl.prototype.name)){let e=new tl;s.addHandler(e,!0)}if(c&&!s.handlers.some(e=>"langchain_tracer"===e.name)&&u){let e=new th;s.addHandler(e,!0),s._parentRunId=th.getTraceableRunTree()?.id??s._parentRunId}}for(let{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:n}of tx()){let i,o=n&&"true"===e3(n)&&r,a=void 0!==e?t_(e):void 0;a&&e6(a)?i=a:o&&(i=new r({})),void 0!==i&&(s||(s=new tT),s.handlers.some(e=>e.name===i.name)||s.addHandler(i,t))}return(r||n)&&s&&(s.addTags(r??[]),s.addTags(n??[],!1)),(i||o)&&s&&(s.addMetadata(i??{}),s.addMetadata(o??{},!1)),s}}function tI(e){return"name"in e?e:e4.fromMethods(e)}class tP{getStore(){}run(e,t){return t()}enterWith(e){}}let tR=new tP,tM=Symbol.for("lc:child_config");class t${getInstance(){return tm()??tR}getRunnableConfig(){let e=this.getInstance();return e.getStore()?.extra?.[tM]}runWithConfig(e,t,r){let n,i=tT._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),o=this.getInstance(),a=o.getStore(),s=i?.getParentRunId(),l=i?.handlers?.find(e=>e?.name==="langchain_tracer");return l&&s?n=l.convertToRunTree(s):r||(n=new ep({name:"<runnable_lambda>",tracingEnabled:!1})),n&&(n.extra={...n.extra,[tM]:e}),void 0!==a&&void 0!==a[td]&&(n[td]=a[td]),o.run(n,t)}initializeGlobalInstance(e){void 0===tm()&&tp(e)}}let tN=new t$,tj=25;async function tB(e){return tT._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function tL(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{let r=e.copy();for(let e of n)r.addHandler(tI(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){let r=n.copy();for(let t of e)r.addHandler(tI(t),!0);t.callbacks=r}else t.callbacks=new tT(n._parentRunId,{handlers:e.handlers.concat(n.handlers),inheritableHandlers:e.inheritableHandlers.concat(n.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(n.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(n.inheritableTags))),metadata:{...e.metadata,...n.metadata}});else t.callbacks=n}else{let n=e;t[n]=r[n]??t[n]}return t}let tF=new Set(["string","number","boolean"]);function tD(e){let t=tN.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:n,...i}=t;r=Object.entries(i).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable)for(let e of Object.keys(r.configurable))tF.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function tz(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:o,runId:a}={}){let s=tD(e);return void 0!==t&&(delete s.runName,s.callbacks=t),void 0!==n&&(s.recursionLimit=n),void 0!==r&&(s.maxConcurrency=r),void 0!==i&&(s.runName=i),void 0!==o&&(s.configurable={...s.configurable,...o}),void 0!==a&&delete s.runId,s}function tU(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function tZ(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,n)=>{r=()=>{n(Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(Error("Aborted"))})]).finally(()=>t.removeEventListener("abort",r))}class tH extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let t=e.getReader();return new tH({start(e){return r();function r(){return t.read().then(({done:t,value:n})=>t?void e.close():(e.enqueue(n),r()))}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new tH({async pull(t){let{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function tG(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function tW(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){let r={...e};for(let[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=tW(r[e],n):r[e]=n;return r}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}class tq{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{tN.runWithConfig(tU(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?tN.runWithConfig(tU(this.config),this.signal?async()=>tZ(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 tV(e,t,r,n,...i){let o=new tq({generator:t,startSetup:r,signal:n}),a=await o.setup;return{output:e(o,a,...i),setup:a}}var tX=r(37149);class tY{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=eZ({},t);return new tK({ops:t,state:r[r.length-1].newDocument})}}class tK extends tY{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),r=eZ(this.state,e.ops);return new tK({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){let t=eZ({},e.ops);return new tK({ops:e.ops,state:t[t.length-1].newDocument})}}let tJ=e=>"log_stream_tracer"===e.name;async function tQ(e,t){if("original"===t)throw 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;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function t0(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}function t1(e){return void 0!==e&&void 0!==e.message}class t2 extends tt{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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=tH.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=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new tY({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new tY({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?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};"streaming_events"===this._schemaFormat&&(r.inputs=await tQ(e,this._schemaFormat)),await this.writer.write(new tY({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await tQ(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await t0(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new tY({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new tY({ops:[{op:"replace",path:"/final_output",value:await t0(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n,i=this.keyMapByRunId[e.id];if(void 0===i)return;n=void 0!==e.inputs.messages?t1(r?.chunk)?r?.chunk:new tX.GC({id:`run-${e.id}`,content:t}):t;let o=new tY({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:n}]});await this.writer.write(o)}}class t3{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new t3({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function t5({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}let t4=e=>"event_stream_tracer"===e.name;class t6 extends tt{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=tH.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new t3({text:t}):t}let o=this.tappedPromises.get(e);if(void 0===o){let a;o=new Promise(e=>{a=e}),this.tappedPromises.set(e,o);try{let o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};for await(let e of(await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value,t))"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...o,data:{chunk:i(n.runType,e)}},n),yield e}finally{a()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=t5(e),r=void 0!==e.inputs.messages?"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 i=`on_${r}_start`;await this.send({event:i,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,i,o=this.runInfoMap.get(e.id);if(void 0===o)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===o.runType)i="on_chat_model_stream",n=r?.chunk===void 0?new tX.GC({content:t,id:`run-${e.id}`}):r.chunk.message;else if("llm"===o.runType)i="on_llm_stream",n=r?.chunk===void 0?new t3({text:t}):r.chunk;else throw Error(`Unexpected run type ${o.runType}`);await this.send({event:i,data:{chunk:n},run_id:e.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(e){let t,r,n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===n)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations;if("chat_model"===n.runType){for(let e of i??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===n.runType)r={generations:i?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){let t=t5(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},n.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,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),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(i.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=t5(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),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw 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 onRetrieverStart(e){let t=t5(e),r="retriever",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw 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(void 0===n)throw 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(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}}let t8=[400,401,402,403,404,405,406,407,409],t9=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name||e?.code==="ECONNABORTED")throw e;let t=e?.response?.status??e?.status;if(t&&t8.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){let t=Error(e?.message);throw t.name="InsufficientQuotaError",t}};class t7{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??t9;let t="default"in p?p.default:p;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>f(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}class re extends tt{constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 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 rt(e){return!!e&&e.lc_runnable}class rr{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 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}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every(e=>!this.excludeTags?.includes(e))),r}}let rn=Symbol("Let zodToJsonSchema decide on which parser to use"),ri={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ro=e=>"string"==typeof e?{...ri,name:e}:{...ri,...e},ra=e=>{let t=ro(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function rs(){return{}}function rl(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ru(e,t,r,n,i){e[t]=r,rl(e,t,n,i)}function rc(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==h.pA.ZodAny&&(r.items=rK(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ru(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ru(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ru(r,"minItems",e.exactLength.value,e.exactLength.message,t),ru(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function rh(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?ru(r,"minimum",n.value,n.message,t):ru(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ru(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?ru(r,"maximum",n.value,n.message,t):ru(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ru(r,"maximum",n.value,n.message,t));break;case"multipleOf":ru(r,"multipleOf",n.value,n.message,t)}return r}function rf(){return{type:"boolean"}}function rd(e,t){return rK(e.type._def,t)}let rp=(e,t)=>rK(e.innerType._def,t);function rm(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>rm(e,t,r))};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 rg(e,t)}}let rg=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let n of e.checks)switch(n.kind){case"min":ru(r,"minimum",n.value,n.message,t);break;case"max":ru(r,"maximum",n.value,n.message,t)}return r};function ry(e,t){return{...rK(e.innerType._def,t),default:e.defaultValue()}}function rv(e,t){return"input"===t.effectStrategy?rK(e.schema._def,t):{}}function rb(e){return{type:"string",enum:Array.from(e.values)}}let r_=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function rw(e,t){let r=[rK(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),rK(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(e=>{if(r_(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}}),i.length?{allOf:i,...n}:void 0}function rx(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let rS={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:()=>(void 0===u&&(u=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),u),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])$/,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 rE(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ru(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ru(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":rO(r,"email",n.message,t);break;case"format:idn-email":rO(r,"idn-email",n.message,t);break;case"pattern:zod":rT(r,rS.email,n.message,t)}break;case"url":rO(r,"uri",n.message,t);break;case"uuid":rO(r,"uuid",n.message,t);break;case"regex":rT(r,n.regex,n.message,t);break;case"cuid":rT(r,rS.cuid,n.message,t);break;case"cuid2":rT(r,rS.cuid2,n.message,t);break;case"startsWith":rT(r,RegExp(`^${rC(n.value,t)}`),n.message,t);break;case"endsWith":rT(r,RegExp(`${rC(n.value,t)}$`),n.message,t);break;case"datetime":rO(r,"date-time",n.message,t);break;case"date":rO(r,"date",n.message,t);break;case"time":rO(r,"time",n.message,t);break;case"duration":rO(r,"duration",n.message,t);break;case"length":ru(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),ru(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":rT(r,RegExp(rC(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&rO(r,"ipv4",n.message,t),"v4"!==n.version&&rO(r,"ipv6",n.message,t);break;case"base64url":rT(r,rS.base64url,n.message,t);break;case"jwt":rT(r,rS.jwt,n.message,t);break;case"cidr":"v6"!==n.version&&rT(r,rS.ipv4Cidr,n.message,t),"v4"!==n.version&&rT(r,rS.ipv6Cidr,n.message,t);break;case"emoji":rT(r,rS.emoji(),n.message,t);break;case"ulid":rT(r,rS.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":rO(r,"binary",n.message,t);break;case"contentEncoding:base64":ru(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":rT(r,rS.base64,n.message,t)}break;case"nanoid":rT(r,rS.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(e=>{})(0)}return r}function rC(e,t){return"escape"===t.patternStrategy?rk(e):e}let rA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rk(e){let t="";for(let r=0;r<e.length;r++)rA.has(e[r])||(t+="\\"),t+=e[r];return t}function rO(e,t,r,n){e.format||e.anyOf?.some(e=>e.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,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ru(e,"format",t,r,n)}function rT(e,t,r,n){e.pattern||e.allOf?.some(e=>e.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,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:rI(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ru(e,"pattern",rI(t,n),r,n)}function rI(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,i="",o=!1,a=!1,s=!1;for(let e=0;e<n.length;e++){if(o){i+=n[e],o=!1;continue}if(r.i){if(a){if(n[e].match(/[a-z]/)){s?(i+=n[e],i+=`${n[e-2]}-${n[e]}`.toUpperCase(),s=!1):"-"===n[e+1]&&n[e+2]?.match(/[a-z]/)?(i+=n[e],s=!0):i+=`${n[e]}${n[e].toUpperCase()}`;continue}}else if(n[e].match(/[a-z]/)){i+=`[${n[e]}${n[e].toUpperCase()}]`;continue}}if(r.m){if("^"===n[e]){i+=`(^|(?<=[\r
266
266
  ]))`;continue}else if("$"===n[e]){i+=`($|(?=[\r
267
267
  ]))`;continue}}if(r.s&&"."===n[e]){i+=a?`${n[e]}\r
268
268
  `:`[${n[e]}\r
269
- ]`;continue}i+=n[e],"\\"===n[e]?o=!0:a&&"]"===n[e]?a=!1:a||"["!==n[e]||(a=!0)}try{new RegExp(i)}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 i}function iG(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===g.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:ot(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:ot(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===g.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=iL(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===g.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===g.ZodBranded&&e.keyType._def.type._def.typeName===g.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=ik(e.keyType._def,t);return{...r,propertyNames:i}}return r}function iW(e,t){return"record"===t.mapStrategy?iG(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ot(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},ot(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function iq(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),n=Array.from(new Set(r.map(e=>typeof e)));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}function iV(){return{not:{}}}function iX(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}let iY={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function iK(e,t){if("openApi3"===t.target)return iJ(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in iY&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=iY[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return iJ(e,t)}let iJ=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>ot(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function iQ(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:iY[e.innerType._def.typeName],nullable:!0}:{type:[iY[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=ot(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=ot(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function i0(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",ix(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?iS(r,"minimum",n.value,n.message,t):iS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),iS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?iS(r,"maximum",n.value,n.message,t):iS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),iS(r,"maximum",n.value,n.message,t));break;case"multipleOf":iS(r,"multipleOf",n.value,n.message,t)}return r}function i1(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:ot(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:ot(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function i2(e,t){let r="openAi"===t.target,n={type:"object",...Object.entries(e.shape()).reduce((e,[n,i])=>{if(void 0===i||void 0===i._def)return e;let o=i.isOptional();o&&r&&(i instanceof eW&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);let a=ot(i._def,{...t,currentPath:[...t.currentPath,"properties",n],propertyPath:[...t.currentPath,"properties",n]});return void 0===a?e:{properties:{...e.properties,[n]:a},required:o?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:i1(e,t)};return n.required.length||delete n.required,n}let i3=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ot(e.innerType._def,t);let r=ot(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},i5=(e,t)=>{if("input"===t.pipeStrategy)return ot(e.in._def,t);if("output"===t.pipeStrategy)return ot(e.out._def,t);let r=ot(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=ot(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(e=>void 0!==e)}};function i4(e,t){return ot(e.type._def,t)}function i6(e,t){let r={type:"array",uniqueItems:!0,items:ot(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&iS(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&iS(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function i8(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>ot(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:ot(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>ot(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}function i9(){return{not:{}}}function i7(){return{}}let oe=(e,t)=>ot(e.innerType._def,t);function ot(e,t,r=!1){let n=t.seen.get(e);if(t.override){let i=t.override?.(e,t,n,r);if(i!==iy)return i}if(n&&!r){let e=or(n,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let o=oi(e,e.typeName,t);return o&&oo(e,t,o),i.jsonSchema=o,o}let or=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:on(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},on=(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("/")},oi=(e,t,r)=>{switch(t){case g.ZodString:return iL(e,r);case g.ZodNumber:return i0(e,r);case g.ZodObject:return i2(e,r);case g.ZodBigInt:return iC(e,r);case g.ZodBoolean:return iA();case g.ZodDate:return iT(e,r);case g.ZodUndefined:return i9();case g.ZodNull:return iX(r);case g.ZodArray:return iE(e,r);case g.ZodUnion:case g.ZodDiscriminatedUnion:return iK(e,r);case g.ZodIntersection:return iN(e,r);case g.ZodTuple:return i8(e,r);case g.ZodRecord:return iG(e,r);case g.ZodLiteral:return ij(e,r);case g.ZodEnum:return iM(e);case g.ZodNativeEnum:return iq(e);case g.ZodNullable:return iQ(e,r);case g.ZodOptional:return i3(e,r);case g.ZodMap:return iW(e,r);case g.ZodSet:return i6(e,r);case g.ZodLazy:return ot(e.getter()._def,r);case g.ZodPromise:return i4(e,r);case g.ZodNaN:case g.ZodNever:return iV();case g.ZodEffects:return iR(e,r);case g.ZodAny:return iw();case g.ZodUnknown:return i7();case g.ZodDefault:return iP(e,r);case g.ZodBranded:return ik(e,r);case g.ZodReadonly:return oe(e,r);case g.ZodCatch:return iO(e,r);case g.ZodPipeline:return i5(e,r);case g.ZodFunction:case g.ZodVoid:case g.ZodSymbol:return;default:let n;return void(n=0)}},oo=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),oa=(e,t)=>{let r=i_(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:ot(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}}),{}):void 0,i="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,o=ot(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},a="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(o.title=a);let s=void 0===i?n?{...o,[r.definitionPath]:n}:o:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return"jsonSchema7"===r.target?s.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===r.target||"openAi"===r.target)&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function os(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}let ol=["*","_","`"];function ou(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
270
- `;return t}function oc(e,t,r){let{firstNode:n,lastNode:i,nodeColors:o,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:l=9}=r??{},u=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
269
+ ]`;continue}i+=n[e],"\\"===n[e]?o=!0:a&&"]"===n[e]?a=!1:a||"["!==n[e]||(a=!0)}try{new RegExp(i)}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 i}function rP(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===h.pA.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===h.pA.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=rE(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===h.pA.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===h.pA.ZodBranded&&e.keyType._def.type._def.typeName===h.pA.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=rd(e.keyType._def,t);return{...r,propertyNames:i}}return r}function rR(e,t){return"record"===t.mapStrategy?rP(e,t):{type:"array",maxItems:125,items:{type:"array",items:[rK(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function rM(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),n=Array.from(new Set(r.map(e=>typeof e)));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}function r$(){return{not:{}}}function rN(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}let rj={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rB(e,t){if("openApi3"===t.target)return rL(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in rj&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=rj[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return rL(e,t)}let rL=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function rF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:rj[e.innerType._def.typeName],nullable:!0}:{type:[rj[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function rD(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",rl(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?ru(r,"minimum",n.value,n.message,t):ru(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ru(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?ru(r,"maximum",n.value,n.message,t):ru(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ru(r,"maximum",n.value,n.message,t));break;case"multipleOf":ru(r,"multipleOf",n.value,n.message,t)}return r}function rz(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:rK(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:rK(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function rU(e,t){let r="openAi"===t.target,n={type:"object",...Object.entries(e.shape()).reduce((e,[n,i])=>{if(void 0===i||void 0===i._def)return e;let o=i.isOptional();o&&r&&(i instanceof h.ak&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);let a=rK(i._def,{...t,currentPath:[...t.currentPath,"properties",n],propertyPath:[...t.currentPath,"properties",n]});return void 0===a?e:{properties:{...e.properties,[n]:a},required:o?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:rz(e,t)};return n.required.length||delete n.required,n}let rZ=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return rK(e.innerType._def,t);let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},rH=(e,t)=>{if("input"===t.pipeStrategy)return rK(e.in._def,t);if("output"===t.pipeStrategy)return rK(e.out._def,t);let r=rK(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=rK(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(e=>void 0!==e)}};function rG(e,t){return rK(e.type._def,t)}function rW(e,t){let r={type:"array",uniqueItems:!0,items:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ru(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ru(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function rq(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:rK(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}function rV(){return{not:{}}}function rX(){return{}}let rY=(e,t)=>rK(e.innerType._def,t);function rK(e,t,r=!1){let n=t.seen.get(e);if(t.override){let i=t.override?.(e,t,n,r);if(i!==rn)return i}if(n&&!r){let e=rJ(n,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let o=r0(e,e.typeName,t);return o&&r1(e,t,o),i.jsonSchema=o,o}let rJ=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:rQ(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},rQ=(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("/")},r0=(e,t,r)=>{switch(t){case h.pA.ZodString:return rE(e,r);case h.pA.ZodNumber:return rD(e,r);case h.pA.ZodObject:return rU(e,r);case h.pA.ZodBigInt:return rh(e,r);case h.pA.ZodBoolean:return rf();case h.pA.ZodDate:return rm(e,r);case h.pA.ZodUndefined:return rV();case h.pA.ZodNull:return rN(r);case h.pA.ZodArray:return rc(e,r);case h.pA.ZodUnion:case h.pA.ZodDiscriminatedUnion:return rB(e,r);case h.pA.ZodIntersection:return rw(e,r);case h.pA.ZodTuple:return rq(e,r);case h.pA.ZodRecord:return rP(e,r);case h.pA.ZodLiteral:return rx(e,r);case h.pA.ZodEnum:return rb(e);case h.pA.ZodNativeEnum:return rM(e);case h.pA.ZodNullable:return rF(e,r);case h.pA.ZodOptional:return rZ(e,r);case h.pA.ZodMap:return rR(e,r);case h.pA.ZodSet:return rW(e,r);case h.pA.ZodLazy:return rK(e.getter()._def,r);case h.pA.ZodPromise:return rG(e,r);case h.pA.ZodNaN:case h.pA.ZodNever:return r$();case h.pA.ZodEffects:return rv(e,r);case h.pA.ZodAny:return rs();case h.pA.ZodUnknown:return rX();case h.pA.ZodDefault:return ry(e,r);case h.pA.ZodBranded:return rd(e,r);case h.pA.ZodReadonly:return rY(e,r);case h.pA.ZodCatch:return rp(e,r);case h.pA.ZodPipeline:return rH(e,r);case h.pA.ZodFunction:case h.pA.ZodVoid:case h.pA.ZodSymbol:return;default:let n;return void(n=0)}},r1=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),r2=(e,t)=>{let r=ra(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:rK(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}}),{}):void 0,i="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,o=rK(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},a="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(o.title=a);let s=void 0===i?n?{...o,[r.definitionPath]:n}:o:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return"jsonSchema7"===r.target?s.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===r.target||"openAi"===r.target)&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function r3(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}let r5=["*","_","`"];function r4(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
270
+ `;return t}function r6(e,t,r){let{firstNode:n,lastNode:i,nodeColors:o,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:l=9}=r??{},u=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
271
271
  graph TD;
272
- `:"graph TD;\n";if(a){let t="default",r={[t]:"{0}({1})"};for(let[o,a]of(void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last"),Object.entries(e))){let e=a.name.split(":").pop()??"",n=ol.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(a.metadata??{}).length&&(n+=`<hr/><small><em>${Object.entries(a.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}</em></small>`);let i=(r[o]??r[t]).replace("{0}",os(o)).replace("{1}",n);u+=` ${i}
272
+ `:"graph TD;\n";if(a){let t="default",r={[t]:"{0}({1})"};for(let[o,a]of(void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last"),Object.entries(e))){let e=a.name.split(":").pop()??"",n=r5.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(a.metadata??{}).length&&(n+=`<hr/><small><em>${Object.entries(a.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}</em></small>`);let i=(r[o]??r[t]).replace("{0}",r3(o)).replace("{1}",n);u+=` ${i}
273
273
  `}}let c={};for(let e of t){let t=e.source.split(":"),r=e.target.split(":"),n=t.filter((e,t)=>e===r[t]).join(":");c[n]||(c[n]=[]),c[n].push(e)}let h=new Set;function f(e,t){let r=1===e.length&&e[0].source===e[0].target;if(t&&!r){let e=t.split(":").pop();if(h.has(e))throw Error(`Found duplicate subgraph '${e}' -- 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.`);h.add(e),u+=` subgraph ${e}
274
- `}for(let t of e){let{source:e,target:r,data:n,conditional:i}=t,o="";if(void 0!==n){let e=n,t=e.split(" ");t.length>l&&(e=Array.from({length:Math.ceil(t.length/l)},(e,r)=>t.slice(r*l,(r+1)*l).join(" ")).join("&nbsp;<br>&nbsp;")),o=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --> `}else o=i?" -.-> ":" --\x3e ";u+=` ${os(e)}${o}${os(r)};
275
- `}for(let e in c)e.startsWith(`${t}:`)&&e!==t&&f(c[e],e);t&&!r&&(u+=" end\n")}for(let e in f(c[""]??[],""),c)e.includes(":")||""===e||f(c[e],e);return a&&(u+=ou(o??{})),u}async function oh(e,t){let{backgroundColor:r="white"}=t??{},n=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let i=`https://mermaid.ink/img/${n}?bgColor=${r}`,o=await fetch(i);if(!o.ok)throw Error(`Failed to render the graph using the Mermaid.INK API.
274
+ `}for(let t of e){let{source:e,target:r,data:n,conditional:i}=t,o="";if(void 0!==n){let e=n,t=e.split(" ");t.length>l&&(e=Array.from({length:Math.ceil(t.length/l)},(e,r)=>t.slice(r*l,(r+1)*l).join(" ")).join("&nbsp;<br>&nbsp;")),o=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --> `}else o=i?" -.-> ":" --\x3e ";u+=` ${r3(e)}${o}${r3(r)};
275
+ `}for(let e in c)e.startsWith(`${t}:`)&&e!==t&&f(c[e],e);t&&!r&&(u+=" end\n")}for(let e in f(c[""]??[],""),c)e.includes(":")||""===e||f(c[e],e);return a&&(u+=r4(o??{})),u}async function r8(e,t){let{backgroundColor:r="white"}=t??{},n=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let i=`https://mermaid.ink/img/${n}?bgColor=${r}`,o=await fetch(i);if(!o.ok)throw Error(`Failed to render the graph using the Mermaid.INK API.
276
276
  Status code: ${o.status}
277
- Status text: ${o.statusText}`);return await o.blob()}function of(e,t){if(void 0!==e&&!(0,tG.Z)(e))return e;if(!im(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch(e){return t.getName()}}function od(e){return im(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...oa(e.data.schema),title:e.data.name}}}class op{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=(0,tG.Z)(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...od(t)})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let n=t??(0,tN.Z)(),i={id:n,data:e,name:of(t,e),metadata:r};return this.nodes[n]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,n){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(i),i}firstNode(){return om(this)}lastNode(){return og(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(e=>e.id).every(tG.Z)&&(r="");let n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}});let i=e.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}));this.edges=[...this.edges,...i];let o=e.firstNode(),a=e.lastNode();return[o?{id:n(o.id),data:o.data}:void 0,a?{id:n(a.id),data:a.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&om(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&og(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),t=new Map;Object.values(e).forEach(e=>{t.set(e,(t.get(e)||0)+1)});let r=r=>{let n=e[r];return(0,tG.Z)(r)&&1===t.get(n)?n:r};return new op({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},o=this.reid(),a=o.firstNode(),s=o.lastNode();return oc(o.nodes,o.edges,{firstNode:a?.id,lastNode:s?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:i})}async drawMermaidPng(e){return oh(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function om(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),n=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function og(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),n=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function oy(e){let t=new TextEncoder,r=new ReadableStream({async start(r){for await(let n of e)r.enqueue(t.encode(`event: data
277
+ Status text: ${o.statusText}`);return await o.blob()}function r9(e,t){if(void 0!==e&&!(0,S.Z)(e))return e;if(!rt(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch(e){return t.getName()}}function r7(e){return rt(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...r2(e.data.schema),title:e.data.name}}}class ne{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=(0,S.Z)(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...r7(t)})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let n=t??(0,d.Z)(),i={id:n,data:e,name:r9(t,e),metadata:r};return this.nodes[n]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,n){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(i),i}firstNode(){return nt(this)}lastNode(){return nr(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(e=>e.id).every(S.Z)&&(r="");let n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}});let i=e.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}));this.edges=[...this.edges,...i];let o=e.firstNode(),a=e.lastNode();return[o?{id:n(o.id),data:o.data}:void 0,a?{id:n(a.id),data:a.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&nt(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&nr(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),t=new Map;Object.values(e).forEach(e=>{t.set(e,(t.get(e)||0)+1)});let r=r=>{let n=e[r];return(0,S.Z)(r)&&1===t.get(n)?n:r};return new ne({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},o=this.reid(),a=o.firstNode(),s=o.lastNode();return r6(o.nodes,o.edges,{firstNode:a?.id,lastNode:s?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:i})}async drawMermaidPng(e){return r8(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function nt(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),n=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function nr(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),n=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function nn(e){let t=new TextEncoder,r=new ReadableStream({async start(r){for await(let n of e)r.enqueue(t.encode(`event: data
278
278
  data: ${JSON.stringify(n)}
279
279
 
280
- `));r.enqueue(t.encode("event: end\n\n")),r.close()}});return n2.fromReadableStream(r)}function ov(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}let ob=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function o_(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*ow(e,t){for(;;){let{value:r,done:n}=nq.runWithConfig(n0(e),t.next.bind(t),!0);if(n)break;yield r}}async function*ox(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await nq.runWithConfig(n0(e),r.next.bind(t),!0);if(i)break;yield n}}var oS=r(71033);function oE(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class oC extends r6.i{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new oA({bound:this,kwargs:e,config:{}})}map(){return new ok({bound:this})}withRetry(e){return new oO({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new oA({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new o$({runnable:this,fallbacks:Array.isArray(e)?e:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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(nJ);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(([e])=>"runId"!==e));return Array.from({length:t},(t,n)=>nJ(0===n?e:r))}return Array.from({length:t},()=>nJ(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=new id({maxConcurrency:n[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=nJ(t),n=new n4({generator:this._streamIterator(e,r),config:r});return await n.setup,n2.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?nJ(e):nJ({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,i=nJ(r),o=await nX(i),a=await o?.handleChainStart(this.toJSON(),oE(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;try{let o=e.call(this,t,i,a);n=await n1(o,r?.signal)}catch(e){throw await a?.handleChainError(e),e}return await a?.handleChainEnd(oE(n,"output")),n}async _batchWithConfig(e,t,r,n){let i,o=this._getOptionsList(r??{},t.length),a=await Promise.all(o.map(nX)),s=await Promise.all(a.map(async(e,r)=>{let n=await e?.handleChainStart(this.toJSON(),oE(t[r],"input"),o[r].runId,o[r].runType,void 0,void 0,o[r].runName??this.getName());return delete o[r].runId,n}));try{let r=e.call(this,t,o,s,n);i=await n1(r,o?.[0]?.signal)}catch(e){throw await Promise.all(s.map(t=>t?.handleChainError(e))),e}return await Promise.all(s.map(e=>e?.handleChainEnd(oE(i,"output")))),i}async *_transformStreamWithConfig(e,t,r){let n,i,o,a=!0,s=!0,l=nJ(r),u=await nX(l);async function*c(){for await(let t of e){if(a)if(void 0===n)n=t;else try{n=n5(n,t)}catch{n=void 0,a=!1}yield t}}try{let e=await n6(t.bind(this),c(),async()=>u?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName()),r?.signal,l);delete l.runId,o=e.setup;let n=o?.handlers.find(il),a=e.output;void 0!==n&&void 0!==o&&(a=n.tapOutputIterable(o.runId,a));let h=o?.handlers.find(ie);for await(let e of(void 0!==h&&void 0!==o&&(a=h.tapOutputIterable(o.runId,a)),a))if(yield e,s)if(void 0===i)i=e;else try{i=n5(i,e)}catch{i=void 0,s=!1}}catch(e){throw await o?.handleChainError(e,void 0,void 0,void 0,{inputs:oE(n,"input")}),e}await o?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:oE(n,"input")})}getGraph(e){let t=new op,r=t.addNode({name:`${this.getName()}Input`,schema:tM.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:tM.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new oT({first:this,last:oN(e)})}pick(e){return this.pipe(new oB(e))}assign(e){return this.pipe(new oj(new oI({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:n5(r,t);yield*this._streamIterator(r,nJ(t))}async *streamLog(e,t,r){let n=new io({...r,autoClose:!1,_schemaFormat:"original"}),i=nJ(t);yield*this._streamLog(e,n,i)}async *_streamLog(e,t,r){let{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let e=n.copy();e.addHandler(t,!0),r.callbacks=e}let i=this.stream(e,r),o=async function(){try{for await(let e of(await i)){let r=new n9({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else if("v2"===t.version)n=this._streamEventsV2(e,t,r);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');return"text/event-stream"===t.encoding?oy(n):n2.fromAsyncGenerator(n)}async *_streamEventsV2(e,t,r){let n,i=new iu({...r,autoClose:!1}),o=nJ(t),a=o.runId??(0,tN.Z)();o.runId=a;let s=o.callbacks;if(void 0===s)o.callbacks=[i];else if(Array.isArray(s))o.callbacks=s.concat(i);else{let e=s.copy();e.addHandler(i,!0),o.callbacks=e}let l=this,u=async function(){try{let t=await l.stream(e,o);for await(let e of i.tapOutputIterable(a,t));}finally{await i.finish()}}(),c=!1;try{for await(let t of i){if(!c){t.data.input=e,c=!0,n=t.run_id,yield t;continue}t.run_id===n&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{await u}}async *_streamEventsV1(e,t,r){let n,i=!1,o=nJ(t),a=o.tags??[],s=o.metadata??{},l=o.runName??this.getName(),u=new io({...r,autoClose:!1,_schemaFormat:"streaming_events"}),c=new ig({...r});for await(let t of this._streamLog(e,u,o)){if(void 0===(n=n?n.concat(t):n7.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:a,metadata:s,data:{input:e}};c.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t,r={},i=n.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=n;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let n={event:`on_${r.type}_stream`,run_id:r.id,tags:a,metadata:s,name:l,data:t};c.includeEvent(n,r.type)&&(yield n)}}let h=n?.state;if(void 0!==h){let e={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:a,metadata:s,data:{output:h.final_output}};c.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return im(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new oA({bound:this,config:{},configFactories:[n=>({callbacks:[new ip({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return oF(this,e)}}class oA extends oC{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=nY(this.config,...e);return nY(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(nJ(t),this.kwargs))}async batch(e,t,r){let n=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(nJ(e),this.kwargs))):await this._mergeConfig(nJ(t),this.kwargs);return this.bound.batch(e,n,r)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(nJ(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(nJ(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(nJ(t),this.kwargs))}streamEvents(e,t,r){let n=this,i=async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(nJ(t),n.kwargs),version:t.version},r)};return n2.fromAsyncGenerator(i())}static isRunnableBinding(e){return e.bound&&oC.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new oA({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new ip({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class ok extends oC{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new ok({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,nQ(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new ok({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class oO extends oA{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),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 nQ(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return t$(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:t=>this.onFailedAttempt(t,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 i={};try{await t$(async o=>{let a,s=e.map((e,t)=>t).filter(e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error),l=s.map(t=>e[t]),u=s.map(e=>this._patchConfigForRetry(o,t?.[e],r?.[e])),c=await super.batch(l,u,{...n,returnExceptions:!0});for(let e=0;e<c.length;e+=1){let t=c[e],r=s[e];t instanceof Error&&void 0===a&&((a=t).input=l[e]),i[r.toString()]=t}if(a)throw a;return c},{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(n?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class oT extends oC{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r,n=nJ(t),i=await nX(n),o=await i?.handleChainStart(this.toJSON(),oE(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=e;try{let e=[this.first,...this.middle];for(let r=0;r<e.length;r+=1){let i=e[r].invoke(a,nQ(n,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${r+1}`)}));a=await n1(i,t?.signal)}if(t?.signal?.aborted)throw Error("Aborted");r=await this.last.invoke(a,nQ(n,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await o?.handleChainError(e),e}return await o?.handleChainEnd(oE(r,"output")),r}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(nX)),o=await Promise.all(i.map(async(t,r)=>{let i=await t?.handleChainStart(this.toJSON(),oE(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName);return delete n[r].runId,i})),a=e;try{for(let e=0;e<this.steps.length;e+=1){let t=this.steps[e].batch(a,o.map((t,r)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return nQ(n[r],{callbacks:i})}),r);a=await n1(t,n[0]?.signal)}}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(oE(a,"output")))),a}async *_streamIterator(e,t){let r,n=await nX(t),{runId:i,...o}=t??{},a=await n?.handleChainStart(this.toJSON(),oE(e,"input"),i,void 0,void 0,void 0,o?.runName),s=[this.first,...this.middle,this.last],l=!0;async function*u(){yield e}try{let e=s[0].transform(u(),nQ(o,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t<s.length;t+=1){let r=s[t];e=await r.transform(e,nQ(o,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}))}for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,l)if(void 0===r)r=n;else try{r=n5(r,n)}catch(e){r=void 0,l=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(oE(r,"output"))}getGraph(e){let t=new op,r=null;return this.steps.forEach((n,i)=>{let o=n.getGraph(e);0!==i&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),t.extend(o);let a=o.firstNode();if(!a)throw Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,a),r=o.lastNode()}),t}pipe(e){return new oT(oT.isRunnableSequence(e)?{first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}:{first:this.first,middle:[...this.middle,this.last],last:oN(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&oC.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new oT({...n,first:oN(e),middle:t.slice(0,-1).map(oN),last:oN(t[t.length-1])})}}class oI extends oC{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(let[t,r]of(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={},Object.entries(e.steps)))this.steps[t]=oN(r)}static from(e){return new oI({steps:e})}async invoke(e,t){let r=nJ(t),n=await nX(r),i=await n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let o={};try{let n=Object.entries(this.steps).map(async([t,n])=>{o[t]=await n.invoke(e,nQ(r,{callbacks:i?.getChild(`map:key:${t}`)}))});await n1(Promise.all(n),t?.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(o),o}async *_transform(e,t,r){let n={...this.steps},i=n3(e,Object.keys(n).length),o=new Map(Object.entries(n).map(([e,n],o)=>{let a=n.transform(i[o],nQ(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,a.next().then(t=>({key:e,gen:a,result:t}))]}));for(;o.size;){let e=Promise.race(o.values()),{key:t,result:n,gen:i}=await n1(e,r?.signal);o.delete(t),n.done||(yield{[t]:n.value},o.set(t,i.next().then(e=>({key:t,gen:i,result:e}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=nJ(t),i=new n4({generator:this.transform(r(),n),config:n});return await i.setup,n2.fromAsyncGenerator(i)}}class oP extends oC{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!rL(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),n=await nX(r);return n1(this.func(nQ(r,{callbacks:n}),e),r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);if(o_(n)){for await(let e of n)r?.signal?.throwIfAborted(),yield e;return}if(ob(n)){for(;;){r?.signal?.throwIfAborted();let e=n.next();if(e.done)break;yield e.value}return}yield n}static from(e){return new oP({func:e})}}function oR(e){if(rL(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class oM extends oC{static lc_name(){return"RunnableLambda"}constructor(e){if(rL(e.func))return oP.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),oR(e.func),this.func=e.func}static from(e){return new oM({func:e})}async _invoke(e,t,r){return new Promise((n,i)=>{let o=nQ(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??nV)-1});nq.runWithConfig(n0(o),async()=>{try{let r=await this.func(e,{...o});if(r&&oC.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...o,recursionLimit:(o.recursionLimit??nV)-1})}else if(o_(r)){let e;for await(let n of ox(o,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=n5(e,n)}catch(t){e=n}r=e}else if(ov(r)){let e;for(let n of ow(o,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=n5(e,n)}catch(t){e=n}r=e}n(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let n;for await(let t of e)if(void 0===n)n=t;else try{n=n5(n,t)}catch(e){n=t}let i=nQ(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??nV)-1}),o=await new Promise((e,t)=>{nq.runWithConfig(n0(i),async()=>{try{let t=await this.func(n,{...i,config:i});e(t)}catch(e){t(e)}})});if(o&&oC.isRunnable(o)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await o.stream(n,i)))yield e}else if(o_(o))for await(let e of ox(i,o))r?.signal?.throwIfAborted(),yield e;else if(ov(o))for(let e of ow(i,o))r?.signal?.throwIfAborted(),yield e;else yield o}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=nJ(t),i=new n4({generator:this.transform(r(),n),config:n});return await i.setup,n2.fromAsyncGenerator(i)}}class o$ extends oC{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=nJ(t),n=await nX(r),{runId:i,...o}=r,a=await n?.handleChainStart(this.toJSON(),oE(e,"input"),i,void 0,void 0,void 0,o?.runName),s=nQ(o,{callbacks:a?.getChild()});return await nq.runWithConfig(s,async()=>{let t;for(let n of this.runnables()){r?.signal?.throwIfAborted();try{let t=await n.invoke(e,s);return await a?.handleChainEnd(oE(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await a?.handleChainError(t),t})}async *_streamIterator(e,t){let r,n,i,o=nJ(t),a=await nX(o),{runId:s,...l}=o,u=await a?.handleChainStart(this.toJSON(),oE(e,"input"),s,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){o?.signal?.throwIfAborted();let i=nQ(l,{callbacks:u?.getChild()});try{let r=await t.stream(e,i);n=ox(i,r);break}catch(e){void 0===r&&(r=e)}}if(void 0===n){let e=r??Error("No error stored at end of fallback.");throw await u?.handleChainError(e),e}try{for await(let e of n){yield e;try{i=void 0===i?i:n5(i,e)}catch(e){i=void 0}}}catch(e){throw await u?.handleChainError(e),e}await u?.handleChainEnd(oE(i,"output"))}async batch(e,t,r){let n;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),o=await Promise.all(i.map(e=>nX(e))),a=await Promise.all(o.map(async(t,r)=>{let n=await t?.handleChainStart(this.toJSON(),oE(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,n}));for(let t of this.runnables()){i[0].signal?.throwIfAborted();try{let n=await t.batch(e,a.map((e,t)=>nQ(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(oE(n[t],"output")))),n}catch(e){void 0===n&&(n=e)}}if(!n)throw Error("No error stored at end of fallbacks.");throw await Promise.all(a.map(e=>e?.handleChainError(n))),n}}function oN(e){if("function"==typeof e)return new oM({func:e});if(oC.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object.
281
- Instead got an unsupported type.`);{let t={};for(let[r,n]of Object.entries(e))t[r]=oN(n);return new oI({steps:t})}}class oj extends oC{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof oI&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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(),[i,o]=n3(e),a=this.mapper.transform(o,nQ(r,{callbacks:t?.getChild()})),s=a.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!n.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await s).value,a))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=nJ(t),i=new n4({generator:this.transform(r(),n),config:n});return await i.setup,n2.fromAsyncGenerator(i)}}class oB extends oC{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?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 e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=nJ(t),i=new n4({generator:this.transform(r(),n),config:n});return await i.setup,n2.fromAsyncGenerator(i)}}class oL extends oA{constructor(e){super({bound:oT.from([oM.from(async e=>{let t;if((0,oS.u)(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new oS.Y("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function oF(e,t){let r=t.name??e.getName(),n=t.description??t.schema?.description;return new oL(t.schema.constructor===tM.ZodString?{name:r,description:n,schema:tM.object({input:tM.string()}).transform(e=>e.input),bound:e}:{name:r,description:n,schema:t.schema,bound:e})}},71033:function(e,t,r){"use strict";function n(e){return!!(e&&"object"==typeof e&&"type"in e&&"tool_call"===e.type)}r.d(t,{Y:()=>i,u:()=>n});class i extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}},55695:function(e,t,r){"use strict";r.d(t,{Pf:()=>a.PromptTemplate});var n=r(70505),i=r(18524);r(63882);class o extends n.d{static lc_name(){return"PipelinePromptTemplate"}constructor(e){super({...e,inputVariables:[]}),Object.defineProperty(this,"pipelinePrompts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finalPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name);return[...new Set(this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat())]}static extractRequiredInputValues(e,t){return t.reduce((t,r)=>(t[r]=e[r],t),{})}async formatPipelinePrompts(e){let t=await this.mergePartialAndUserVariables(e);for(let{name:e,prompt:r}of this.pipelinePrompts){let n=o.extractRequiredInputValues(t,r.inputVariables);r instanceof i.ks?t[e]=await r.formatMessages(n):t[e]=await r.format(n)}return o.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){let t={...this};return t.inputVariables=this.inputVariables.filter(t=>!(t in e)),t.partialVariables={...this.partialVariables??{},...e},new o(t)}serialize(){throw Error("Not implemented.")}_getPromptType(){return"pipeline"}}var a=r(34367);function s(e){return"object"==typeof e&&null!=e&&"withStructuredOutput"in e&&"function"==typeof e.withStructuredOutput}function l(e){return"object"==typeof e&&null!=e&&"lc_id"in e&&Array.isArray(e.lc_id)&&"langchain_core/runnables/RunnableBinding"===e.lc_id.join("/")}r(88357),r(82188),r(35304);class u extends i.ks{get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","structured"]}),this.schema=e.schema}pipe(e){if(s(e))return super.pipe(e.withStructuredOutput(this.schema));if(l(e)&&s(e.bound))return super.pipe(e.bound.withStructuredOutput(this.schema).bind(e.kwargs??{}).withConfig(e.config));throw Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t){return u.fromMessages(e,{schema:t})}}},91488:function(e,t,r){"use strict";r.d(t,{F:()=>d});let n=28,i=78400,o=0xc40000,a=200;var s=function(e){return e.V1_0="1.0",e.V1_5="1.5",e.DOUBAO_1_5_15B="doubao-1.5-15B",e.DOUBAO_1_5_20B="doubao-1.5-20B",e}({}),l=r(57186);function u(e,t){return Math.round(e/t)*t}function c(e,t){return Math.floor(e/t)*t}function h(e,t){return Math.ceil(e/t)*t}function f(e,t,r=a,s=n,l=i,d=o){if(Math.max(e,t)/Math.min(e,t)>r)return console.error(`absolute aspect ratio must be smaller than ${r}, got ${Math.max(e,t)/Math.min(e,t)}`),null;let p=Math.max(s,u(t,s)),m=Math.max(s,u(e,s));if(m*p>d){let r=Math.sqrt(e*t/d);m=c(e/r,s),p=c(t/r,s)}else if(m*p<l){let r=Math.sqrt(l/(e*t));m=h(e*r,s),p=h(t*r,s)}return[p,m]}function d(e){let{prediction:t,factor:r,mode:n,screenContext:i,scaleFactor:o,modelVer:a}=e;return{parsed:p(t,Array.isArray(r)?r:[r,r],n,i,o,a)}}function p(e,t=[1e3,1e3],r="bc",n,i,o=s.V1_0){let a=null,u=null,c="",h=null;if(o===s.V1_5&&(null==n?void 0:n.height)&&(null==n?void 0:n.width)&&(h=f(n.height,n.width)),e=e.trim(),"bc"===r){if(e.includes("Thought:")){let t=e.match(/Thought: ([\s\S]+?)(?=\s*Action[::]|$)/);t&&(u=t[1].trim())}else if(e.startsWith("Reflection:")){let t=e.match(/Reflection: ([\s\S]+?)Action_Summary: ([\s\S]+?)(?=\s*Action[::]|$)/);t&&(u=t[2].trim(),a=t[1].trim())}else if(e.startsWith("Action_Summary:")){let t=e.match(/Action_Summary: (.+?)(?=\s*Action[::]|$)/);t&&(u=t[1].trim())}if(["Action:","Action:"].some(t=>e.includes(t))){let t=e.split(/Action[::]/);c=t[t.length-1]}else c=e}else if("o1"===r){let t=e.match(/<Thought>\s*(.*?)\s*<\/Thought>/),r=e.match(/\nAction_Summary:\s*(.*?)\s*Action:/),n=e.match(/\nAction:\s*(.*?)\s*<\/Output>/),i=t?t[1]:null,o=r?r[1]:null,a=n?n[1]:null;u=`${i}
280
+ `));r.enqueue(t.encode("event: end\n\n")),r.close()}});return tH.fromReadableStream(r)}function ni(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}let no=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function na(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*ns(e,t){for(;;){let{value:r,done:n}=tN.runWithConfig(tU(e),t.next.bind(t),!0);if(n)break;yield r}}async function*nl(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await tN.runWithConfig(tU(e),r.next.bind(t),!0);if(i)break;yield n}}var nu=r(71033);function nc(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class nh extends eV.i{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new nf({bound:this,kwargs:e,config:{}})}map(){return new nd({bound:this})}withRetry(e){return new np({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new nf({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new n_({runnable:this,fallbacks:Array.isArray(e)?e:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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(tD);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(([e])=>"runId"!==e));return Array.from({length:t},(t,n)=>tD(0===n?e:r))}return Array.from({length:t},()=>tD(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=new t7({maxConcurrency:n[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=tD(t),n=new tq({generator:this._streamIterator(e,r),config:r});return await n.setup,tH.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?tD(e):tD({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,i=tD(r),o=await tB(i),a=await o?.handleChainStart(this.toJSON(),nc(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;try{let o=e.call(this,t,i,a);n=await tZ(o,r?.signal)}catch(e){throw await a?.handleChainError(e),e}return await a?.handleChainEnd(nc(n,"output")),n}async _batchWithConfig(e,t,r,n){let i,o=this._getOptionsList(r??{},t.length),a=await Promise.all(o.map(tB)),s=await Promise.all(a.map(async(e,r)=>{let n=await e?.handleChainStart(this.toJSON(),nc(t[r],"input"),o[r].runId,o[r].runType,void 0,void 0,o[r].runName??this.getName());return delete o[r].runId,n}));try{let r=e.call(this,t,o,s,n);i=await tZ(r,o?.[0]?.signal)}catch(e){throw await Promise.all(s.map(t=>t?.handleChainError(e))),e}return await Promise.all(s.map(e=>e?.handleChainEnd(nc(i,"output")))),i}async *_transformStreamWithConfig(e,t,r){let n,i,o,a=!0,s=!0,l=tD(r),u=await tB(l);async function*c(){for await(let t of e){if(a)if(void 0===n)n=t;else try{n=tW(n,t)}catch{n=void 0,a=!1}yield t}}try{let e=await tV(t.bind(this),c(),async()=>u?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName()),r?.signal,l);delete l.runId,o=e.setup;let n=o?.handlers.find(t4),a=e.output;void 0!==n&&void 0!==o&&(a=n.tapOutputIterable(o.runId,a));let h=o?.handlers.find(tJ);for await(let e of(void 0!==h&&void 0!==o&&(a=h.tapOutputIterable(o.runId,a)),a))if(yield e,s)if(void 0===i)i=e;else try{i=tW(i,e)}catch{i=void 0,s=!1}}catch(e){throw await o?.handleChainError(e,void 0,void 0,void 0,{inputs:nc(n,"input")}),e}await o?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:nc(n,"input")})}getGraph(e){let t=new ne,r=t.addNode({name:`${this.getName()}Input`,schema:h.z.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:h.z.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new nm({first:this,last:nw(e)})}pick(e){return this.pipe(new nS(e))}assign(e){return this.pipe(new nx(new ng({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:tW(r,t);yield*this._streamIterator(r,tD(t))}async *streamLog(e,t,r){let n=new t2({...r,autoClose:!1,_schemaFormat:"original"}),i=tD(t);yield*this._streamLog(e,n,i)}async *_streamLog(e,t,r){let{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let e=n.copy();e.addHandler(t,!0),r.callbacks=e}let i=this.stream(e,r),o=async function(){try{for await(let e of(await i)){let r=new tY({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else if("v2"===t.version)n=this._streamEventsV2(e,t,r);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');return"text/event-stream"===t.encoding?nn(n):tH.fromAsyncGenerator(n)}async *_streamEventsV2(e,t,r){let n,i=new t6({...r,autoClose:!1}),o=tD(t),a=o.runId??(0,d.Z)();o.runId=a;let s=o.callbacks;if(void 0===s)o.callbacks=[i];else if(Array.isArray(s))o.callbacks=s.concat(i);else{let e=s.copy();e.addHandler(i,!0),o.callbacks=e}let l=this,u=async function(){try{let t=await l.stream(e,o);for await(let e of i.tapOutputIterable(a,t));}finally{await i.finish()}}(),c=!1;try{for await(let t of i){if(!c){t.data.input=e,c=!0,n=t.run_id,yield t;continue}t.run_id===n&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{await u}}async *_streamEventsV1(e,t,r){let n,i=!1,o=tD(t),a=o.tags??[],s=o.metadata??{},l=o.runName??this.getName(),u=new t2({...r,autoClose:!1,_schemaFormat:"streaming_events"}),c=new rr({...r});for await(let t of this._streamLog(e,u,o)){if(void 0===(n=n?n.concat(t):tK.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:a,metadata:s,data:{input:e}};c.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t,r={},i=n.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=n;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let n={event:`on_${r.type}_stream`,run_id:r.id,tags:a,metadata:s,name:l,data:t};c.includeEvent(n,r.type)&&(yield n)}}let h=n?.state;if(void 0!==h){let e={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:a,metadata:s,data:{output:h.final_output}};c.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return rt(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new nf({bound:this,config:{},configFactories:[n=>({callbacks:[new re({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return nC(this,e)}}class nf extends nh{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=tL(this.config,...e);return tL(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(tD(t),this.kwargs))}async batch(e,t,r){let n=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(tD(e),this.kwargs))):await this._mergeConfig(tD(t),this.kwargs);return this.bound.batch(e,n,r)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(tD(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(tD(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(tD(t),this.kwargs))}streamEvents(e,t,r){let n=this,i=async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(tD(t),n.kwargs),version:t.version},r)};return tH.fromAsyncGenerator(i())}static isRunnableBinding(e){return e.bound&&nh.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new nf({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new re({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class nd extends nh{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new nd({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,tz(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new nd({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class np extends nf{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),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 tz(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return f(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:t=>this.onFailedAttempt(t,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 i={};try{await f(async o=>{let a,s=e.map((e,t)=>t).filter(e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error),l=s.map(t=>e[t]),u=s.map(e=>this._patchConfigForRetry(o,t?.[e],r?.[e])),c=await super.batch(l,u,{...n,returnExceptions:!0});for(let e=0;e<c.length;e+=1){let t=c[e],r=s[e];t instanceof Error&&void 0===a&&((a=t).input=l[e]),i[r.toString()]=t}if(a)throw a;return c},{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(n?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class nm extends nh{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r,n=tD(t),i=await tB(n),o=await i?.handleChainStart(this.toJSON(),nc(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=e;try{let e=[this.first,...this.middle];for(let r=0;r<e.length;r+=1){let i=e[r].invoke(a,tz(n,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${r+1}`)}));a=await tZ(i,t?.signal)}if(t?.signal?.aborted)throw Error("Aborted");r=await this.last.invoke(a,tz(n,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await o?.handleChainError(e),e}return await o?.handleChainEnd(nc(r,"output")),r}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(tB)),o=await Promise.all(i.map(async(t,r)=>{let i=await t?.handleChainStart(this.toJSON(),nc(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName);return delete n[r].runId,i})),a=e;try{for(let e=0;e<this.steps.length;e+=1){let t=this.steps[e].batch(a,o.map((t,r)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return tz(n[r],{callbacks:i})}),r);a=await tZ(t,n[0]?.signal)}}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(nc(a,"output")))),a}async *_streamIterator(e,t){let r,n=await tB(t),{runId:i,...o}=t??{},a=await n?.handleChainStart(this.toJSON(),nc(e,"input"),i,void 0,void 0,void 0,o?.runName),s=[this.first,...this.middle,this.last],l=!0;async function*u(){yield e}try{let e=s[0].transform(u(),tz(o,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t<s.length;t+=1){let r=s[t];e=await r.transform(e,tz(o,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}))}for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,l)if(void 0===r)r=n;else try{r=tW(r,n)}catch(e){r=void 0,l=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(nc(r,"output"))}getGraph(e){let t=new ne,r=null;return this.steps.forEach((n,i)=>{let o=n.getGraph(e);0!==i&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),t.extend(o);let a=o.firstNode();if(!a)throw Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,a),r=o.lastNode()}),t}pipe(e){return new nm(nm.isRunnableSequence(e)?{first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}:{first:this.first,middle:[...this.middle,this.last],last:nw(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&nh.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new nm({...n,first:nw(e),middle:t.slice(0,-1).map(nw),last:nw(t[t.length-1])})}}class ng extends nh{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(let[t,r]of(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={},Object.entries(e.steps)))this.steps[t]=nw(r)}static from(e){return new ng({steps:e})}async invoke(e,t){let r=tD(t),n=await tB(r),i=await n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let o={};try{let n=Object.entries(this.steps).map(async([t,n])=>{o[t]=await n.invoke(e,tz(r,{callbacks:i?.getChild(`map:key:${t}`)}))});await tZ(Promise.all(n),t?.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(o),o}async *_transform(e,t,r){let n={...this.steps},i=tG(e,Object.keys(n).length),o=new Map(Object.entries(n).map(([e,n],o)=>{let a=n.transform(i[o],tz(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,a.next().then(t=>({key:e,gen:a,result:t}))]}));for(;o.size;){let e=Promise.race(o.values()),{key:t,result:n,gen:i}=await tZ(e,r?.signal);o.delete(t),n.done||(yield{[t]:n.value},o.set(t,i.next().then(e=>({key:t,gen:i,result:e}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=tD(t),i=new tq({generator:this.transform(r(),n),config:n});return await i.setup,tH.fromAsyncGenerator(i)}}class ny extends nh{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!eA(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),n=await tB(r);return tZ(this.func(tz(r,{callbacks:n}),e),r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);if(na(n)){for await(let e of n)r?.signal?.throwIfAborted(),yield e;return}if(no(n)){for(;;){r?.signal?.throwIfAborted();let e=n.next();if(e.done)break;yield e.value}return}yield n}static from(e){return new ny({func:e})}}function nv(e){if(eA(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class nb extends nh{static lc_name(){return"RunnableLambda"}constructor(e){if(eA(e.func))return ny.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),nv(e.func),this.func=e.func}static from(e){return new nb({func:e})}async _invoke(e,t,r){return new Promise((n,i)=>{let o=tz(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??tj)-1});tN.runWithConfig(tU(o),async()=>{try{let r=await this.func(e,{...o});if(r&&nh.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...o,recursionLimit:(o.recursionLimit??tj)-1})}else if(na(r)){let e;for await(let n of nl(o,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=tW(e,n)}catch(t){e=n}r=e}else if(ni(r)){let e;for(let n of ns(o,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=tW(e,n)}catch(t){e=n}r=e}n(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let n;for await(let t of e)if(void 0===n)n=t;else try{n=tW(n,t)}catch(e){n=t}let i=tz(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??tj)-1}),o=await new Promise((e,t)=>{tN.runWithConfig(tU(i),async()=>{try{let t=await this.func(n,{...i,config:i});e(t)}catch(e){t(e)}})});if(o&&nh.isRunnable(o)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await o.stream(n,i)))yield e}else if(na(o))for await(let e of nl(i,o))r?.signal?.throwIfAborted(),yield e;else if(ni(o))for(let e of ns(i,o))r?.signal?.throwIfAborted(),yield e;else yield o}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=tD(t),i=new tq({generator:this.transform(r(),n),config:n});return await i.setup,tH.fromAsyncGenerator(i)}}class n_ extends nh{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=tD(t),n=await tB(r),{runId:i,...o}=r,a=await n?.handleChainStart(this.toJSON(),nc(e,"input"),i,void 0,void 0,void 0,o?.runName),s=tz(o,{callbacks:a?.getChild()});return await tN.runWithConfig(s,async()=>{let t;for(let n of this.runnables()){r?.signal?.throwIfAborted();try{let t=await n.invoke(e,s);return await a?.handleChainEnd(nc(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await a?.handleChainError(t),t})}async *_streamIterator(e,t){let r,n,i,o=tD(t),a=await tB(o),{runId:s,...l}=o,u=await a?.handleChainStart(this.toJSON(),nc(e,"input"),s,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){o?.signal?.throwIfAborted();let i=tz(l,{callbacks:u?.getChild()});try{let r=await t.stream(e,i);n=nl(i,r);break}catch(e){void 0===r&&(r=e)}}if(void 0===n){let e=r??Error("No error stored at end of fallback.");throw await u?.handleChainError(e),e}try{for await(let e of n){yield e;try{i=void 0===i?i:tW(i,e)}catch(e){i=void 0}}}catch(e){throw await u?.handleChainError(e),e}await u?.handleChainEnd(nc(i,"output"))}async batch(e,t,r){let n;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),o=await Promise.all(i.map(e=>tB(e))),a=await Promise.all(o.map(async(t,r)=>{let n=await t?.handleChainStart(this.toJSON(),nc(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,n}));for(let t of this.runnables()){i[0].signal?.throwIfAborted();try{let n=await t.batch(e,a.map((e,t)=>tz(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(nc(n[t],"output")))),n}catch(e){void 0===n&&(n=e)}}if(!n)throw Error("No error stored at end of fallbacks.");throw await Promise.all(a.map(e=>e?.handleChainError(n))),n}}function nw(e){if("function"==typeof e)return new nb({func:e});if(nh.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object.
281
+ Instead got an unsupported type.`);{let t={};for(let[r,n]of Object.entries(e))t[r]=nw(n);return new ng({steps:t})}}class nx extends nh{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof ng&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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(),[i,o]=tG(e),a=this.mapper.transform(o,tz(r,{callbacks:t?.getChild()})),s=a.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!n.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await s).value,a))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=tD(t),i=new tq({generator:this.transform(r(),n),config:n});return await i.setup,tH.fromAsyncGenerator(i)}}class nS extends nh{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?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 e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=tD(t),i=new tq({generator:this.transform(r(),n),config:n});return await i.setup,tH.fromAsyncGenerator(i)}}class nE extends nf{constructor(e){super({bound:nm.from([nb.from(async e=>{let t;if((0,nu.u)(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new nu.Y("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function nC(e,t){let r=t.name??e.getName(),n=t.description??t.schema?.description;return new nE(t.schema.constructor===h.z.ZodString?{name:r,description:n,schema:h.z.object({input:h.z.string()}).transform(e=>e.input),bound:e}:{name:r,description:n,schema:t.schema,bound:e})}},71033:function(e,t,r){"use strict";function n(e){return!!(e&&"object"==typeof e&&"type"in e&&"tool_call"===e.type)}r.d(t,{Y:()=>i,u:()=>n});class i extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}},55695:function(e,t,r){"use strict";r.d(t,{Pf:()=>a.PromptTemplate});var n=r(70505),i=r(18524);r(63882);class o extends n.d{static lc_name(){return"PipelinePromptTemplate"}constructor(e){super({...e,inputVariables:[]}),Object.defineProperty(this,"pipelinePrompts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finalPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name);return[...new Set(this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat())]}static extractRequiredInputValues(e,t){return t.reduce((t,r)=>(t[r]=e[r],t),{})}async formatPipelinePrompts(e){let t=await this.mergePartialAndUserVariables(e);for(let{name:e,prompt:r}of this.pipelinePrompts){let n=o.extractRequiredInputValues(t,r.inputVariables);r instanceof i.ks?t[e]=await r.formatMessages(n):t[e]=await r.format(n)}return o.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){let t={...this};return t.inputVariables=this.inputVariables.filter(t=>!(t in e)),t.partialVariables={...this.partialVariables??{},...e},new o(t)}serialize(){throw Error("Not implemented.")}_getPromptType(){return"pipeline"}}var a=r(34367);function s(e){return"object"==typeof e&&null!=e&&"withStructuredOutput"in e&&"function"==typeof e.withStructuredOutput}function l(e){return"object"==typeof e&&null!=e&&"lc_id"in e&&Array.isArray(e.lc_id)&&"langchain_core/runnables/RunnableBinding"===e.lc_id.join("/")}r(88357),r(82188),r(35304);class u extends i.ks{get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","structured"]}),this.schema=e.schema}pipe(e){if(s(e))return super.pipe(e.withStructuredOutput(this.schema));if(l(e)&&s(e.bound))return super.pipe(e.bound.withStructuredOutput(this.schema).bind(e.kwargs??{}).withConfig(e.config));throw Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t){return u.fromMessages(e,{schema:t})}}},91488:function(e,t,r){"use strict";r.d(t,{F:()=>d});let n=28,i=78400,o=0xc40000,a=200;var s=function(e){return e.V1_0="1.0",e.V1_5="1.5",e.DOUBAO_1_5_15B="doubao-1.5-15B",e.DOUBAO_1_5_20B="doubao-1.5-20B",e}({}),l=r(57186);function u(e,t){return Math.round(e/t)*t}function c(e,t){return Math.floor(e/t)*t}function h(e,t){return Math.ceil(e/t)*t}function f(e,t,r=a,s=n,l=i,d=o){if(Math.max(e,t)/Math.min(e,t)>r)return console.error(`absolute aspect ratio must be smaller than ${r}, got ${Math.max(e,t)/Math.min(e,t)}`),null;let p=Math.max(s,u(t,s)),m=Math.max(s,u(e,s));if(m*p>d){let r=Math.sqrt(e*t/d);m=c(e/r,s),p=c(t/r,s)}else if(m*p<l){let r=Math.sqrt(l/(e*t));m=h(e*r,s),p=h(t*r,s)}return[p,m]}function d(e){let{prediction:t,factor:r,mode:n,screenContext:i,scaleFactor:o,modelVer:a}=e;return{parsed:p(t,Array.isArray(r)?r:[r,r],n,i,o,a)}}function p(e,t=[1e3,1e3],r="bc",n,i,o=s.V1_0){let a=null,u=null,c="",h=null;if(o===s.V1_5&&(null==n?void 0:n.height)&&(null==n?void 0:n.width)&&(h=f(n.height,n.width)),e=e.trim(),"bc"===r){if(e.includes("Thought:")){let t=e.match(/Thought: ([\s\S]+?)(?=\s*Action[::]|$)/);t&&(u=t[1].trim())}else if(e.startsWith("Reflection:")){let t=e.match(/Reflection: ([\s\S]+?)Action_Summary: ([\s\S]+?)(?=\s*Action[::]|$)/);t&&(u=t[2].trim(),a=t[1].trim())}else if(e.startsWith("Action_Summary:")){let t=e.match(/Action_Summary: (.+?)(?=\s*Action[::]|$)/);t&&(u=t[1].trim())}if(["Action:","Action:"].some(t=>e.includes(t))){let t=e.split(/Action[::]/);c=t[t.length-1]}else c=e}else if("o1"===r){let t=e.match(/<Thought>\s*(.*?)\s*<\/Thought>/),r=e.match(/\nAction_Summary:\s*(.*?)\s*Action:/),n=e.match(/\nAction:\s*(.*?)\s*<\/Output>/),i=t?t[1]:null,o=r?r[1]:null,a=n?n[1]:null;u=`${i}
282
282
  <Action_Summary>
283
283
  ${o}`,c=a||""}let d=c.split("\n\n"),g=[];for(let e of d){let r=m(e.replace(/\n/g,String.raw`\n`).trimStart()),c="",f={};if(r)for(let[e,a]of(c=r.function,f={},Object.entries(r.args))){if(!a)continue;let r=a.trim();if(e.includes("start_box")||e.includes("end_box")){let a=r.replace(/[()[\]]/g,"").split(",").filter(e=>""!==e).map((e,r)=>{let n=r%2;return o===s.V1_5&&h?Number.parseFloat(e)/h[n]:Number.parseFloat(e)/t[n]});if(2===a.length&&a.push(a[0],a[1]),f[e.trim()]=JSON.stringify(a),(null==n?void 0:n.width)&&(null==n?void 0:n.height)){let r=e.includes("start_box")?"start_coords":"end_coords",[o,s,u=o,c=s]=a,[h,d]=t;f[r]=[o,s,u,c].every(l)?[Math.round((o+u)/2*(null==n?void 0:n.width)*h)/h*(i??1),Math.round((s+c)/2*(null==n?void 0:n.height)*d)/d*(i??1)]:[]}}else f[e.trim()]=r}g.push({reflection:a,thought:u||"",action_type:c,action_inputs:f})}return g}function m(e){try{e=(e=e.replace(/<\|box_start\|>|<\|box_end\|>/g,"")).replace(/(?<!start_|end_)point=/g,"start_box=").replace(/start_point=/g,"start_box=").replace(/end_point=/g,"end_box=");let t=/^(\w+)\((.*)\)$/,r=e.trim().match(t);if(!r)throw Error("Not a function call");let[n,i,o]=r,a={};if(o.trim())for(let e of o.match(/([^,']|'[^']*')+/g)||[]){let[t,...r]=e.split("=");if(!t)continue;let n=r.join("=").trim().replace(/^['"]|['"]$/g,"");n.includes("<bbox>")&&(n=n.replace(/<bbox>|<\/bbox>/g,"").replace(/\s+/g,","),n=`(${n})`),n.includes("<point>")&&(n=n.replace(/<point>|<\/point>/g,"").replace(/\s+/g,","),n=`(${n})`),a[t.trim()]=n}return{function:i,args:a}}catch(t){return console.error(`Failed to parse action '${e}': ${t}`),null}}},7370:function(e,t,r){"use strict";r.d(t,{v:()=>n});class n{listeners=[];constructor(){this.event=this.event.bind(this)}addEventListener(e){this.listeners.push(e);let t=()=>{let t=this.listeners.indexOf(e);-1!==t&&this.listeners.splice(t,1)};return t.dispose=t,t}event=(e,t,...r)=>{let n={listener:e,thisArg:t,args:r};return this.addEventListener(n)};fire(e){for(let t of this.listeners.slice())t.listener.apply(t.thisArg,[e,...t.args])}dispose(){this.listeners.length=0}}},67979:function(e,t,r){"use strict";let n;r.d(t,{v:()=>b});class i{#e;get promise(){return this.#e}#t;#r;#n="running";get state(){return this.#n}constructor(){this.#e=new Promise((e,t)=>{this.#t=e,this.#r=t})}resolve=e=>{this.#t(e),this.#n="resolved"};reject=e=>{this.#r(e),this.#n="rejected"}}var o=r(7370),a=r(23711),s=r(12649),l=r(89940),u=r(80969);class c{#i=[];constructor(){this.dispose=this.dispose.bind(this)}addDisposable(e){return this.#i.push(e),e}dispose(){for(let e of this.#i)e.dispose();this.#i=[]}}let h=!1,f=[],d=0,p=new Map;function m(e,t){return p.set(e,t),{dispose(){p.delete(e)}}}class g extends c{streamId;#o=new o.v;get onPictureReady(){return this.#o.event}constructor(e){super(),this.streamId=e,this.addDisposable(m(e,this.#a))}#a=e=>{this.#o.fire(e)};feed(e){n.postMessage({type:"decode",data:e,offset:0,length:e.byteLength,renderStateId:this.streamId},[e])}dispose(){super.dispose(),n.postMessage({type:"release",renderStateId:this.streamId})}}function y(){if(n||(n=new Worker(new URL(r.p+r.u("166"),r.b),Object.assign({},{type:"module"},{type:void 0}))).addEventListener("message",({data:e})=>{switch(e.type){case"decoderReady":for(let e of(h=!0,f))e.resolve(new g(d)),d+=1;f.length=0;break;case"pictureReady":p.get(e.renderStateId)?.(e)}}),!h){let e=new i;return f.push(e),e.promise}let e=new g(d);return d+=1,Promise.resolve(e)}let v=()=>{};function b(){if("undefined"!=typeof document)return document.createElement("canvas");if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(1,1);throw Error("no canvas input found nor any canvas can be created")}class _{static capabilities={h264:{maxProfile:a.vo.Baseline,maxLevel:a.Nm.Level4}};#s;get renderer(){return this.#s}#l=new o.v;get sizeChanged(){return this.#l.event}#u=0;get framesRendered(){return this.#u}#c=0;get framesSkipped(){return this.#c}#h;get writable(){return this.#h}#f;#d;constructor({canvas:e}={}){e?this.#s=e:this.#s=b(),this.#h=new s.Vj({write:async e=>{switch(e.type){case"configuration":await this.#p(e.data);break;case"data":if(!this.#d)throw Error("Decoder not configured");(await this.#d.promise).feed(e.data.slice().buffer)}}})}async #p(e){if(this.dispose(),this.#d=new i,!this.#f){let e=b(),t={failIfMajorPerformanceCaveat:!0},r=e.getContext("webgl2",t)||e.getContext("webgl",t);this.#f=u.attach(this.#s,{webGL:!!r})}let{encodedWidth:t,encodedHeight:r,croppedWidth:n,croppedHeight:o,cropLeft:s,cropTop:c}=(0,a.VM)(e);this.#l.fire({width:n,height:o});let h=t/2,f=r/2,d=l.format({width:t,height:r,chromaWidth:h,chromaHeight:f,cropLeft:s,cropTop:c,cropWidth:n,cropHeight:o,displayWidth:n,displayHeight:o}),p=await y();this.#d.resolve(p);let m=t*r,g=m+h*f;p.onPictureReady(({data:e})=>{this.#u+=1;let r=new Uint8Array(e),n=l.frame(d,l.lumaPlane(d,r,t,0),l.chromaPlane(d,r,h,m),l.chromaPlane(d,r,h,g));this.#f.drawFrame(n)}),p.feed(e.slice().buffer)}dispose(){this.#d?.promise.then(e=>e.dispose()).catch(v),this.#d=void 0}}},81138:function(e,t,r){"use strict";r.d(t,{h:()=>U});var n=r(7370),i=r(92882),o=r(12649),a=r(23711);class s{#m;#g;constructor(e){this.#g=e}decode(e){let t;if("configuration"===e.type){this.#m=e.data,this.configure(e.data);return}void 0!==this.#m?((t=new Uint8Array(this.#m.length+e.data.length)).set(this.#m,0),t.set(e.data,this.#m.length),this.#m=void 0):t=e.data,this.#g.decode(new EncodedVideoChunk({type:!1===e.keyframe?"delta":"key",timestamp:0,data:t}))}}function l(e){return e.toString(16).toUpperCase()}function u(e){return e.toString(16).toUpperCase().padStart(2,"0")}function c(e){return e.toString(10).padStart(2,"0")}class h extends s{#g;#y;constructor(e,t){super(e),this.#g=e,this.#y=t}configure(e){let{profileIndex:t,constraintSet:r,levelIndex:n,croppedWidth:i,croppedHeight:o}=(0,a.VM)(e);this.#y(i,o);let s="avc1."+u(t)+u(r)+u(n);this.#g.configure({codec:s,optimizeForLatency:!0})}}function f(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}var d=r(25170);function p(e){switch(e){case 0:case 3:return 1;case 1:case 2:return 2;default:throw Error("Invalid chroma_format_idc")}}function m(e){switch(e){case 0:case 2:case 3:return 1;case 1:return 2;default:throw Error("Invalid chroma_format_idc")}}function g(e){let t=new d.t(e);if(0!==t.next())throw Error("Invalid NALU header");let r=t.read(6);return{nal_unit_type:r,nuh_layer_id:t.read(6),nuh_temporal_id_plus1:t.read(3)}}function y(e){let t,r,n,i,o,a,s,l,u=new d.t(e),c=u.read(4),h=!!u.next(),f=!!u.next(),p=u.read(6),m=u.read(3),g=!!u.next();u.skip(16);let y=_(u,!0,m),v=!!u.next(),b=[],w=[],x=[];for(let e=v?0:m;e<=m;e+=1)b[e]=u.decodeExponentialGolombNumber(),w[e]=u.decodeExponentialGolombNumber(),x[e]=u.decodeExponentialGolombNumber();let S=u.read(6),C=u.decodeExponentialGolombNumber(),A=[];for(let e=1;e<=C;e+=1){A[e]=[];for(let t=0;t<=S;t+=1)A[e][t]=!!u.next()}let k=!!u.next();if(k){t=u.read(32),r=u.read(32),(n=!!u.next())&&(i=u.decodeExponentialGolombNumber()),o=u.decodeExponentialGolombNumber(),a=[],s=[!0],l=[];for(let e=0;e<o;e+=1)a[e]=u.decodeExponentialGolombNumber(),e>0&&(s[e]=!!u.next()),l[e]=E(u,s[e],m)}return{vps_video_parameter_set_id:c,vps_base_layer_internal_flag:h,vps_base_layer_available_flag:f,vps_max_layers_minus1:p,vps_max_sub_layers_minus1:m,vps_temporal_id_nesting_flag:g,profileTierLevel:y,vps_sub_layer_ordering_info_present_flag:v,vps_max_dec_pic_buffering_minus1:b,vps_max_num_reorder_pics:w,vps_max_latency_increase_plus1:x,vps_max_layer_id:S,vps_num_layer_sets_minus1:C,layer_id_included_flag:A,vps_timing_info_present_flag:k,vps_num_units_in_tick:t,vps_time_scale:r,vps_poc_proportional_to_timing_flag:n,vps_num_ticks_poc_diff_one_minus1:i,vps_num_hrd_parameters:o,hrd_layer_set_idx:a,cprms_present_flag:s,hrdParameters:l,vps_extension_flag:!!u.next()}}function v(e){let t,r,n,i,o,a,s,l,u,c,h,f,p,m,g,y,v,b,E,C,A,k,I,P,R=new d.t(e),M=R.read(4),$=R.read(3),N=!!R.next(),j=_(R,!0,$),B=R.decodeExponentialGolombNumber(),L=R.decodeExponentialGolombNumber();3===L&&(t=!!R.next());let F=R.decodeExponentialGolombNumber(),D=R.decodeExponentialGolombNumber(),z=!!R.next();z&&(r=R.decodeExponentialGolombNumber(),n=R.decodeExponentialGolombNumber(),i=R.decodeExponentialGolombNumber(),o=R.decodeExponentialGolombNumber());let U=R.decodeExponentialGolombNumber(),Z=R.decodeExponentialGolombNumber(),H=R.decodeExponentialGolombNumber(),G=[],W=[],q=[],V=!!R.next();for(let e=V?0:$;e<=$;e+=1)G[e]=R.decodeExponentialGolombNumber(),W[e]=R.decodeExponentialGolombNumber(),q[e]=R.decodeExponentialGolombNumber();let X=R.decodeExponentialGolombNumber(),Y=R.decodeExponentialGolombNumber(),K=R.decodeExponentialGolombNumber(),J=R.decodeExponentialGolombNumber(),Q=R.decodeExponentialGolombNumber(),ee=R.decodeExponentialGolombNumber(),et=!!R.next();et&&(a=!!R.next())&&(s=w(R));let er=!!R.next(),en=!!R.next(),ei=!!R.next();ei&&(l=R.read(4),u=R.read(4),c=R.read(4),h=R.read(4),f=!!R.next());let eo=R.decodeExponentialGolombNumber(),ea=[];for(let e=0;e<eo;e+=1)ea[e]=x(R,e,eo,ea);let es=!!R.next();if(es){p=R.decodeExponentialGolombNumber(),m=[],g=[];for(let e=0;e<p;e+=1)m[e]=R.read(H+4),g[e]=!!R.next()}let el=!!R.next(),eu=!!R.next(),ec=!!R.next();ec&&(y=S(R,$));let eh=!!R.next();if(eh&&(v=!!R.next(),b=!!R.next(),E=!!R.next(),C=!!R.next(),A=R.read(4)),v||(b&&(k=O(R)),E&&(I=T(R)),C))throw Error("Not implemented");if(A){P=[];let e=0;for(;!R.ended;)P[e]=!!R.next(),e+=1}return{sps_video_parameter_set_id:M,sps_max_sub_layers_minus1:$,sps_temporal_id_nesting_flag:N,profileTierLevel:j,sps_seq_parameter_set_id:B,chroma_format_idc:L,separate_colour_plane_flag:t,pic_width_in_luma_samples:F,pic_height_in_luma_samples:D,conformance_window_flag:z,conf_win_left_offset:r,conf_win_right_offset:n,conf_win_top_offset:i,conf_win_bottom_offset:o,bit_depth_luma_minus8:U,bit_depth_chroma_minus8:Z,log2_max_pic_order_cnt_lsb_minus4:H,sps_sub_layer_ordering_info_present_flag:V,sps_max_dec_pic_buffering_minus1:G,sps_max_num_reorder_pics:W,sps_max_latency_increase_plus1:q,log2_min_luma_coding_block_size_minus3:X,log2_diff_max_min_luma_coding_block_size:Y,log2_min_luma_transform_block_size_minus2:K,log2_diff_max_min_luma_transform_block_size:J,max_transform_hierarchy_depth_inter:Q,max_transform_hierarchy_depth_intra:ee,scaling_list_enabled_flag:et,sps_scaling_list_data_present_flag:a,scalingListData:s,amp_enabled_flag:er,sample_adaptive_offset_enabled_flag:en,pcm_enabled_flag:ei,pcm_sample_bit_depth_luma_minus1:l,pcm_sample_bit_depth_chroma_minus1:u,log2_min_pcm_luma_coding_block_size_minus3:c,log2_diff_max_min_pcm_luma_coding_block_size:h,pcm_loop_filter_disabled_flag:f,num_short_term_ref_pic_sets:eo,shortTermRefPicSets:ea,long_term_ref_pics_present_flag:es,num_long_term_ref_pics_sps:p,lt_ref_pic_poc_lsb_sps:m,used_by_curr_pic_lt_sps_flag:g,sps_temporal_mvp_enabled_flag:el,strong_intra_smoothing_enabled_flag:eu,vui_parameters_present_flag:ec,vuiParameters:y,sps_extension_present_flag:eh,sps_range_extension_flag:v,sps_multilayer_extension_flag:b,sps_3d_extension_flag:E,sps_scc_extension_flag:C,sps_extension_4bits:A,spsMultilayerExtension:k,sps3dExtension:I,sps_extension_data_flag:P}}function b(e){let t,r,n,i,o,a,s,l,u,c,h,f=e.read(2),d=!!e.next(),p=e.read(5),m=e.peekBytes(4),g=[];for(let t=0;t<32;t+=1)g[t]=!!e.next();let y=e.peekBytes(6),v=!!e.next(),b=!!e.next(),_=!!e.next(),w=!!e.next();return 4===p||g[4]||5===p||g[5]||6===p||g[6]||7===p||g[7]||8===p||g[8]||9===p||g[9]||10===p||g[10]||11===p||g[11]?(t=!!e.next(),r=!!e.next(),n=!!e.next(),i=!!e.next(),o=!!e.next(),a=!!e.next(),s=!!e.next(),l=!!e.next(),u=!!e.next(),5===p||g[5]||9===p||g[9]||10===p||g[10]||11===p||g[11]?(c=!!e.next(),e.skip(33)):e.skip(34)):2===p||g[2]?(e.skip(7),l=!!e.next(),e.skip(35)):e.skip(43),1===p||g[1]||2===p||g[2]||3===p||g[3]||4===p||g[4]||5===p||g[5]||9===p||g[9]||11===p||g[11]?h=!!e.next():e.skip(1),{profile_space:f,tier_flag:d,profile_idc:p,profileCompatibilitySet:m,profile_compatibility_flag:g,constraintSet:y,progressive_source_flag:v,interlaced_source_flag:b,non_packed_constraint_flag:_,frame_only_constraint_flag:w,max_12bit_constraint_flag:t,max_10bit_constraint_flag:r,max_8bit_constraint_flag:n,max_422chroma_constraint_flag:i,max_420chroma_constraint_flag:o,max_monochrome_constraint_flag:a,intra_constraint_flag:s,one_picture_only_constraint_flag:l,lower_bit_rate_constraint_flag:u,max_14bit_constraint_flag:c,inbld_flag:h}}function _(e,t,r){let n;t&&(n=b(e));let i=e.read(8),o=[],a=[];for(let t=0;t<r;t+=1)o[t]=!!e.next(),a[t]=!!e.next();if(r>0)for(let t=r;t<8;t+=1)e.read(2);let s=[],l=[];for(let t=0;t<r;t+=1)o[t]&&(s[t]=b(e)),a[t]&&(l[t]=e.read(8));return{generalProfileTier:n,general_level_idc:i,sub_layer_profile_present_flag:o,sub_layer_level_present_flag:a,subLayerProfileTier:s,sub_layer_level_idc:l}}function w(e){let t=[];for(let r=0;r<4;r+=1){t[r]=[];for(let n=0;n<6;n+=3===r?3:1)if(e.next()){let i=8,o=Math.min(64,1<<4+(r<<1));r>1&&(i=e.decodeExponentialGolombNumber()+8),t[r][n]=[];for(let a=0;a<o;a+=1)i=(i+e.decodeExponentialGolombNumber()+256)%256,t[r][n][a]=i}else e.decodeExponentialGolombNumber()}return t}function x(e,t,r,n){let i=!1;0!==t&&(i=!!e.next());let o=0,a=!1,s=0,l=[],u=[],c=0,h=0,f=[],d=[],p=[],m=[];if(i){t===r&&(o=e.decodeExponentialGolombNumber()),a=!!e.next(),s=e.decodeExponentialGolombNumber();let i=n[t-(o+1)],g=i.num_negative_pics+i.num_positive_pics;for(let t=0;t<=g;t+=1)l[t]=!!e.next(),l[t]?u[t]=!0:u[t]=!!e.next();let y=(1-2*Number(a))*(s+1),v=[],b=[],_=[],w=[],x=0;for(let e=0;e<i.num_negative_pics;e+=1)x-=i.delta_poc_s0_minus1[e]+1,v[e]=x;x=0;for(let e=0;e<i.num_positive_pics;e+=1)x+=i.delta_poc_s1_minus1[e]+1,b[e]=x;let S=0;if(i.num_positive_pics>0)for(let e=i.num_positive_pics-1;e>=0;e-=1)(x=b[e]+y)<0&&u[i.num_negative_pics+e]&&(_[S]=x,d[S]=l[i.num_negative_pics+e],S+=1);y<0&&u[g]&&(_[S]=y,d[S]=l[g],S+=1);for(let e=0;e<i.num_negative_pics;e+=1)(x=v[e]+y)<0&&u[e]&&(_[S]=x,d[S]=l[e],S+=1);c=S;let E=0;for(S=0;S<c;S+=1){let e=_[S];f[S]=-(e-E-1),E=e}if(S=0,i.num_negative_pics>0)for(let e=i.num_negative_pics-1;e>=0;e-=1)(x=v[e]+y)>0&&u[e]&&(w[S]=x,m[S]=l[e],S+=1);y>0&&u[g]&&(w[S]=y,m[S]=l[g],S+=1);for(let e=0;e<i.num_positive_pics;e+=1)(x=b[e]+y)>0&&u[i.num_negative_pics+e]&&(w[S]=x,m[S]=l[i.num_negative_pics+e],S+=1);for(h=S,E=0,S=0;S<h;S+=1){let e=w[S];p[S]=e-E-1,E=e}}else{c=e.decodeExponentialGolombNumber(),h=e.decodeExponentialGolombNumber();for(let t=0;t<c;t+=1)f[t]=e.decodeExponentialGolombNumber(),d[t]=!!e.next();for(let t=0;t<h;t+=1)p[t]=e.decodeExponentialGolombNumber(),m[t]=!!e.next()}return{stRpsIdx:t,num_short_term_ref_pic_sets:r,inter_ref_pic_set_prediction_flag:i,delta_idx_minus1:o,delta_rps_sign:a,abs_delta_rps_minus1:s,used_by_curr_pic_flag:l,use_delta_flag:u,num_negative_pics:c,num_positive_pics:h,delta_poc_s0_minus1:f,used_by_curr_pic_s0_flag:d,delta_poc_s1_minus1:p,used_by_curr_pic_s1_flag:m}}function S(e,t){let r,n,i,o,a,s,l,u,c,h,f,d,p,m,g,y,v,b,_,w,x,S,C,A,k,O,T,I,P,R,M=!!e.next();M&&255===(r=e.read(8))&&(n=e.read(16),i=e.read(16));let $=!!e.next();$&&(o=!!e.next());let N=!!e.next();N&&(a=e.read(3),s=!!e.next(),(l=!!e.next())&&(u=e.read(8),c=e.read(8),h=e.read(8)));let j=!!e.next();j&&(f=e.decodeExponentialGolombNumber(),d=e.decodeExponentialGolombNumber());let B=!!e.next(),L=!!e.next(),F=!!e.next(),D=!!e.next();D&&(p=e.decodeExponentialGolombNumber(),m=e.decodeExponentialGolombNumber(),g=e.decodeExponentialGolombNumber(),y=e.decodeExponentialGolombNumber());let z=!!e.next();z&&(v=e.read(32),b=e.read(32),(_=!!e.next())&&(w=e.decodeExponentialGolombNumber()),(x=!!e.next())&&(S=E(e,!0,t)));let U=!!e.next();return U&&(C=!!e.next(),A=!!e.next(),k=!!e.next(),O=e.decodeExponentialGolombNumber(),T=e.decodeExponentialGolombNumber(),I=e.decodeExponentialGolombNumber(),P=e.decodeExponentialGolombNumber(),R=e.decodeExponentialGolombNumber()),{aspect_ratio_info_present_flag:M,aspect_ratio_idc:r,sar_width:n,sar_height:i,overscan_info_present_flag:$,overscan_appropriate_flag:o,video_signal_type_present_flag:N,video_format:a,video_full_range_flag:s,colour_description_present_flag:l,colour_primaries:u,transfer_characteristics:c,matrix_coeffs:h,chroma_loc_info_present_flag:j,chroma_sample_loc_type_top_field:f,chroma_sample_loc_type_bottom_field:d,neutral_chroma_indication_flag:B,field_seq_flag:L,frame_field_info_present_flag:F,default_display_window_flag:D,def_disp_win_left_offset:p,def_disp_win_right_offset:m,def_disp_win_top_offset:g,def_disp_win_bottom_offset:y,vui_timing_info_present_flag:z,vui_num_units_in_tick:v,vui_time_scale:b,vui_poc_proportional_to_timing_flag:_,vui_num_ticks_poc_diff_one_minus1:w,vui_hrd_parameters_present_flag:x,vui_hrd_parameters:S,bitstream_restriction_flag:U,tiles_fixed_structure_flag:C,motion_vectors_over_pic_boundaries_flag:A,restricted_ref_pic_lists_flag:k,min_spatial_segmentation_idc:O,max_bytes_per_pic_denom:T,max_bits_per_min_cu_denom:I,log2_max_mv_length_horizontal:P,log2_max_mv_length_vertical:R}}function E(e,t,r){let n,i,o,a,s,l,u,c,h,f,d,p,m;t&&(n=!!e.next(),i=!!e.next(),(n||i)&&((o=!!e.next())&&(a=e.read(8),s=e.read(5),l=!!e.next(),u=e.read(5)),c=e.read(4),h=e.read(4),o&&(f=e.read(4)),d=e.read(5),p=e.read(5),m=e.read(5)));let g=[],y=[],v=[],b=[],_=[],w=[],x=[];for(let t=0;t<=r;t+=1)g[t]=!!e.next(),g[t]||(y[t]=!!e.next()),y[t]?v[t]=e.decodeExponentialGolombNumber():b[t]=!!e.next(),b[t]||(_[t]=e.decodeExponentialGolombNumber()),n&&(w[t]=C(e,t,A(_[t]))),i&&(x[t]=C(e,t,A(_[t])));return{nal_hrd_parameters_present_flag:n,vcl_hrd_parameters_present_flag:i,sub_pic_hrd_params_present_flag:o,tick_divisor_minus2:a,du_cpb_removal_delay_increment_length_minus1:s,sub_pic_cpb_params_in_pic_timing_sei_flag:l,dpb_output_delay_du_length_minus1:u,bit_rate_scale:c,cpb_size_scale:h,cpb_size_du_scale:f,initial_cpb_removal_delay_length_minus1:d,au_cpb_removal_delay_length_minus1:p,dpb_output_delay_length_minus1:m,fixed_pic_rate_general_flag:g,fixed_pic_rate_within_cvs_flag:y,elemental_duration_in_tc_minus1:v,low_delay_hrd_flag:b,cpb_cnt_minus1:_,nalHrdParameters:w,vclHrdParameters:x}}function C(e,t,r){let n=[],i=[],o=[],a=[],s=[];for(let o=0;o<r;o+=1)n[o]=e.decodeExponentialGolombNumber(),i[o]=e.decodeExponentialGolombNumber(),t>0&&(s[o]=!!e.next());return{bit_rate_value_minus1:n,cpb_size_value_minus1:i,cpb_size_du_value_minus1:o,bit_rate_du_value_minus1:a,cbr_flag:s}}function A(e){return e+1}function k(e){let t,r,n,i=0;for(let o of(0,d.q)(e)){let e=g(o),a={...e,data:o,rbsp:o.subarray(2)};switch(e.nal_unit_type){case 32:t=a;break;case 33:r=a;break;case 34:n=a;break;default:continue}if(3===(i+=1))return{videoParameterSet:t,sequenceParameterSet:r,pictureParameterSet:n}}throw Error("Invalid data")}function O(e){return{inter_view_mv_vert_constraint_flag:!!e.next()}}function T(e){let t=[],r=[];t[0]=!!e.next(),r[0]=!!e.next();let n=e.decodeExponentialGolombNumber(),i=!!e.next(),o=!!e.next(),a=!!e.next(),s=!!e.next();t[1]=!!e.next(),r[1]=!!e.next();let l=!!e.next(),u=e.decodeExponentialGolombNumber(),c=!!e.next(),h=!!e.next(),f=!!e.next();return{iv_di_mc_enabled_flag:t,iv_mv_scal_enabled_flag:r,log2_ivmc_sub_pb_size_minus3:n,iv_res_pred_enabled_flag:i,depth_ref_enabled_flag:o,vsp_mc_enabled_flag:a,dbbp_enabled_flag:s,tex_mc_enabled_flag:l,log2_texmc_sub_pb_size_minus3:u,intra_contour_enabled_flag:c,intra_dc_only_wedge_enabled_flag:h,cqt_cu_part_pred_enabled_flag:f,inter_dc_only_enabled_flag:!!e.next(),skip_intra_enabled_flag:!!e.next()}}function I(e){let{videoParameterSet:t,sequenceParameterSet:r,pictureParameterSet:n}=k(e),{profileTierLevel:{generalProfileTier:{profile_space:i,tier_flag:o,profile_idc:a,profileCompatibilitySet:s,constraintSet:l},general_level_idc:u}}=y(t.rbsp),{chroma_format_idc:c,pic_width_in_luma_samples:h,pic_height_in_luma_samples:f,conf_win_left_offset:d=0,conf_win_right_offset:g=0,conf_win_top_offset:b=0,conf_win_bottom_offset:_=0}=v(r.rbsp),w=p(c),x=m(c),S=h-w*(d+g),E=f-x*(b+_);return{videoParameterSet:t,sequenceParameterSet:r,pictureParameterSet:n,generalProfileSpace:i,generalProfileIndex:a,generalProfileCompatibilitySet:s,generalTierFlag:o,generalLevelIndex:u,generalConstraintSet:l,encodedWidth:h,encodedHeight:f,cropLeft:d,cropRight:g,cropTop:b,cropBottom:_,croppedWidth:S,croppedHeight:E}}class P extends s{#g;#y;constructor(e,t){super(e),this.#g=e,this.#y=t}configure(e){let{generalProfileSpace:t,generalProfileIndex:r,generalProfileCompatibilitySet:n,generalTierFlag:i,generalLevelIndex:o,generalConstraintSet:a,croppedWidth:s,croppedHeight:u}=I(e);this.#y(s,u);let c=["hev1",["","A","B","C"][t]+r.toString(),l(f(n,0)),(i?"H":"L")+o.toString(),...Array.from(a,l)].join(".");this.#g.configure({codec:c,codedWidth:s,codedHeight:u,optimizeForLatency:!0})}}class R{#v;#b;#_=0;#w=7;get byteAligned(){return 7===this.#w}get ended(){return this.#_>=this.#v.length}constructor(e){this.#v=e,this.#b=e[0]}f1(){let e=this.#b>>this.#w;return this.#w-=1,this.#w<0&&(this.#_+=1,this.#w=7,this.#b=this.#v[this.#_]),1&e}f(e){let t=0;for(;e>0;e-=1)t<<=1,t|=this.f1();return t}skip(e){if(e<=this.#w+1){this.#_+=1,this.#w=7,this.#b=this.#v[this.#_];return}e-=this.#w+1,this.#_+=1;let t=e/8|0;t>0&&(this.#_+=t,e-=8*t),this.#w=7-e,this.#b=this.#v[this.#_]}readBytes(e){if(!this.byteAligned)throw Error("Bytes must be byte-aligned");let t=this.#v.subarray(this.#_,this.#_+e);return this.#_+=e,this.#b=this.#v[this.#_],t}getPosition(){return[this.#_,this.#w]}setPosition([e,t]){this.#_=e,this.#w=t,this.#b=this.#v[e]}}let M={SequenceHeader:1,TemporalDelimiter:2,FrameHeader:3,TileGroup:4,Metadata:5,Frame:6,RedundantFrameHeader:7,TileList:8,Padding:15},$={Bt709:1,Unspecified:2,Bt470M:4,Bt470BG:5,Bt601:6,Smpte240:7,GenericFilm:8,Bt2020:9,Xyz:10,Smpte431:11,Smpte432:12,Ebu3213:22},N={Bt709:1,Unspecified:2,Bt470M:4,Bt470BG:5,Bt601:6,Smpte240:7,Linear:8,Log100:9,Log100Sqrt10:10,Iec61966:11,Bt1361:12,Srgb:13,Bt2020Ten:14,Bt2020Twelve:15,Smpte2084:16,Smpte428:17,Hlg:18},j={Identity:0,Bt709:1,Unspecified:2,Fcc:4,Bt470BG:5,Bt601:6,Smpte240:7,YCgCo:8,Bt2020Ncl:9,Bt2020Cl:10,Smpte2085:11,ChromatNcl:12,ChromatCl:13,ICtCp:14};class B extends R{static ObuType=M;static ColorPrimaries=$;static TransferCharacteristics=N;static MatrixCoefficients=j;#x=0;uvlc(){let e=0;for(;!this.f1();)e+=1;return e>=32?0x100000000-1:this.f(e)+(1<<e>>>0)-1}leb128(){if(!this.byteAligned)throw Error("LEB128 must be byte-aligned");let e=0n;this.#x=0;for(let t=0n;t<8n;t+=1n){let r=this.f(8);if(e|=BigInt(127&r)<<7n*t,this.#x+=1,(128&r)==0)break}return e}*annexBBitstream(){for(;!this.ended;){let e=this.leb128();yield*this.temporalUnit(e)}}*temporalUnit(e){for(;e>0;){let t=this.leb128();e-=BigInt(this.#x),yield*this.frameUnit(t),e-=t}}*frameUnit(e){for(;e>0;){let t=this.leb128();e-=BigInt(this.#x);let r=this.openBitstreamUnit(t);r&&(yield r),e-=t}}#S=0;openBitstreamUnit(e){let t,r,n=this.obuHeader();if(n.obu_has_size_field)t=this.leb128();else if(void 0!==e)t=e-1n-(n.obu_extension_flag?1n:0n);else throw Error("obu_has_size_field must be true");let i=this.getPosition();if(n.obu_type!==B.ObuType.SequenceHeader&&n.obu_type!==B.ObuType.TemporalDelimiter&&0!==this.#S&&n.obu_extension_header){let e=!!(this.#S&1<<n.obu_extension_header.temporal_id),r=!!(this.#S&1<<n.obu_extension_header.spatial_id+8);if(!e||!r)return void this.skip(Number(t))}n.obu_type===B.ObuType.SequenceHeader&&(r=this.sequenceHeaderObu());let o=this.getPosition(),a=(o[0]-i[0])*8+(i[1]-o[1]);return t>0&&this.skip(8*Number(t)-a),{obu_header:n,obu_size:t,sequence_header_obu:r}}obuHeader(){let e;if(this.f1())throw Error("Invalid data");let t=this.f(4),r=!!this.f1(),n=!!this.f1();return this.f1(),r&&(e=this.obuExtensionHeader()),{obu_type:t,obu_extension_flag:r,obu_has_size_field:n,obu_extension_header:e}}obuExtensionHeader(){let e=this.f(3),t=this.f(2);return this.skip(3),{temporal_id:e,spatial_id:t}}static SelectScreenContentTools=2;static SelectIntegerMv=2;sequenceHeaderObu(){let e,t,r,n,i,o,a,s=this.f(3),l=!!this.f1(),u=!!this.f1(),c=!1,h=!1,f=!1,d=0,p=[],m=[],g=[],y=[],v=[];if(u)p[0]=0,m[0]=this.f(5),g[0]=0,y[0]=!1,v[0]=!1;else{(c=!!this.f1())&&(e=this.timingInfo(),(h=!!this.f1())&&(t=this.decoderModelInfo(),r=[])),(f=!!this.f1())&&(n=[]),d=this.f(5);for(let e=0;e<=d;e+=1)p[e]=this.f(12),m[e]=this.f(5),m[e]>7?g[e]=this.f1():g[e]=0,h?(y[e]=!!this.f1(),y[e]&&(r[e]=this.operatingParametersInfo(t))):y[e]=!1,f&&(v[e]=!!this.f1(),v[e]&&(n[e]=this.f(4)))}let b=this.chooseOperatingPoint();this.#S=p[b];let _=this.f(4),w=this.f(4),x=this.f(_+1),S=this.f(w+1),E=!1;!u&&(E=!!this.f1())&&(i=this.f(4),o=this.f(3));let C=!!this.f1(),A=!!this.f1(),k=!!this.f1(),O=!1,T=!1,I=!1,P=!1,R=!1,M=!1,$=!1,N=!1,j=B.SelectScreenContentTools,L=!1,F=B.SelectIntegerMv;!u&&(O=!!this.f1(),T=!!this.f1(),I=!!this.f1(),P=!!this.f1(),(R=!!this.f1())&&(M=!!this.f1(),$=!!this.f1()),(N=!!this.f1())||(j=this.f1()),j>0&&((L=!!this.f1())||(F=this.f1())),R&&(a=this.f(3)));let D=!!this.f1(),z=!!this.f1(),U=!!this.f1(),Z=this.colorConfig(s);return{seq_profile:s,still_picture:l,reduced_still_picture_header:u,timing_info_present_flag:c,timing_info:e,decoder_model_info_present_flag:h,decoder_model_info:t,initial_display_delay_present_flag:f,initial_display_delay_minus_1:n,operating_points_cnt_minus_1:d,operating_point_idc:p,seq_level_idx:m,seq_tier:g,decoder_model_present_for_this_op:y,operating_parameters_info:r,initial_display_delay_present_for_this_op:v,frame_width_bits_minus_1:_,frame_height_bits_minus_1:w,max_frame_width_minus_1:x,max_frame_height_minus_1:S,frame_id_numbers_present_flag:E,delta_frame_id_length_minus_2:i,additional_frame_id_length_minus_1:o,use_128x128_superblock:C,enable_filter_intra:A,enable_intra_edge_filter:k,enable_interintra_compound:O,enable_masked_compound:T,enable_warped_motion:I,enable_dual_filter:P,enable_order_hint:R,enable_jnt_comp:M,enable_ref_frame_mvs:$,seq_choose_screen_content_tools:N,seq_force_screen_content_tools:j,seq_choose_integer_mv:L,seq_force_integer_mv:F,order_hint_bits_minus_1:a,enable_superres:D,enable_cdef:z,enable_restoration:U,color_config:Z,film_grain_params_present:!!this.f1()}}searchSequenceHeaderObu(){for(;!this.ended;){let e=this.openBitstreamUnit();if(e&&e.sequence_header_obu)return e.sequence_header_obu}}timingInfo(){let e,t=this.f(32),r=this.f(32),n=!!this.f1();return n&&(e=this.uvlc()),{num_units_in_display_tick:t,time_scale:r,equal_picture_interval:n,num_ticks_per_picture_minus_1:e}}decoderModelInfo(){let e=this.f(5),t=this.f(32);return{buffer_delay_length_minus_1:e,num_units_in_decoding_tick:t,buffer_removal_time_length_minus_1:this.f(5),frame_presentation_time_length_minus_1:this.f(5)}}operatingParametersInfo(e){let t=e.buffer_delay_length_minus_1+1,r=this.f(t);return{decoder_buffer_delay:r,encoder_buffer_delay:this.f(t),low_delay_mode_flag:!!this.f1()}}chooseOperatingPoint(){return 0}colorConfig(e){let t,r,n=!!this.f1(),i=!1,o=8;2===e&&n?o=(i=!!this.f1())?12:10:e<=2&&(o=n?10:8);let a=!1;1===e&&(a=!!this.f1());let s=!!this.f1(),l=B.ColorPrimaries.Unspecified,u=B.TransferCharacteristics.Unspecified,c=B.MatrixCoefficients.Unspecified;s&&(l=this.f(8),u=this.f(8),c=this.f(8));let h=!1,f=0,d=!1;if(a)h=!!this.f1(),t=!0,r=!0;else{if(l===B.ColorPrimaries.Bt709&&u===B.TransferCharacteristics.Srgb&&c===B.MatrixCoefficients.Identity)h=!0,t=!1,r=!1;else{switch(h=!!this.f1(),e){case 0:t=!0,r=!0;break;case 1:t=!1,r=!1;break;default:12==o?r=!!(t=!!this.f1())&&!!this.f1():(t=!0,r=!1)}t&&r&&(f=this.f(2))}d=!!this.f1()}return{high_bitdepth:n,twelve_bit:i,BitDepth:o,mono_chrome:a,color_description_present_flag:s,color_primaries:l,transfer_characteristics:u,matrix_coefficients:c,color_range:h,subsampling_x:t,subsampling_y:r,chroma_sample_position:f,separate_uv_delta_q:d}}}class L{#g;#y;constructor(e,t){this.#g=e,this.#y=t}#p(e){let t,r,n,i,o=new B(e).searchSequenceHeaderObu();if(!o)return;let{seq_profile:a,seq_level_idx:[s=0],max_frame_width_minus_1:l,max_frame_height_minus_1:u,color_config:{BitDepth:h,mono_chrome:f,subsampling_x:d,subsampling_y:p,chroma_sample_position:m,color_description_present_flag:g}}=o;g?{color_primaries:t,transfer_characteristics:r,matrix_coefficients:n,color_range:i}=o.color_config:(t=B.ColorPrimaries.Bt709,r=B.TransferCharacteristics.Bt709,n=B.MatrixCoefficients.Bt709,i=!1);let y=l+1,v=u+1;this.#y(y,v);let b=["av01",a.toString(16),c(s)+(o.seq_tier[0]?"H":"M"),c(h),f?"1":"0",(d?"1":"0")+(p?"1":"0")+m.toString(),c(t),c(r),c(n),i?"1":"0"].join(".");this.#g.configure({codec:b,optimizeForLatency:!0})}decode(e){"configuration"!==e.type&&(this.#p(e.data),this.#g.decode(new EncodedVideoChunk({type:!1===e.keyframe?"delta":"key",timestamp:0,data:e.data})))}}class F{#E;#C=new ReadableStream({start:e=>{this.#E=e},pull:e=>{e.enqueue(this.#d())}},{highWaterMark:0});#A=this.#C.getReader();#d;#k=0;#O;constructor(e,t){this.#d=e,this.#O=t}async borrow(){return(await this.#A.read()).value}return(e){this.#k<this.#O&&(this.#E.enqueue(e),this.#k+=1)}}class D{#T;#I;constructor(){"undefined"!=typeof OffscreenCanvas?this.#T=new OffscreenCanvas(1,1):(this.#T=document.createElement("canvas"),this.#T.width=1,this.#T.height=1),this.#I=this.#T.getContext("bitmaprenderer",{alpha:!1})}async capture(e){this.#T.width=e.displayWidth,this.#T.height=e.displayHeight;let t=await createImageBitmap(e);return(this.#I.transferFromImageBitmap(t),this.#T instanceof OffscreenCanvas)?await this.#T.convertToBlob({type:"image/png"}):new Promise((e,t)=>{this.#T.toBlob(r=>{r?e(r):t(Error("Failed to convert canvas to blob"))},"image/png")})}}let z=new F(()=>new D,4);class U{static get isSupported(){return void 0!==globalThis.VideoDecoder}static capabilities={h264:{},h265:{},av1:{}};#P;get codec(){return this.#P}#R;#h;get writable(){return this.#h}#M;#E;#s;get renderer(){return this.#s}#$=0;#N=0;get framesRendered(){return this.#N}#j=0;get framesSkipped(){return this.#j}#l=new n.v;get sizeChanged(){return this.#l.event}#g;#B=!1;#L;#F;#D=0;constructor({codec:e,renderer:t}){switch(this.#P=e,this.#s=t,this.#g=new VideoDecoder({output:e=>{if(this.#F?.close(),this.#F=e.clone(),this.#B){this.#L&&(this.#L.close(),this.#j+=1),this.#L=e;return}this.#z(e)},error:e=>{this.#U(e)}}),this.#P){case i.W.H264:this.#R=new h(this.#g,this.#y);break;case i.W.H265:this.#R=new P(this.#g,this.#y);break;case i.W.AV1:this.#R=new L(this.#g,this.#y);break;default:throw Error(`Unsupported codec: ${this.#P}`)}this.#h=new o.Vj({start:e=>{this.#M?e.error(this.#M):this.#E=e},write:e=>{this.#R.decode(e)}}),this.#Z()}#U(e){if(this.#E)try{this.#E.error(e)}catch{}else this.#M=e}async #z(e){try{if(this.#B=!0,this.#y(e.displayWidth,e.displayHeight),await this.#s.draw(e),this.#$+=1,e.close(),this.#L){let e=this.#L;this.#L=void 0,await this.#z(e)}this.#B=!1}catch(e){this.#U(e)}}#y=(e,t)=>{this.#s.setSize(e,t),this.#l.fire({width:e,height:t})};#Z=()=>{this.#$>0&&(this.#N+=1,this.#j+=this.#$-1,this.#$=0),this.#D=requestAnimationFrame(this.#Z)};async snapshot(){let e=this.#F;if(!e)return;let t=await z.borrow(),r=await t.capture(e);return z.return(t),r}dispose(){cancelAnimationFrame(this.#D),"closed"!==this.#g.state&&this.#g.close(),this.#L?.close(),this.#F?.close()}}},72688:function(e,t,r){"use strict";r.d(t,{I:()=>i});var n=r(45567);class i extends n.F{#I;constructor(e){super(e),this.#I=this.canvas.getContext("bitmaprenderer",{alpha:!1})}async draw(e){let t=await createImageBitmap(e);this.#I.transferFromImageBitmap(t)}}},45567:function(e,t,r){"use strict";r.d(t,{F:()=>i});var n=r(67979);class i{#T;get canvas(){return this.#T}constructor(e){e?this.#T=e:this.#T=(0,n.v)()}setSize(e,t){(this.#T.width!==e||this.#T.height!==t)&&(this.#T.width=e,this.#T.height=t)}}},32686:function(e,t,r){"use strict";r.d(t,{P:()=>s});var n=r(67979),i=r(45567);let o=Promise.resolve();function a(e,t){let r={powerPreference:"low-power",alpha:!1,failIfMajorPerformanceCaveat:!0,preserveDrawingBuffer:!!t};return e.getContext("webgl2",r)||e.getContext("webgl",r)}class s extends i.F{static vertexShaderSource=`
284
284
  attribute vec2 xy;
@@ -646,5 +646,5 @@ ${e}`:e}},f=Object.create(null),d=class e{constructor(t){let r=-1!==(t={...e.def
646
646
  `:t}static _getFromCache(t,r,n,i){let o=n[t];return"number"!=typeof o&&(o=e._measureText(t,r,i)+r,n[t]=o),o}static _collapseSpaces(e){return"normal"===e||"pre-line"===e}static _collapseNewlines(e){return"normal"===e}static _trimRight(t){if("string"!=typeof t)return"";for(let r=t.length-1;r>=0;r--){let n=t[r];if(!e.isBreakingSpace(n))break;t=t.slice(0,-1)}return t}static _isNewline(t){return"string"==typeof t&&e._newlines.includes(t.charCodeAt(0))}static isBreakingSpace(t,r){return"string"==typeof t&&e._breakingSpaces.includes(t.charCodeAt(0))}static _tokenize(t){let r=[],n="";if("string"!=typeof t)return r;for(let i=0;i<t.length;i++){let o=t[i],a=t[i+1];if(e.isBreakingSpace(o,a)||e._isNewline(o)){""!==n&&(r.push(n),n=""),r.push(o);continue}n+=o}return""!==n&&r.push(n),r}static canBreakWords(e,t){return t}static canBreakChars(e,t,r,n,i){return!0}static wordWrapSplit(t){return e.graphemeSegmenter(t)}static measureFont(t){if(e._fonts[t])return e._fonts[t];let r=e._context;r.font=t;let n=r.measureText(e.METRICS_STRING+e.BASELINE_SYMBOL),i={ascent:n.actualBoundingBoxAscent,descent:n.actualBoundingBoxDescent,fontSize:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent};return e._fonts[t]=i,i}static clearMetrics(t=""){t?delete e._fonts[t]:e._fonts={}}static get _canvas(){if(!e.__canvas){let t;try{let r=new OffscreenCanvas(0,0),i=r.getContext("2d",o);if(i?.measureText)return e.__canvas=r,r;t=n.z.get().createCanvas()}catch(e){t=n.z.get().createCanvas()}t.width=t.height=10,e.__canvas=t}return e.__canvas}static get _context(){return e.__context||(e.__context=e._canvas.getContext("2d",o)),e.__context}};a.METRICS_STRING="|\xc9q\xc5",a.BASELINE_SYMBOL="M",a.BASELINE_MULTIPLIER=1.4,a.HEIGHT_MULTIPLIER=2,a.graphemeSegmenter=(()=>{if("function"==typeof Intl?.Segmenter){let e=new Intl.Segmenter;return t=>[...e.segment(t)].map(e=>e.segment)}return e=>[...e]})(),a.experimentalLetterSpacing=!1,a._fonts={},a._newlines=[10,13],a._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],a._measurementCache={};let s=a},92007:function(e,t,r){"use strict";r.d(t,{M:()=>i});let n=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function i(e){let t="number"==typeof e.fontSize?`${e.fontSize}px`:e.fontSize,r=e.fontFamily;Array.isArray(e.fontFamily)||(r=e.fontFamily.split(","));for(let e=r.length-1;e>=0;e--){let t=r[e].trim();/([\"\'])[^\'\"]+\1/.test(t)||n.includes(t)||(t=`"${t}"`),r[e]=t}return`${e.fontStyle} ${e.fontVariant} ${e.fontWeight} ${t} ${r.join(",")}`}},71722:function(e,t,r){"use strict";r.d(t,{L:()=>i});let n=["_fontFamily","_fontStyle","_fontSize","_fontVariant","_fontWeight","_breakWords","_align","_leading","_letterSpacing","_lineHeight","_textBaseline","_whiteSpace","_wordWrap","_wordWrapWidth","_padding","_cssOverrides","_trim"];function i(e){let t=[],r=0;for(let i=0;i<n.length;i++){let o=n[i];t[r++]=e[o]}return r=o(e._fill,t,r),r=a(e._stroke,t,r),t.join("-")}function o(e,t,r){return e&&(t[r++]=e.color,t[r++]=e.alpha,t[r++]=e.fill?.uid),r}function a(e,t,r){return e&&(r=o(e,t,r),t[r++]=e.width,t[r++]=e.alignment,t[r++]=e.cap,t[r++]=e.join,t[r++]=e.miterLimit),r}},65003:function(e,t,r){"use strict";var n=r(91957),i=r(79886),o=r(87894),a=r(86160),s=r(41277),l=r(15792),u=r(45266);let c=class e{constructor(e,t){this.linkedSheets=[],this._texture=e instanceof s.x?e:null,this.textureSource=e.source,this.textures={},this.animations={},this.data=t;let r=parseFloat(t.meta.scale);r?(this.resolution=r,e.source.resolution=this.resolution):this.resolution=e.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=e.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(t){let r=t,n=e.BATCH_SIZE;for(;r-t<n&&r<this._frameKeys.length;){let e=this._frameKeys[r],t=this._frames[e],n=t.frame;if(n){let r=null,i=null,o=!1!==t.trimmed&&t.sourceSize?t.sourceSize:t.frame,a=new u.A(0,0,Math.floor(o.w)/this.resolution,Math.floor(o.h)/this.resolution);r=t.rotated?new u.A(Math.floor(n.x)/this.resolution,Math.floor(n.y)/this.resolution,Math.floor(n.h)/this.resolution,Math.floor(n.w)/this.resolution):new u.A(Math.floor(n.x)/this.resolution,Math.floor(n.y)/this.resolution,Math.floor(n.w)/this.resolution,Math.floor(n.h)/this.resolution),!1!==t.trimmed&&t.spriteSourceSize&&(i=new u.A(Math.floor(t.spriteSourceSize.x)/this.resolution,Math.floor(t.spriteSourceSize.y)/this.resolution,Math.floor(n.w)/this.resolution,Math.floor(n.h)/this.resolution)),this.textures[e]=new s.x({source:this.textureSource,frame:r,orig:a,trim:i,rotate:2*!!t.rotated,defaultAnchor:t.anchor,defaultBorders:t.borders,label:e.toString()})}r++}}_processAnimations(){let e=this.data.animations||{};for(let t in e){this.animations[t]=[];for(let r=0;r<e[t].length;r++){let n=e[t][r];this.animations[t].push(this.textures[n])}}}_parseComplete(){let e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*e.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*e.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(let e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};c.BATCH_SIZE=1e3;let h=c,f=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function d(e,t,r){let n={};if(e.forEach(e=>{n[e]=t}),Object.keys(t.textures).forEach(e=>{n[e]=t.textures[e]}),!r){let r=l.E.dirname(e[0]);t.linkedSheets.forEach((e,i)=>{Object.assign(n,d([`${r}/${t.data.meta.related_multi_packs[i]}`],e,!0))})}return n}let p={extension:n.nw.Asset,cache:{test:e=>e instanceof h,getCacheableAssets:(e,t)=>d(e,t,!1)},resolver:{test:e=>{let t=e.split("?")[0].split("."),r=t.pop(),n=t.pop();return"json"===r&&f.includes(n)},parse:e=>{let t=e.split(".");return{resolution:parseFloat(o.H.RETINA_PREFIX.exec(e)?.[1]??"1"),format:t[t.length-2],src:e}}},loader:{name:"spritesheetLoader",extension:{type:n.nw.LoadParser,priority:i.Q.Normal},testParse:async(e,t)=>".json"===l.E.extname(t.src).toLowerCase()&&!!e.frames,async parse(e,t,r){let n,{texture:i,imageFilename:o}=t?.data??{},u=l.E.dirname(t.src);if(u&&u.lastIndexOf("/")!==u.length-1&&(u+="/"),i instanceof s.x)n=i;else{let i=(0,a.u)(u+(o??e.meta.image),t.src);n=(await r.load([i]))[i]}let c=new h(n.source,e);await c.parse();let f=e?.meta?.related_multi_packs;if(Array.isArray(f)){let e=[];for(let n of f){if("string"!=typeof n)continue;let i=u+n;t.data?.ignoreMultiPack||(i=(0,a.u)(i,t.src),e.push(r.load({src:i,data:{ignoreMultiPack:!0}})))}let n=await Promise.all(e);c.linkedSheets=n,n.forEach(e=>{e.linkedSheets=[c].concat(c.linkedSheets.filter(t=>t!==e))})}return c},async unload(e,t,r){await r.unload(e.textureSource._sourceOrigin),e.destroy(!1)}}};n.Rw.add(p)},96743:function(e,t,r){"use strict";r.d(t,{v:()=>a});var n=r(95909);class i{constructor(e,t=null,r=0,n=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=r,this._once=n}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));let t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);let t=this.next;return this.next=e?null:t,this.previous=null,t}}let o=class e{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new i(null,null,1/0),this.deltaMS=1/e.targetFPMS,this.elapsedMS=1/e.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,r=n.u.NORMAL){return this._addListener(new i(e,t,r))}addOnce(e,t,r=n.u.NORMAL){return this._addListener(new i(e,t,r,!0))}_addListener(e){let t=this._head.next,r=this._head;if(t){for(;t;){if(e.priority>t.priority){e.connect(r);break}r=t,t=t.next}e.previous||e.connect(r)}else e.connect(r);return this._startIfPossible(),this}remove(e,t){let r=this._head.next;for(;r;)r=r.match(e,t)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let r;if(t>this.lastTime){if((r=this.elapsedMS=t-this.lastTime)>this._maxElapsedMS&&(r=this._maxElapsedMS),r*=this.speed,this._minElapsedMS){let e=t-this._lastFrame|0;if(e<this._minElapsedMS)return;this._lastFrame=t-e%this._minElapsedMS}this.deltaMS=r,this.deltaTime=this.deltaMS*e.targetFPMS;let n=this._head,i=n.next;for(;i;)i=i.emit(this);n.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){let r=Math.min(Math.max(0,Math.min(this.maxFPS,t))/1e3,e.targetFPMS);this._maxElapsedMS=1/r}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){if(0===e)this._minElapsedMS=0;else{let t=Math.max(this.minFPS,e);this._minElapsedMS=1/(t/1e3)}}static get shared(){if(!e._shared){let t=e._shared=new e;t.autoStart=!0,t._protected=!0}return e._shared}static get system(){if(!e._system){let t=e._system=new e;t.autoStart=!0,t._protected=!0}return e._system}};o.targetFPMS=.06;let a=o},95909:function(e,t,r){"use strict";let n;r.d(t,{u:()=>i});var i=((n=i||{})[n.INTERACTION=50]="INTERACTION",n[n.HIGH=25]="HIGH",n[n.NORMAL=0]="NORMAL",n[n.LOW=-25]="LOW",n[n.UTILITY=-50]="UTILITY",n)},83264:function(e,t,r){"use strict";var n=r(15011),i=r(37861),o=r(87434),a=r(1839),s=r(63949),l=r(17638),u=r(95753),c=r(73109),h=r(62815),f=r(47191);function d(){return p}function p(e,t,r){let n=e.gl,i=e.shader,o=i._getProgramData(t.glProgram);for(let a in t.groups){let s=t.groups[a];for(let l in s.resources){let d=s.resources[l];if(d instanceof c.o)d.ubo?i.bindUniformBlock(d,t._uniformBindMap[a][l],r.blockIndex++):i.updateUniformGroup(d);else if(d instanceof u.q)i.bindUniformBlock(d,t._uniformBindMap[a][l],r.blockIndex++);else if(d instanceof h.p){e.texture.bind(d,r.textureCount);let i=t._uniformBindMap[a][l],s=o.uniformData[i];s&&(s.value!==r.textureCount&&n.uniform1i(s.location,r.textureCount),r.textureCount++)}else f.L}}}var m=r(5468),g=r(98790),y=r(4281);let v=[(e,t,r,n,i)=>{let o=n[e].toArray(!0);t[r]=o[0],t[r+1]=o[1],t[r+2]=o[2],t[r+4]=o[3],t[r+5]=o[4],t[r+6]=o[5],t[r+8]=o[6],t[r+9]=o[7],t[r+10]=o[8]},(e,t,r,n,i)=>{i=n[e],t[r]=i.x,t[r+1]=i.y,t[r+2]=i.width,t[r+3]=i.height},(e,t,r,n,i)=>{i=n[e],t[r]=i.x,t[r+1]=i.y},(e,t,r,n,i)=>{i=n[e],t[r]=i.red,t[r+1]=i.green,t[r+2]=i.blue,t[r+3]=i.alpha},(e,t,r,n,i)=>{i=n[e],t[r]=i.red,t[r+1]=i.green,t[r+2]=i.blue}],b={f32:(e,t,r,n,i)=>{t[r]=i},i32:(e,t,r,n,i)=>{t[r]=i},"vec2<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1]},"vec3<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2]},"vec4<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3]},"mat2x2<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3]},"mat3x3<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+4]=i[3],t[r+5]=i[4],t[r+6]=i[5],t[r+8]=i[6],t[r+9]=i[7],t[r+10]=i[8]},"mat4x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<16;e++)t[r+e]=i[e]},"mat3x2<f32>":(e,t,r,n,i)=>{for(let e=0;e<6;e++)t[r+(e/3|0)*4+e%3]=i[e]},"mat4x2<f32>":(e,t,r,n,i)=>{for(let e=0;e<8;e++)t[r+(e/4|0)*4+e%4]=i[e]},"mat2x3<f32>":(e,t,r,n,i)=>{for(let e=0;e<6;e++)t[r+(e/2|0)*4+e%2]=i[e]},"mat4x3<f32>":(e,t,r,n,i)=>{for(let e=0;e<12;e++)t[r+(e/4|0)*4+e%4]=i[e]},"mat2x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<8;e++)t[r+(e/2|0)*4+e%2]=i[e]},"mat3x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<12;e++)t[r+(e/3|0)*4+e%3]=i[e]}},_={f32:(e,t,r,n,i)=>{t[r]=i},i32:(e,t,r,n,i)=>{t[r]=i},"vec2<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1]},"vec3<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2]},"vec4<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3]},"mat2x2<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+4]=i[2],t[r+5]=i[3]},"mat3x3<f32>":(e,t,r,n,i)=>{t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+4]=i[3],t[r+5]=i[4],t[r+6]=i[5],t[r+8]=i[6],t[r+9]=i[7],t[r+10]=i[8]},"mat4x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<16;e++)t[r+e]=i[e]},"mat3x2<f32>":(e,t,r,n,i)=>{for(let e=0;e<6;e++)t[r+(e/3|0)*4+e%3]=i[e]},"mat4x2<f32>":(e,t,r,n,i)=>{for(let e=0;e<8;e++)t[r+(e/4|0)*4+e%4]=i[e]},"mat2x3<f32>":(e,t,r,n,i)=>{for(let e=0;e<6;e++)t[r+(e/2|0)*4+e%2]=i[e]},"mat4x3<f32>":(e,t,r,n,i)=>{for(let e=0;e<12;e++)t[r+(e/4|0)*4+e%4]=i[e]},"mat2x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<8;e++)t[r+(e/2|0)*4+e%2]=i[e]},"mat3x4<f32>":(e,t,r,n,i)=>{for(let e=0;e<12;e++)t[r+(e/3|0)*4+e%3]=i[e]}};function w(e){return S(e,_,e=>{let t=Math.max(m.P[e.data.type]/16,1),r=e.data.value.length/e.data.size,n=(4-r%4)%4;return(i,o,a,s,l)=>{let u=0;for(let i=0;i<e.data.size*t;i++){for(let e=0;e<r;e++)o[a++]=l[u++];a+=n}}})}function x(e){return S(e,b,e=>{let{size:t,align:r}=g.j[e.data.type],n=(t-r)/4;return(r,i,o,a,s)=>{let l=0;for(let r=0;r<e.data.size*(t/4);r++){for(let e=0;e<t/4;e++)i[o++]=s[l++];o+=n}}})}function S(e,t,r){let n={};for(let i in e){let o=e[i],a=o.data,s=!1;n[a.name]={offset:o.offset/4,func:null};for(let e=0;e<y.s.length;e++){let t=y.s[e];if(a.type===t.type&&t.test(a)){n[a.name].func=v[e],s=!0;break}}s||(1===a.size?n[a.name].func=t[a.type]:n[a.name].func=r(o))}return(e,t,r)=>{for(let i in n)n[i].func(i,t,r+n[i].offset,e,e[i])}}let E={f32(e,t,r,n,i,o,a){r!==n&&(t.value=n,a.uniform1f(i[e].location,n))},"vec2<f32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1])&&(r[0]=n[0],r[1]=n[1],a.uniform2f(i[e].location,n[0],n[1]))},"vec3<f32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],a.uniform3f(i[e].location,n[0],n[1],n[2]))},"vec4<f32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2]||r[3]!==n[3])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],a.uniform4f(i[e].location,n[0],n[1],n[2],n[3]))},i32(e,t,r,n,i,o,a){r!==n&&(t.value=n,a.uniform1i(i[e].location,n))},"vec2<i32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1])&&(r[0]=n[0],r[1]=n[1],a.uniform2i(i[e].location,n[0],n[1]))},"vec3<i32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],a.uniform3i(i[e].location,n[0],n[1],n[2]))},"vec4<i32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2]||r[3]!==n[3])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],a.uniform4i(i[e].location,n[0],n[1],n[2],n[3]))},u32(e,t,r,n,i,o,a){r!==n&&(t.value=n,a.uniform1ui(i[e].location,n))},"vec2<u32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1])&&(r[0]=n[0],r[1]=n[1],a.uniform2ui(i[e].location,n[0],n[1]))},"vec3<u32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],a.uniform3ui(i[e].location,n[0],n[1],n[2]))},"vec4<u32>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2]||r[3]!==n[3])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],a.uniform4ui(i[e].location,n[0],n[1],n[2],n[3]))},bool(e,t,r,n,i,o,a){r!==n&&(t.value=n,a.uniform1i(i[e].location,n))},"vec2<bool>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1])&&(r[0]=n[0],r[1]=n[1],a.uniform2i(i[e].location,n[0],n[1]))},"vec3<bool>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],a.uniform3i(i[e].location,n[0],n[1],n[2]))},"vec4<bool>"(e,t,r,n,i,o,a){(r[0]!==n[0]||r[1]!==n[1]||r[2]!==n[2]||r[3]!==n[3])&&(r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],a.uniform4i(i[e].location,n[0],n[1],n[2],n[3]))},"mat2x2<f32>"(e,t,r,n,i,o,a){a.uniformMatrix2fv(i[e].location,!1,n)},"mat3x3<f32>"(e,t,r,n,i,o,a){a.uniformMatrix3fv(i[e].location,!1,n)},"mat4x4<f32>"(e,t,r,n,i,o,a){a.uniformMatrix4fv(i[e].location,!1,n)}},C={f32(e,t,r,n,i,o,a){a.uniform1fv(i[e].location,n)},"vec2<f32>"(e,t,r,n,i,o,a){a.uniform2fv(i[e].location,n)},"vec3<f32>"(e,t,r,n,i,o,a){a.uniform3fv(i[e].location,n)},"vec4<f32>"(e,t,r,n,i,o,a){a.uniform4fv(i[e].location,n)},"mat2x2<f32>"(e,t,r,n,i,o,a){a.uniformMatrix2fv(i[e].location,!1,n)},"mat3x3<f32>"(e,t,r,n,i,o,a){a.uniformMatrix3fv(i[e].location,!1,n)},"mat4x4<f32>"(e,t,r,n,i,o,a){a.uniformMatrix4fv(i[e].location,!1,n)},i32(e,t,r,n,i,o,a){a.uniform1iv(i[e].location,n)},"vec2<i32>"(e,t,r,n,i,o,a){a.uniform2iv(i[e].location,n)},"vec3<i32>"(e,t,r,n,i,o,a){a.uniform3iv(i[e].location,n)},"vec4<i32>"(e,t,r,n,i,o,a){a.uniform4iv(i[e].location,n)},u32(e,t,r,n,i,o,a){a.uniform1iv(i[e].location,n)},"vec2<u32>"(e,t,r,n,i,o,a){a.uniform2iv(i[e].location,n)},"vec3<u32>"(e,t,r,n,i,o,a){a.uniform3iv(i[e].location,n)},"vec4<u32>"(e,t,r,n,i,o,a){a.uniform4iv(i[e].location,n)},bool(e,t,r,n,i,o,a){a.uniform1iv(i[e].location,n)},"vec2<bool>"(e,t,r,n,i,o,a){a.uniform2iv(i[e].location,n)},"vec3<bool>"(e,t,r,n,i,o,a){a.uniform3iv(i[e].location,n)},"vec4<bool>"(e,t,r,n,i,o,a){a.uniform4iv(i[e].location,n)}},A=[(e,t,r,n,i,o,a)=>{a.uniformMatrix3fv(i[e].location,!1,o[e].toArray(!0))},(e,t,r,n,i,o,a)=>{r=i[e].value,n=o[e],(r[0]!==n.x||r[1]!==n.y||r[2]!==n.width||r[3]!==n.height)&&(r[0]=n.x,r[1]=n.y,r[2]=n.width,r[3]=n.height,a.uniform4f(i[e].location,n.x,n.y,n.width,n.height))},(e,t,r,n,i,o,a)=>{r=i[e].value,n=o[e],(r[0]!==n.x||r[1]!==n.y)&&(r[0]=n.x,r[1]=n.y,a.uniform2f(i[e].location,n.x,n.y))},(e,t,r,n,i,o,a)=>{r=i[e].value,n=o[e],(r[0]!==n.red||r[1]!==n.green||r[2]!==n.blue||r[3]!==n.alpha)&&(r[0]=n.red,r[1]=n.green,r[2]=n.blue,r[3]=n.alpha,a.uniform4f(i[e].location,n.red,n.green,n.blue,n.alpha))},(e,t,r,n,i,o,a)=>{r=i[e].value,n=o[e],(r[0]!==n.red||r[1]!==n.green||r[2]!==n.blue)&&(r[0]=n.red,r[1]=n.green,r[2]=n.blue,a.uniform3f(i[e].location,n.red,n.green,n.blue))}];function k(e,t){let r={};for(let n in e.uniformStructures){if(!t[n])continue;let i=e.uniformStructures[n],o=!1;for(let e=0;e<y.s.length;e++){let t=y.s[e];if(i.type===t.type&&t.test(i)){r[n]=A[e],o=!0;break}}if(!o){let e=1===i.size?E:C;r[n]=e[i.type]}}return(e,t,n)=>{let i=n.gl;for(let n in r){let o=t[n],a=e[n],s=e[n].value;r[n](n,a,s,o,e,t,i)}}}!function(){Object.assign(l.I.prototype,{_unsafeEvalCheck(){}}),Object.assign(s.L.prototype,{_systemCheck(){}}),Object.assign(o.V.prototype,{_generateUniformsSync:k}),Object.assign(n.S.prototype,{_generateUboSync:w}),Object.assign(a.Y.prototype,{_generateUboSync:x}),Object.assign(i.S.prototype,{_generateShaderSync:d})}()},39613:function(e,t,r){"use strict";let n;async function i(){return n??(n=(async()=>{let e=document.createElement("canvas").getContext("webgl");if(!e)return"premultiply-alpha-on-upload";let t=await new Promise(e=>{let t=document.createElement("video");t.onloadeddata=()=>e(t),t.onerror=()=>e(null),t.autoplay=!1,t.crossOrigin="anonymous",t.preload="auto",t.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",t.load()});if(!t)return"premultiply-alpha-on-upload";let r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let n=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);let i=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,i),e.deleteFramebuffer(n),e.deleteTexture(r),e.getExtension("WEBGL_lose_context")?.loseContext(),i[0]<=i[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),n}r.d(t,{D:()=>i})},59319:function(e,t,r){"use strict";let n;function i(){if("boolean"==typeof n)return n;try{let e=Function("param1","param2","param3","return param1[param2] === param3;");n=!0===e({a:"b"},"a","b")}catch(e){n=!1}return n}r.d(t,{O:()=>i})},32472:function(e,t,r){"use strict";function n(e,t,r){let n,i=e.length;if(t>=i||0===r)return;r=t+r>i?i-t:r;let o=i-r;for(n=t;n<o;++n)e[n]=e[n+r];e.length=o}r.d(t,{E:()=>n})},45649:function(e,t,r){"use strict";r.d(t,{h:()=>i});let n={default:-1};function i(e="default"){return void 0===n[e]&&(n[e]=-1),++n[e]}},88515:function(e,t,r){"use strict";function n(e,t,r,n){let{width:i,height:o}=r.orig,a=r.trim;if(a){let r=a.width,s=a.height;e.minX=a.x-t._x*i-n,e.maxX=e.minX+r,e.minY=a.y-t._y*o-n,e.maxY=e.minY+s}else e.minX=-t._x*i-n,e.maxX=e.minX+i,e.minY=-t._y*o-n,e.maxY=e.minY+o}r.d(t,{w:()=>n})},24584:function(e,t,r){"use strict";r.d(t,{P:()=>i,a:()=>o});let n={},i="8.0.0";function o(e,t,r=3){if(n[t])return;let i=Error().stack;void 0===i?console.warn("PixiJS Deprecation Warning: ",`${t}
647
647
  Deprecated since v${e}`):(i=i.split("\n").splice(r).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",`${t}
648
648
  Deprecated since v${e}`),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",`${t}
649
- Deprecated since v${e}`),console.warn(i))),n[t]=!0}},92245:function(e,t,r){"use strict";r.d(t,{Z:()=>o});let n=0,i=500;function o(...e){n!==i&&(++n===i?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...e))}},15792:function(e,t,r){"use strict";r.d(t,{E:()=>u});var n=r(767);function i(e){if("string"!=typeof e)throw TypeError(`Path must be a string. Received ${JSON.stringify(e)}`)}function o(e){return e.split("?")[0].split("#")[0]}function a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s(e,t,r){return e.replace(RegExp(a(t),"g"),r)}function l(e,t){let r="",n=0,i=-1,o=0,a=-1;for(let s=0;s<=e.length;++s){if(s<e.length)a=e.charCodeAt(s);else if(47===a)break;else a=47;if(47===a){if(i===s-1||1===o);else if(i!==s-1&&2===o){if(r.length<2||2!==n||46!==r.charCodeAt(r.length-1)||46!==r.charCodeAt(r.length-2)){if(r.length>2){let e=r.lastIndexOf("/");if(e!==r.length-1){-1===e?(r="",n=0):n=(r=r.slice(0,e)).length-1-r.lastIndexOf("/"),i=s,o=0;continue}}else if(2===r.length||1===r.length){r="",n=0,i=s,o=0;continue}}t&&(r.length>0?r+="/..":r="..",n=2)}else r.length>0?r+=`/${e.slice(i+1,s)}`:r=e.slice(i+1,s),n=s-i-1;i=s,o=0}else 46===a&&-1!==o?++o:o=-1}return r}let u={toPosix:e=>s(e,"\\","/"),isUrl(e){return/^https?:/.test(this.toPosix(e))},isDataUrl:e=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(e),isBlobUrl:e=>e.startsWith("blob:"),hasProtocol(e){return/^[^/:]+:/.test(this.toPosix(e))},getProtocol(e){i(e),e=this.toPosix(e);let t=/^file:\/\/\//.exec(e);if(t)return t[0];let r=/^[^/:]+:\/{0,2}/.exec(e);return r?r[0]:""},toAbsolute(e,t,r){if(i(e),this.isDataUrl(e)||this.isBlobUrl(e))return e;let a=o(this.toPosix(t??n.z.get().getBaseUrl())),s=o(this.toPosix(r??this.rootname(a)));return(e=this.toPosix(e)).startsWith("/")?u.join(s,e.slice(1)):this.isAbsolute(e)?e:this.join(a,e)},normalize(e){if(i(e),0===e.length)return".";if(this.isDataUrl(e)||this.isBlobUrl(e))return e;e=this.toPosix(e);let t="",r=e.startsWith("/");this.hasProtocol(e)&&(t=this.rootname(e),e=e.slice(t.length));let n=e.endsWith("/");return((e=l(e,!1)).length>0&&n&&(e+="/"),r)?`/${e}`:t+e},isAbsolute(e){return i(e),e=this.toPosix(e),!!this.hasProtocol(e)||e.startsWith("/")},join(...e){let t;if(0===e.length)return".";for(let r=0;r<e.length;++r){let n=e[r];if(i(n),n.length>0)if(void 0===t)t=n;else{let i=e[r-1]??"";this.joinExtensions.includes(this.extname(i).toLowerCase())?t+=`/../${n}`:t+=`/${n}`}}return void 0===t?".":this.normalize(t)},dirname(e){if(i(e),0===e.length)return".";let t=(e=this.toPosix(e)).charCodeAt(0),r=47===t,n=-1,o=!0,a=this.getProtocol(e),s=e;e=e.slice(a.length);for(let r=e.length-1;r>=1;--r)if(47===(t=e.charCodeAt(r))){if(!o){n=r;break}}else o=!1;return -1===n?r?"/":this.isUrl(s)?a+e:a:r&&1===n?"//":a+e.slice(0,n)},rootname(e){i(e);let t="";if(t=(e=this.toPosix(e)).startsWith("/")?"/":this.getProtocol(e),this.isUrl(e)){let r=e.indexOf("/",t.length);(t=-1!==r?e.slice(0,r):e).endsWith("/")||(t+="/")}return t},basename(e,t){let r;i(e),t&&i(t),e=o(this.toPosix(e));let n=0,a=-1,s=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let i=t.length-1,o=-1;for(r=e.length-1;r>=0;--r){let l=e.charCodeAt(r);if(47===l){if(!s){n=r+1;break}}else -1===o&&(s=!1,o=r+1),i>=0&&(l===t.charCodeAt(i)?-1==--i&&(a=r):(i=-1,a=o))}return n===a?a=o:-1===a&&(a=e.length),e.slice(n,a)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!s){n=r+1;break}}else -1===a&&(s=!1,a=r+1);return -1===a?"":e.slice(n,a)},extname(e){i(e),e=o(this.toPosix(e));let t=-1,r=0,n=-1,a=!0,s=0;for(let i=e.length-1;i>=0;--i){let o=e.charCodeAt(i);if(47===o){if(!a){r=i+1;break}continue}-1===n&&(a=!1,n=i+1),46===o?-1===t?t=i:1!==s&&(s=1):-1!==t&&(s=-1)}return -1===t||-1===n||0===s||1===s&&t===n-1&&t===r+1?"":e.slice(t,n)},parse(e){let t;i(e);let r={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return r;let n=(e=o(this.toPosix(e))).charCodeAt(0),a=this.isAbsolute(e),s="";r.root=this.rootname(e),t=a||this.hasProtocol(e)?1:0;let l=-1,u=0,c=-1,h=!0,f=e.length-1,d=0;for(;f>=t;--f){if(47===(n=e.charCodeAt(f))){if(!h){u=f+1;break}continue}-1===c&&(h=!1,c=f+1),46===n?-1===l?l=f:1!==d&&(d=1):-1!==l&&(d=-1)}return -1===l||-1===c||0===d||1===d&&l===c-1&&l===u+1?-1!==c&&(0===u&&a?r.base=r.name=e.slice(1,c):r.base=r.name=e.slice(u,c)):(0===u&&a?(r.name=e.slice(1,l),r.base=e.slice(1,c)):(r.name=e.slice(u,l),r.base=e.slice(u,c)),r.ext=e.slice(l,c)),r.dir=this.dirname(e),s&&(r.dir=s+r.dir),r},sep:"/",delimiter:":",joinExtensions:[".html"]}},25400:function(e,t,r){"use strict";r.d(t,{K:()=>n});class n{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){let t;return t=this._index>0?this._pool[--this._index]:new this._classType,t.init?.(e),t}return(e){e.reset?.(),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}}},24951:function(e,t,r){"use strict";r.d(t,{u:()=>o});var n=r(25400);class i{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new n.K(e)),this._poolsByClass.get(e)}stats(){let e={};return this._poolsByClass.forEach(t=>{let r=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[r]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}}let o=new i},90419:function(e,t,r){"use strict";let n,i;r.d(t,{io:()=>eW});var o,a={};r.r(a),r.d(a,{Decoder:()=>eL,Encoder:()=>ej,PacketType:()=>o,protocol:()=>eN});let s=Object.create(null);s.open="0",s.close="1",s.ping="2",s.pong="3",s.message="4",s.upgrade="5",s.noop="6";let l=Object.create(null);Object.keys(s).forEach(e=>{l[s[e]]=e});let u={type:"error",data:"parser error"},c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),h="function"==typeof ArrayBuffer,f=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,d=({type:e,data:t},r,n)=>{if(c&&t instanceof Blob)if(r)return n(t);else return p(t,n);if(h&&(t instanceof ArrayBuffer||f(t)))if(r)return n(t);else return p(new Blob([t]),n);return n(s[e]+(t||""))},p=(e,t)=>{let r=new FileReader;return r.onload=function(){t("b"+(r.result.split(",")[1]||""))},r.readAsDataURL(e)};function m(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function g(e,t){return c&&e.data instanceof Blob?e.data.arrayBuffer().then(m).then(t):h&&(e.data instanceof ArrayBuffer||f(e.data))?t(m(e.data)):void d(e,!1,e=>{n||(n=new TextEncoder),t(n.encode(e))})}let y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",v="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<y.length;e++)v[y.charCodeAt(e)]=e;let b=e=>{let t=.75*e.length,r=e.length,n,i=0,o,a,s,l;"="===e[e.length-1]&&(t--,"="===e[e.length-2]&&t--);let u=new ArrayBuffer(t),c=new Uint8Array(u);for(n=0;n<r;n+=4)o=v[e.charCodeAt(n)],a=v[e.charCodeAt(n+1)],s=v[e.charCodeAt(n+2)],l=v[e.charCodeAt(n+3)],c[i++]=o<<2|a>>4,c[i++]=(15&a)<<4|s>>2,c[i++]=(3&s)<<6|63&l;return u},_="function"==typeof ArrayBuffer,w=(e,t)=>{if("string"!=typeof e)return{type:"message",data:S(e,t)};let r=e.charAt(0);return"b"===r?{type:"message",data:x(e.substring(1),t)}:l[r]?e.length>1?{type:l[r],data:e.substring(1)}:{type:l[r]}:u},x=(e,t)=>_?S(b(e),t):{base64:!0,data:e},S=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,E="\x1e",C=(e,t)=>{let r=e.length,n=Array(r),i=0;e.forEach((e,o)=>{d(e,!1,e=>{n[o]=e,++i===r&&t(n.join(E))})})},A=(e,t)=>{let r=e.split(E),n=[];for(let e=0;e<r.length;e++){let i=w(r[e],t);if(n.push(i),"error"===i.type)break}return n};function k(){return new TransformStream({transform(e,t){g(e,r=>{let n,i=r.length;if(i<126)new DataView((n=new Uint8Array(1)).buffer).setUint8(0,i);else if(i<65536){let e=new DataView((n=new Uint8Array(3)).buffer);e.setUint8(0,126),e.setUint16(1,i)}else{let e=new DataView((n=new Uint8Array(9)).buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}function O(e){return e.reduce((e,t)=>e+t.length,0)}function T(e,t){if(e[0].length===t)return e.shift();let r=new Uint8Array(t),n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function I(e,t){i||(i=new TextDecoder);let r=[],n=0,o=-1,a=!1;return new TransformStream({transform(s,l){for(r.push(s);;){if(0===n){if(1>O(r))break;let e=T(r,1);a=(128&e[0])==128,n=(o=127&e[0])<126?3:126===o?1:2}else if(1===n){if(2>O(r))break;let e=T(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(8>O(r))break;let e=T(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>2097151){l.enqueue(u);break}o=0x100000000*i+t.getUint32(4),n=3}else{if(O(r)<o)break;let e=T(r,o);l.enqueue(w(a?e:i.decode(e),t)),n=0}if(0===o||o>e){l.enqueue(u);break}}}})}let P=4;function R(e){if(e)return M(e)}function M(e){for(var t in R.prototype)e[t]=R.prototype[t];return e}R.prototype.on=R.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},R.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},R.prototype.off=R.prototype.removeListener=R.prototype.removeAllListeners=R.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},R.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,i=r.length;n<i;++n)r[n].apply(this,t)}return this},R.prototype.emitReserved=R.prototype.emit,R.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},R.prototype.hasListeners=function(e){return!!this.listeners(e).length};let $="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),N="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),j="arraybuffer";function B(){}function L(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}let F=N.setTimeout,D=N.clearTimeout;function z(e,t){t.useNativeTimers?(e.setTimeoutFn=F.bind(N),e.clearTimeoutFn=D.bind(N)):(e.setTimeoutFn=N.setTimeout.bind(N),e.clearTimeoutFn=N.clearTimeout.bind(N))}let U=1.33;function Z(e){return"string"==typeof e?H(e):Math.ceil((e.byteLength||e.size)*U)}function H(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)(t=e.charCodeAt(n))<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}function G(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function W(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function q(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}class V extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class X extends R{constructor(e){super(),this.writable=!1,z(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new V(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return("opening"===this.readyState||"open"===this.readyState)&&(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=w(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return -1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){let t=W(e);return t.length?"?"+t:""}}class Y extends X{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)};A(e,this.socket.binaryType).forEach(t),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,C(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=G()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let K=!1;try{K="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let J=K;function Q(){}class ee extends Y{constructor(e){if(super(e),"undefined"!=typeof location){let t="https:"===location.protocol,r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class et extends R{constructor(e,t,r){super(),this.createRequest=e,z(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var e;let t=L(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders)for(let e in r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0),this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}catch(e){}if("POST"===this._method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null==(e=this._opts.cookieJar)||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null==(e=this._opts.cookieJar)||e.parseCookies(r.getResponseHeader("set-cookie"))),4===r.readyState&&(200===r.status||1223===r.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof r.status?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}"undefined"!=typeof document&&(this._index=et.requestsCount++,et.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Q,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete et.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function er(){for(let e in et.requests)et.requests.hasOwnProperty(e)&&et.requests[e].abort()}et.requestsCount=0,et.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",er):"function"==typeof addEventListener&&addEventListener("onpagehide"in N?"pagehide":"unload",er,!1));let en=function(){let e=eo({xdomain:!1});return e&&null!==e.responseType}();class ei extends ee{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=en&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new et(eo,this.uri(),e)}}function eo(e){let t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||J))return new XMLHttpRequest}catch(e){}if(!t)try{return new N[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let ea="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class es extends X{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=ea?{}:L(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;d(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(e){}n&&$(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=G()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let el=N.WebSocket||N.MozWebSocket;class eu extends es{createSocket(e,t,r){return ea?new el(e,t,r):t?new el(e,t):new el(e)}doWrite(e,t){this.ws.send(t)}}class ec extends X{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=I(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=k();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let i=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;this._writer.write(r).then(()=>{n&&$(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}}let eh={websocket:eu,webtransport:ec,polling:ei},ef=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ed=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ep(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=ef.exec(e||""),o={},a=14;for(;a--;)o[ed[a]]=i[a]||"";return -1!=r&&-1!=n&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=em(o,o.path),o.queryKey=eg(o,o.query),o}function em(e,t){let r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return("/"==t.slice(0,1)||0===t.length)&&n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}function eg(e,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),r}let ey="function"==typeof addEventListener&&"function"==typeof removeEventListener,ev=[];ey&&addEventListener("offline",()=>{ev.forEach(e=>e())},!1);class eb extends R{constructor(e,t){if(super(),this.binaryType=j,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){let r=ep(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=ep(t.host).host);z(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=q(this.opts.query)),ey&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ev.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=B()),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=P,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);let e=this.opts.rememberUpgrade&&eb.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",eb.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let r=this.writeBuffer[t].data;if(r&&(e+=Z(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,$(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return("opening"===this.readyState||"open"===this.readyState)&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(eb.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ey&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ev.indexOf(this._offlineEventListener);-1!==e&&ev.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eb.protocol=P;class e_ extends eb{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;eb.priorWebsocketSuccess=!1;let n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;eb.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){r||(r=!0,u(),t.close(),t=null)}let o=e=>{let r=Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function a(){o("transport closed")}function s(){o("socket closed")}function l(e){t&&e.name!==t.name&&i()}let u=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",n),t.once("error",o),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}class ew extends e_{constructor(e,t={}){let r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>eh[e]).filter(e=>!!e)),super(e,r)}}function ex(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=ep(e)),!n.port&&(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}ew.protocol;let eS="function"==typeof ArrayBuffer,eE=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,eC=Object.prototype.toString,eA="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===eC.call(Blob),ek="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===eC.call(File);function eO(e){return eS&&(e instanceof ArrayBuffer||eE(e))||eA&&e instanceof Blob||ek&&e instanceof File}function eT(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(eT(e[t]))return!0;return!1}if(eO(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1==arguments.length)return eT(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&eT(e[t]))return!0;return!1}function eI(e){let t=[],r=e.data,n=e;return n.data=eP(r,t),n.attachments=t.length,{packet:n,buffers:t}}function eP(e,t){if(!e)return e;if(eO(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){let r=Array(e.length);for(let n=0;n<e.length;n++)r[n]=eP(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=eP(e[n],t));return r}return e}function eR(e,t){return e.data=eM(e.data,t),delete e.attachments,e}function eM(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=eM(e[r],t);else if("object"==typeof e)for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=eM(e[r],t));return e}let e$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],eN=5;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(o||(o={}));class ej{constructor(e){this.replacer=e}encode(e){return(e.type===o.EVENT||e.type===o.ACK)&&eT(e)?this.encodeAsBinary({type:e.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===o.BINARY_EVENT||e.type===o.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=eI(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}function eB(e){return"[object Object]"===Object.prototype.toString.call(e)}class eL extends R{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw Error("got plaintext data when reconstructing a packet");let r=(t=this.decodeString(e)).type===o.BINARY_EVENT;r||t.type===o.BINARY_ACK?(t.type=r?o.EVENT:o.ACK,this.reconstructor=new eF(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(eO(e)||e.base64)if(this.reconstructor)(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw Error("got binary data when not reconstructing a packet");else throw Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(void 0===o[r.type])throw Error("unknown packet type "+r.type);if(r.type===o.BINARY_EVENT||r.type===o.BINARY_ACK){let n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);let i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){let n=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);r.nsp=e.substring(n,t)}else r.nsp="/";let n=e.charAt(t+1);if(""!==n&&Number(n)==n){let n=t+1;for(;++t;){let r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(eL.isPayloadValid(r.type,n))r.data=n;else throw Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case o.CONNECT:return eB(t);case o.DISCONNECT:return void 0===t;case o.CONNECT_ERROR:return"string"==typeof t||eB(t);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===e$.indexOf(t[0]));case o.ACK:case o.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class eF{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=eR(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function eD(e,t,r){return e.on(t,r),function(){e.off(t,r)}}let ez=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class eU extends R{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[eD(e,"open",this.onopen.bind(this)),eD(e,"packet",this.onpacket.bind(this)),eD(e,"error",this.onerror.bind(this)),eD(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,n,i;if(ez.hasOwnProperty(e))throw Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:o.EVENT,data:t};if(a.options={},a.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),a.id=e}let s=null==(n=null==(r=this.io.engine)?void 0:r.transport)?void 0:n.writable,l=this.connected&&!(null==(i=this.io.engine)?void 0:i._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var r;let n=null!=(r=this.flags.timeout)?r:this._opts.ackTimeout;if(void 0===n){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error("operation has timed out"))},n),o=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,n)=>{let i=(e,t)=>e?n(e):r(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(r===this._queue[0])return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:o.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case o.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case o.EVENT:case o.BINARY_EVENT:this.onevent(e);break;case o.ACK:case o.BINARY_ACK:this.onack(e);break;case o.DISCONNECT:this.ondisconnect();break;case o.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){let t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length)for(let t of this._anyListeners.slice())t.apply(this,e);super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...n){r||(r=!0,t.packet({type:o.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:o.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r]){t.splice(r,1);break}}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r]){t.splice(r,1);break}}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length)for(let t of this._anyOutgoingListeners.slice())t.apply(this,e.data)}}function eZ(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}eZ.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=(1&Math.floor(10*t))==0?e-r:e+r}return 0|Math.min(e,this.max)},eZ.prototype.reset=function(){this.attempts=0},eZ.prototype.setMin=function(e){this.ms=e},eZ.prototype.setMax=function(e){this.max=e},eZ.prototype.setJitter=function(e){this.jitter=e};class eH extends R{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,z(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!=(r=t.randomizationFactor)?r:.5),this.backoff=new eZ({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||a;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null==(t=this.backoff)||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null==(t=this.backoff)||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null==(t=this.backoff)||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ew(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let n=eD(t,"open",function(){r.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=eD(t,"error",i);if(!1!==this._timeout){let e=this._timeout,r=this.setTimeoutFn(()=>{n(),i(Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(n),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(eD(e,"ping",this.onping.bind(this)),eD(e,"data",this.ondata.bind(this)),eD(e,"error",this.onerror.bind(this)),eD(e,"close",this.onclose.bind(this)),eD(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){$(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new eU(this,e,t),this.nsps[e]=r),r}_destroy(e){for(let e of Object.keys(this.nsps))if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null==(r=this.engine)||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{!e.skipReconnect&&(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}let eG={};function eW(e,t){let r;"object"==typeof e&&(t=e,e=void 0);let n=ex(e,(t=t||{}).path||"/socket.io"),i=n.source,o=n.id,a=n.path,s=eG[o]&&a in eG[o].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?r=new eH(i,t):(eG[o]||(eG[o]=new eH(i,t)),r=eG[o]),n.query&&!t.query&&(t.query=n.queryKey),r.socket(n.path,t)}Object.assign(eW,{Manager:eH,Socket:eU,io:eW,connect:eW})},62858:function(e,t,r){"use strict";r.d(t,{Ue:()=>d});let n=e=>{let t,r=new Set,n=(e,n)=>{let i="function"==typeof e?e(t):e;if(!Object.is(i,t)){let e=t;t=(null!=n?n:"object"!=typeof i||null===i)?i:Object.assign({},t,i),r.forEach(r=>r(t,e))}},i=()=>t,o={setState:n,getState:i,getInitialState:()=>a,subscribe:e=>(r.add(e),()=>r.delete(e)),destroy:()=>{console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},a=t=e(n,i,o);return o},i=e=>e?n(e):n;var o=r(44194),a=r(67591);let{useDebugValue:s}=o,{useSyncExternalStoreWithSelector:l}=a,u=!1,c=e=>e;function h(e,t=c,r){r&&!u&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),u=!0);let n=l(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return s(n),n}let f=e=>{"function"!=typeof e&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");let t="function"==typeof e?i(e):e,r=(e,r)=>h(t,e,r);return Object.assign(r,t),r},d=e=>e?f(e):f}}]);
650
- //# sourceMappingURL=806.d6c23766.js.map
649
+ Deprecated since v${e}`),console.warn(i))),n[t]=!0}},92245:function(e,t,r){"use strict";r.d(t,{Z:()=>o});let n=0,i=500;function o(...e){n!==i&&(++n===i?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...e))}},15792:function(e,t,r){"use strict";r.d(t,{E:()=>u});var n=r(767);function i(e){if("string"!=typeof e)throw TypeError(`Path must be a string. Received ${JSON.stringify(e)}`)}function o(e){return e.split("?")[0].split("#")[0]}function a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s(e,t,r){return e.replace(RegExp(a(t),"g"),r)}function l(e,t){let r="",n=0,i=-1,o=0,a=-1;for(let s=0;s<=e.length;++s){if(s<e.length)a=e.charCodeAt(s);else if(47===a)break;else a=47;if(47===a){if(i===s-1||1===o);else if(i!==s-1&&2===o){if(r.length<2||2!==n||46!==r.charCodeAt(r.length-1)||46!==r.charCodeAt(r.length-2)){if(r.length>2){let e=r.lastIndexOf("/");if(e!==r.length-1){-1===e?(r="",n=0):n=(r=r.slice(0,e)).length-1-r.lastIndexOf("/"),i=s,o=0;continue}}else if(2===r.length||1===r.length){r="",n=0,i=s,o=0;continue}}t&&(r.length>0?r+="/..":r="..",n=2)}else r.length>0?r+=`/${e.slice(i+1,s)}`:r=e.slice(i+1,s),n=s-i-1;i=s,o=0}else 46===a&&-1!==o?++o:o=-1}return r}let u={toPosix:e=>s(e,"\\","/"),isUrl(e){return/^https?:/.test(this.toPosix(e))},isDataUrl:e=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(e),isBlobUrl:e=>e.startsWith("blob:"),hasProtocol(e){return/^[^/:]+:/.test(this.toPosix(e))},getProtocol(e){i(e),e=this.toPosix(e);let t=/^file:\/\/\//.exec(e);if(t)return t[0];let r=/^[^/:]+:\/{0,2}/.exec(e);return r?r[0]:""},toAbsolute(e,t,r){if(i(e),this.isDataUrl(e)||this.isBlobUrl(e))return e;let a=o(this.toPosix(t??n.z.get().getBaseUrl())),s=o(this.toPosix(r??this.rootname(a)));return(e=this.toPosix(e)).startsWith("/")?u.join(s,e.slice(1)):this.isAbsolute(e)?e:this.join(a,e)},normalize(e){if(i(e),0===e.length)return".";if(this.isDataUrl(e)||this.isBlobUrl(e))return e;e=this.toPosix(e);let t="",r=e.startsWith("/");this.hasProtocol(e)&&(t=this.rootname(e),e=e.slice(t.length));let n=e.endsWith("/");return((e=l(e,!1)).length>0&&n&&(e+="/"),r)?`/${e}`:t+e},isAbsolute(e){return i(e),e=this.toPosix(e),!!this.hasProtocol(e)||e.startsWith("/")},join(...e){let t;if(0===e.length)return".";for(let r=0;r<e.length;++r){let n=e[r];if(i(n),n.length>0)if(void 0===t)t=n;else{let i=e[r-1]??"";this.joinExtensions.includes(this.extname(i).toLowerCase())?t+=`/../${n}`:t+=`/${n}`}}return void 0===t?".":this.normalize(t)},dirname(e){if(i(e),0===e.length)return".";let t=(e=this.toPosix(e)).charCodeAt(0),r=47===t,n=-1,o=!0,a=this.getProtocol(e),s=e;e=e.slice(a.length);for(let r=e.length-1;r>=1;--r)if(47===(t=e.charCodeAt(r))){if(!o){n=r;break}}else o=!1;return -1===n?r?"/":this.isUrl(s)?a+e:a:r&&1===n?"//":a+e.slice(0,n)},rootname(e){i(e);let t="";if(t=(e=this.toPosix(e)).startsWith("/")?"/":this.getProtocol(e),this.isUrl(e)){let r=e.indexOf("/",t.length);(t=-1!==r?e.slice(0,r):e).endsWith("/")||(t+="/")}return t},basename(e,t){let r;i(e),t&&i(t),e=o(this.toPosix(e));let n=0,a=-1,s=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let i=t.length-1,o=-1;for(r=e.length-1;r>=0;--r){let l=e.charCodeAt(r);if(47===l){if(!s){n=r+1;break}}else -1===o&&(s=!1,o=r+1),i>=0&&(l===t.charCodeAt(i)?-1==--i&&(a=r):(i=-1,a=o))}return n===a?a=o:-1===a&&(a=e.length),e.slice(n,a)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!s){n=r+1;break}}else -1===a&&(s=!1,a=r+1);return -1===a?"":e.slice(n,a)},extname(e){i(e),e=o(this.toPosix(e));let t=-1,r=0,n=-1,a=!0,s=0;for(let i=e.length-1;i>=0;--i){let o=e.charCodeAt(i);if(47===o){if(!a){r=i+1;break}continue}-1===n&&(a=!1,n=i+1),46===o?-1===t?t=i:1!==s&&(s=1):-1!==t&&(s=-1)}return -1===t||-1===n||0===s||1===s&&t===n-1&&t===r+1?"":e.slice(t,n)},parse(e){let t;i(e);let r={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return r;let n=(e=o(this.toPosix(e))).charCodeAt(0),a=this.isAbsolute(e),s="";r.root=this.rootname(e),t=a||this.hasProtocol(e)?1:0;let l=-1,u=0,c=-1,h=!0,f=e.length-1,d=0;for(;f>=t;--f){if(47===(n=e.charCodeAt(f))){if(!h){u=f+1;break}continue}-1===c&&(h=!1,c=f+1),46===n?-1===l?l=f:1!==d&&(d=1):-1!==l&&(d=-1)}return -1===l||-1===c||0===d||1===d&&l===c-1&&l===u+1?-1!==c&&(0===u&&a?r.base=r.name=e.slice(1,c):r.base=r.name=e.slice(u,c)):(0===u&&a?(r.name=e.slice(1,l),r.base=e.slice(1,c)):(r.name=e.slice(u,l),r.base=e.slice(u,c)),r.ext=e.slice(l,c)),r.dir=this.dirname(e),s&&(r.dir=s+r.dir),r},sep:"/",delimiter:":",joinExtensions:[".html"]}},25400:function(e,t,r){"use strict";r.d(t,{K:()=>n});class n{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){let t;return t=this._index>0?this._pool[--this._index]:new this._classType,t.init?.(e),t}return(e){e.reset?.(),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}}},24951:function(e,t,r){"use strict";r.d(t,{u:()=>o});var n=r(25400);class i{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new n.K(e)),this._poolsByClass.get(e)}stats(){let e={};return this._poolsByClass.forEach(t=>{let r=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[r]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}}let o=new i},90419:function(e,t,r){"use strict";let n,i;r.d(t,{io:()=>eW});var o,a={};r.r(a),r.d(a,{Decoder:()=>eL,Encoder:()=>ej,PacketType:()=>o,protocol:()=>eN});let s=Object.create(null);s.open="0",s.close="1",s.ping="2",s.pong="3",s.message="4",s.upgrade="5",s.noop="6";let l=Object.create(null);Object.keys(s).forEach(e=>{l[s[e]]=e});let u={type:"error",data:"parser error"},c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),h="function"==typeof ArrayBuffer,f=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,d=({type:e,data:t},r,n)=>{if(c&&t instanceof Blob)if(r)return n(t);else return p(t,n);if(h&&(t instanceof ArrayBuffer||f(t)))if(r)return n(t);else return p(new Blob([t]),n);return n(s[e]+(t||""))},p=(e,t)=>{let r=new FileReader;return r.onload=function(){t("b"+(r.result.split(",")[1]||""))},r.readAsDataURL(e)};function m(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function g(e,t){return c&&e.data instanceof Blob?e.data.arrayBuffer().then(m).then(t):h&&(e.data instanceof ArrayBuffer||f(e.data))?t(m(e.data)):void d(e,!1,e=>{n||(n=new TextEncoder),t(n.encode(e))})}let y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",v="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<y.length;e++)v[y.charCodeAt(e)]=e;let b=e=>{let t=.75*e.length,r=e.length,n,i=0,o,a,s,l;"="===e[e.length-1]&&(t--,"="===e[e.length-2]&&t--);let u=new ArrayBuffer(t),c=new Uint8Array(u);for(n=0;n<r;n+=4)o=v[e.charCodeAt(n)],a=v[e.charCodeAt(n+1)],s=v[e.charCodeAt(n+2)],l=v[e.charCodeAt(n+3)],c[i++]=o<<2|a>>4,c[i++]=(15&a)<<4|s>>2,c[i++]=(3&s)<<6|63&l;return u},_="function"==typeof ArrayBuffer,w=(e,t)=>{if("string"!=typeof e)return{type:"message",data:S(e,t)};let r=e.charAt(0);return"b"===r?{type:"message",data:x(e.substring(1),t)}:l[r]?e.length>1?{type:l[r],data:e.substring(1)}:{type:l[r]}:u},x=(e,t)=>_?S(b(e),t):{base64:!0,data:e},S=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,E="\x1e",C=(e,t)=>{let r=e.length,n=Array(r),i=0;e.forEach((e,o)=>{d(e,!1,e=>{n[o]=e,++i===r&&t(n.join(E))})})},A=(e,t)=>{let r=e.split(E),n=[];for(let e=0;e<r.length;e++){let i=w(r[e],t);if(n.push(i),"error"===i.type)break}return n};function k(){return new TransformStream({transform(e,t){g(e,r=>{let n,i=r.length;if(i<126)new DataView((n=new Uint8Array(1)).buffer).setUint8(0,i);else if(i<65536){let e=new DataView((n=new Uint8Array(3)).buffer);e.setUint8(0,126),e.setUint16(1,i)}else{let e=new DataView((n=new Uint8Array(9)).buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}function O(e){return e.reduce((e,t)=>e+t.length,0)}function T(e,t){if(e[0].length===t)return e.shift();let r=new Uint8Array(t),n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function I(e,t){i||(i=new TextDecoder);let r=[],n=0,o=-1,a=!1;return new TransformStream({transform(s,l){for(r.push(s);;){if(0===n){if(1>O(r))break;let e=T(r,1);a=(128&e[0])==128,n=(o=127&e[0])<126?3:126===o?1:2}else if(1===n){if(2>O(r))break;let e=T(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(8>O(r))break;let e=T(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>2097151){l.enqueue(u);break}o=0x100000000*i+t.getUint32(4),n=3}else{if(O(r)<o)break;let e=T(r,o);l.enqueue(w(a?e:i.decode(e),t)),n=0}if(0===o||o>e){l.enqueue(u);break}}}})}let P=4;function R(e){if(e)return M(e)}function M(e){for(var t in R.prototype)e[t]=R.prototype[t];return e}R.prototype.on=R.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},R.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},R.prototype.off=R.prototype.removeListener=R.prototype.removeAllListeners=R.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},R.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,i=r.length;n<i;++n)r[n].apply(this,t)}return this},R.prototype.emitReserved=R.prototype.emit,R.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},R.prototype.hasListeners=function(e){return!!this.listeners(e).length};let $="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),N="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),j="arraybuffer";function B(){}function L(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}let F=N.setTimeout,D=N.clearTimeout;function z(e,t){t.useNativeTimers?(e.setTimeoutFn=F.bind(N),e.clearTimeoutFn=D.bind(N)):(e.setTimeoutFn=N.setTimeout.bind(N),e.clearTimeoutFn=N.clearTimeout.bind(N))}let U=1.33;function Z(e){return"string"==typeof e?H(e):Math.ceil((e.byteLength||e.size)*U)}function H(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)(t=e.charCodeAt(n))<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}function G(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function W(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function q(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}class V extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class X extends R{constructor(e){super(),this.writable=!1,z(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new V(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return("opening"===this.readyState||"open"===this.readyState)&&(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=w(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return -1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){let t=W(e);return t.length?"?"+t:""}}class Y extends X{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)};A(e,this.socket.binaryType).forEach(t),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,C(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=G()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let K=!1;try{K="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let J=K;function Q(){}class ee extends Y{constructor(e){if(super(e),"undefined"!=typeof location){let t="https:"===location.protocol,r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class et extends R{constructor(e,t,r){super(),this.createRequest=e,z(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var e;let t=L(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders)for(let e in r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0),this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}catch(e){}if("POST"===this._method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null==(e=this._opts.cookieJar)||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null==(e=this._opts.cookieJar)||e.parseCookies(r.getResponseHeader("set-cookie"))),4===r.readyState&&(200===r.status||1223===r.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof r.status?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}"undefined"!=typeof document&&(this._index=et.requestsCount++,et.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Q,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete et.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function er(){for(let e in et.requests)et.requests.hasOwnProperty(e)&&et.requests[e].abort()}et.requestsCount=0,et.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",er):"function"==typeof addEventListener&&addEventListener("onpagehide"in N?"pagehide":"unload",er,!1));let en=function(){let e=eo({xdomain:!1});return e&&null!==e.responseType}();class ei extends ee{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=en&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new et(eo,this.uri(),e)}}function eo(e){let t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||J))return new XMLHttpRequest}catch(e){}if(!t)try{return new N[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let ea="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class es extends X{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=ea?{}:L(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;d(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(e){}n&&$(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=G()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let el=N.WebSocket||N.MozWebSocket;class eu extends es{createSocket(e,t,r){return ea?new el(e,t,r):t?new el(e,t):new el(e)}doWrite(e,t){this.ws.send(t)}}class ec extends X{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=I(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=k();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let i=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;this._writer.write(r).then(()=>{n&&$(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}}let eh={websocket:eu,webtransport:ec,polling:ei},ef=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ed=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ep(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=ef.exec(e||""),o={},a=14;for(;a--;)o[ed[a]]=i[a]||"";return -1!=r&&-1!=n&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=em(o,o.path),o.queryKey=eg(o,o.query),o}function em(e,t){let r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return("/"==t.slice(0,1)||0===t.length)&&n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}function eg(e,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),r}let ey="function"==typeof addEventListener&&"function"==typeof removeEventListener,ev=[];ey&&addEventListener("offline",()=>{ev.forEach(e=>e())},!1);class eb extends R{constructor(e,t){if(super(),this.binaryType=j,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){let r=ep(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=ep(t.host).host);z(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=q(this.opts.query)),ey&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ev.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=B()),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=P,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);let e=this.opts.rememberUpgrade&&eb.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",eb.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let r=this.writeBuffer[t].data;if(r&&(e+=Z(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,$(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return("opening"===this.readyState||"open"===this.readyState)&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(eb.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ey&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ev.indexOf(this._offlineEventListener);-1!==e&&ev.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eb.protocol=P;class e_ extends eb{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;eb.priorWebsocketSuccess=!1;let n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;eb.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){r||(r=!0,u(),t.close(),t=null)}let o=e=>{let r=Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function a(){o("transport closed")}function s(){o("socket closed")}function l(e){t&&e.name!==t.name&&i()}let u=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",n),t.once("error",o),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}class ew extends e_{constructor(e,t={}){let r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>eh[e]).filter(e=>!!e)),super(e,r)}}function ex(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=ep(e)),!n.port&&(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}ew.protocol;let eS="function"==typeof ArrayBuffer,eE=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,eC=Object.prototype.toString,eA="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===eC.call(Blob),ek="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===eC.call(File);function eO(e){return eS&&(e instanceof ArrayBuffer||eE(e))||eA&&e instanceof Blob||ek&&e instanceof File}function eT(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(eT(e[t]))return!0;return!1}if(eO(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1==arguments.length)return eT(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&eT(e[t]))return!0;return!1}function eI(e){let t=[],r=e.data,n=e;return n.data=eP(r,t),n.attachments=t.length,{packet:n,buffers:t}}function eP(e,t){if(!e)return e;if(eO(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){let r=Array(e.length);for(let n=0;n<e.length;n++)r[n]=eP(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=eP(e[n],t));return r}return e}function eR(e,t){return e.data=eM(e.data,t),delete e.attachments,e}function eM(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=eM(e[r],t);else if("object"==typeof e)for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=eM(e[r],t));return e}let e$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],eN=5;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(o||(o={}));class ej{constructor(e){this.replacer=e}encode(e){return(e.type===o.EVENT||e.type===o.ACK)&&eT(e)?this.encodeAsBinary({type:e.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===o.BINARY_EVENT||e.type===o.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=eI(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}function eB(e){return"[object Object]"===Object.prototype.toString.call(e)}class eL extends R{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw Error("got plaintext data when reconstructing a packet");let r=(t=this.decodeString(e)).type===o.BINARY_EVENT;r||t.type===o.BINARY_ACK?(t.type=r?o.EVENT:o.ACK,this.reconstructor=new eF(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(eO(e)||e.base64)if(this.reconstructor)(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw Error("got binary data when not reconstructing a packet");else throw Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(void 0===o[r.type])throw Error("unknown packet type "+r.type);if(r.type===o.BINARY_EVENT||r.type===o.BINARY_ACK){let n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);let i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){let n=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);r.nsp=e.substring(n,t)}else r.nsp="/";let n=e.charAt(t+1);if(""!==n&&Number(n)==n){let n=t+1;for(;++t;){let r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(eL.isPayloadValid(r.type,n))r.data=n;else throw Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case o.CONNECT:return eB(t);case o.DISCONNECT:return void 0===t;case o.CONNECT_ERROR:return"string"==typeof t||eB(t);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===e$.indexOf(t[0]));case o.ACK:case o.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class eF{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=eR(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function eD(e,t,r){return e.on(t,r),function(){e.off(t,r)}}let ez=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class eU extends R{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[eD(e,"open",this.onopen.bind(this)),eD(e,"packet",this.onpacket.bind(this)),eD(e,"error",this.onerror.bind(this)),eD(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,n,i;if(ez.hasOwnProperty(e))throw Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:o.EVENT,data:t};if(a.options={},a.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),a.id=e}let s=null==(n=null==(r=this.io.engine)?void 0:r.transport)?void 0:n.writable,l=this.connected&&!(null==(i=this.io.engine)?void 0:i._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var r;let n=null!=(r=this.flags.timeout)?r:this._opts.ackTimeout;if(void 0===n){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error("operation has timed out"))},n),o=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,n)=>{let i=(e,t)=>e?n(e):r(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(r===this._queue[0])return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:o.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case o.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case o.EVENT:case o.BINARY_EVENT:this.onevent(e);break;case o.ACK:case o.BINARY_ACK:this.onack(e);break;case o.DISCONNECT:this.ondisconnect();break;case o.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){let t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length)for(let t of this._anyListeners.slice())t.apply(this,e);super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...n){r||(r=!0,t.packet({type:o.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:o.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r]){t.splice(r,1);break}}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r]){t.splice(r,1);break}}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length)for(let t of this._anyOutgoingListeners.slice())t.apply(this,e.data)}}function eZ(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}eZ.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=(1&Math.floor(10*t))==0?e-r:e+r}return 0|Math.min(e,this.max)},eZ.prototype.reset=function(){this.attempts=0},eZ.prototype.setMin=function(e){this.ms=e},eZ.prototype.setMax=function(e){this.max=e},eZ.prototype.setJitter=function(e){this.jitter=e};class eH extends R{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,z(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!=(r=t.randomizationFactor)?r:.5),this.backoff=new eZ({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||a;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null==(t=this.backoff)||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null==(t=this.backoff)||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null==(t=this.backoff)||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ew(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let n=eD(t,"open",function(){r.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=eD(t,"error",i);if(!1!==this._timeout){let e=this._timeout,r=this.setTimeoutFn(()=>{n(),i(Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(n),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(eD(e,"ping",this.onping.bind(this)),eD(e,"data",this.ondata.bind(this)),eD(e,"error",this.onerror.bind(this)),eD(e,"close",this.onclose.bind(this)),eD(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){$(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new eU(this,e,t),this.nsps[e]=r),r}_destroy(e){for(let e of Object.keys(this.nsps))if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null==(r=this.engine)||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{!e.skipReconnect&&(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}let eG={};function eW(e,t){let r;"object"==typeof e&&(t=e,e=void 0);let n=ex(e,(t=t||{}).path||"/socket.io"),i=n.source,o=n.id,a=n.path,s=eG[o]&&a in eG[o].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?r=new eH(i,t):(eG[o]||(eG[o]=new eH(i,t)),r=eG[o]),n.query&&!t.query&&(t.query=n.queryKey),r.socket(n.path,t)}Object.assign(eW,{Manager:eH,Socket:eU,io:eW,connect:eW})},43427:function(e,t,r){"use strict";let n;r.d(t,{ak:()=>eR,pA:()=>tE,z:()=>tC}),function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(let e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(tb||(tb={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t_||(t_={}));let i=tb.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":if(Array.isArray(e))return i.array;if(null===e)return i.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return i.promise;if("undefined"!=typeof Map&&e instanceof Map)return i.map;if("undefined"!=typeof Set&&e instanceof Set)return i.set;if("undefined"!=typeof Date&&e instanceof Date)return i.date;return i.object;default:return i.unknown}},a=tb.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"]),s=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class l extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){let r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof l))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,tb.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}l.create=e=>new l(e);let u=(e,t)=>{let r;switch(e.code){case a.invalid_type:r=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case a.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,tb.jsonStringifyReplacer)}`;break;case a.unrecognized_keys:r=`Unrecognized key(s) in object: ${tb.joinValues(e.keys,", ")}`;break;case a.invalid_union:r="Invalid input";break;case a.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${tb.joinValues(e.options)}`;break;case a.invalid_enum_value:r=`Invalid enum value. Expected ${tb.joinValues(e.options)}, received '${e.received}'`;break;case a.invalid_arguments:r="Invalid function arguments";break;case a.invalid_return_type:r="Invalid function return type";break;case a.invalid_date:r="Invalid date";break;case a.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(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}"`:tb.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case a.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case a.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case a.custom:r="Invalid input";break;case a.invalid_intersection_types:r="Intersection results could not be merged";break;case a.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case a.not_finite:r="Number must be finite";break;default:r=t.defaultError,tb.assertNever(e)}return{message:r}},c=u;function h(e){c=e}function f(){return c}let d=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(void 0!==i.message)return{...i,path:o,message:i.message};let s="";for(let e of n.filter(e=>!!e).slice().reverse())s=e(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}},p=[];function m(e,t){let r=f(),n=d({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===u?void 0:u].filter(e=>!!e)});e.common.issues.push(n)}class g{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if("aborted"===n.status)return y;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return g.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:t,value:i}=n;if("aborted"===t.status||"aborted"===i.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||n.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let y=Object.freeze({status:"aborted"}),v=e=>({status:"dirty",value:e}),b=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,w=e=>"dirty"===e.status,x=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;function E(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function C(e,t,r,n,i){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r}"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(tw||(tw={}));class A{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let k=(e,t)=>{if(x(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new l(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{var o,a;let{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:i.defaultError}:void 0===i.data?{message:null!=(o=null!=s?s:n)?o:i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:null!=(a=null!=s?s:r)?a:i.defaultError}},description:i}}class T{get description(){return this._def.description}_getType(e){return o(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new g,ctx:{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(S(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let n={common:{issues:[],async:null!=(r=null==t?void 0:t.async)&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},i=this._parseSync({data:e,path:n.path,parent:n});return k(n,i)}"~validate"(e){var t,r;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)};if(!this["~standard"].async)try{let t=this._parseSync({data:e,path:[],parent:n});return x(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null==(r=null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(e=>x(e)?{value:e.value}:{issues:n.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},n=this._parse({data:e,path:r.path,parent:r});return k(r,await (S(n)?n:Promise.resolve(n)))}refine(e,t){let r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{let i=e(t),o=()=>n.addIssue({code:a.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(o(),!1)):!!i||(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new eP({schema:this,typeName:tE.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eR.create(this,this._def)}nullable(){return eM.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ef.create(this)}promise(){return eI.create(this,this._def)}or(e){return em.create([this,e],this._def)}and(e){return eb.create(this,e,this._def)}transform(e){return new eP({...O(this._def),schema:this,typeName:tE.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t="function"==typeof e?e:()=>e;return new e$({...O(this._def),innerType:this,defaultValue:t,typeName:tE.ZodDefault})}brand(){return new eL({typeName:tE.ZodBranded,type:this,...O(this._def)})}catch(e){let t="function"==typeof e?e:()=>e;return new eN({...O(this._def),innerType:this,catchValue:t,typeName:tE.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eF.create(this,e)}readonly(){return eD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let I=/^c[^\s-]{8,}$/i,P=/^[0-9a-z]+$/,R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,M=/^[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,$=/^[a-z0-9_-]{21}$/i,N=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j=/^[-+]?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)?)??$/,B=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",F=/^(?:(?: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])$/,D=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,z=/^(([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]))$/,U=/^(([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])$/,Z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G="((\\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])))",W=RegExp(`^${G}$`);function q(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function V(e){return RegExp(`^${q(e)}$`)}function X(e){let t=`${G}T${q(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)}function Y(e,t){return!!(("v4"===t||!t)&&F.test(e)||("v6"===t||!t)&&z.test(e))}function K(e,t){if(!N.test(e))return!1;try{let[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));if("object"!=typeof i||null===i||!i.typ||!i.alg||t&&i.alg!==t)return!1;return!0}catch(e){return!1}}function J(e,t){return!!(("v4"===t||!t)&&D.test(e)||("v6"===t||!t)&&U.test(e))}class Q extends T{_parse(e){let t;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==i.string){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.string,received:t.parsedType}),y}let r=new g;for(let i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("max"===i.kind)e.data.length>i.value&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("length"===i.kind){let n=e.data.length>i.value,o=e.data.length<i.value;(n||o)&&(t=this._getOrReturnCtx(e,t),n?m(t,{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&m(t,{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if("email"===i.kind)B.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"email",code:a.invalid_string,message:i.message}),r.dirty());else if("emoji"===i.kind)n||(n=RegExp(L,"u")),n.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"emoji",code:a.invalid_string,message:i.message}),r.dirty());else if("uuid"===i.kind)M.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"uuid",code:a.invalid_string,message:i.message}),r.dirty());else if("nanoid"===i.kind)$.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"nanoid",code:a.invalid_string,message:i.message}),r.dirty());else if("cuid"===i.kind)I.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"cuid",code:a.invalid_string,message:i.message}),r.dirty());else if("cuid2"===i.kind)P.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"cuid2",code:a.invalid_string,message:i.message}),r.dirty());else if("ulid"===i.kind)R.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"ulid",code:a.invalid_string,message:i.message}),r.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(n){m(t=this._getOrReturnCtx(e,t),{validation:"url",code:a.invalid_string,message:i.message}),r.dirty()}else"regex"===i.kind?(i.regex.lastIndex=0,i.regex.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"regex",code:a.invalid_string,message:i.message}),r.dirty())):"trim"===i.kind?e.data=e.data.trim():"includes"===i.kind?e.data.includes(i.value,i.position)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):"toLowerCase"===i.kind?e.data=e.data.toLowerCase():"toUpperCase"===i.kind?e.data=e.data.toUpperCase():"startsWith"===i.kind?e.data.startsWith(i.value)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):"endsWith"===i.kind?e.data.endsWith(i.value)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):"datetime"===i.kind?X(i).test(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:"datetime",message:i.message}),r.dirty()):"date"===i.kind?W.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:"date",message:i.message}),r.dirty()):"time"===i.kind?V(i).test(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_string,validation:"time",message:i.message}),r.dirty()):"duration"===i.kind?j.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"duration",code:a.invalid_string,message:i.message}),r.dirty()):"ip"===i.kind?Y(e.data,i.version)||(m(t=this._getOrReturnCtx(e,t),{validation:"ip",code:a.invalid_string,message:i.message}),r.dirty()):"jwt"===i.kind?K(e.data,i.alg)||(m(t=this._getOrReturnCtx(e,t),{validation:"jwt",code:a.invalid_string,message:i.message}),r.dirty()):"cidr"===i.kind?J(e.data,i.version)||(m(t=this._getOrReturnCtx(e,t),{validation:"cidr",code:a.invalid_string,message:i.message}),r.dirty()):"base64"===i.kind?Z.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"base64",code:a.invalid_string,message:i.message}),r.dirty()):"base64url"===i.kind?H.test(e.data)||(m(t=this._getOrReturnCtx(e,t),{validation:"base64url",code:a.invalid_string,message:i.message}),r.dirty()):tb.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:a.invalid_string,...tw.errToObj(r)})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...tw.errToObj(e)})}url(e){return this._addCheck({kind:"url",...tw.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...tw.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...tw.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...tw.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...tw.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...tw.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...tw.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...tw.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...tw.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...tw.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...tw.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...tw.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!=(t=null==e?void 0:e.offset)&&t,local:null!=(r=null==e?void 0:e.local)&&r,...tw.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...tw.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...tw.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...tw.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...tw.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...tw.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...tw.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...tw.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...tw.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...tw.errToObj(t)})}nonempty(e){return this.min(1,tw.errToObj(e))}trim(){return new Q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function ee(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return parseInt(e.toFixed(i).replace(".",""))%parseInt(t.toFixed(i).replace(".",""))/Math.pow(10,i)}Q.create=e=>{var t;return new Q({checks:[],typeName:tE.ZodString,coerce:null!=(t=null==e?void 0:e.coerce)&&t,...O(e)})};class et extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==i.number){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.number,received:t.parsedType}),y}let r=new g;for(let n of this._def.checks)"int"===n.kind?tb.isInteger(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:a.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==ee(e.data,n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:a.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:a.not_finite,message:n.message}),r.dirty()):tb.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,tw.toString(t))}gt(e,t){return this.setLimit("min",e,!1,tw.toString(t))}lte(e,t){return this.setLimit("max",e,!0,tw.toString(t))}lt(e,t){return this.setLimit("max",e,!1,tw.toString(t))}setLimit(e,t,r,n){return new et({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:tw.toString(n)}]})}_addCheck(e){return new et({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:tw.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tw.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tw.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tw.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tw.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:tw.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:tw.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tw.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tw.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&tb.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}et.create=e=>new et({checks:[],typeName:tE.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class er extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==i.bigint)return this._getInvalidInput(e);let r=new g;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(m(t=this._getOrReturnCtx(e,t),{code:a.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):tb.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,tw.toString(t))}gt(e,t){return this.setLimit("min",e,!1,tw.toString(t))}lte(e,t){return this.setLimit("max",e,!0,tw.toString(t))}lt(e,t){return this.setLimit("max",e,!1,tw.toString(t))}setLimit(e,t,r,n){return new er({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:tw.toString(n)}]})}_addCheck(e){return new er({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:tw.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tw.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tw.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tw.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:tw.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}er.create=e=>{var t;return new er({checks:[],typeName:tE.ZodBigInt,coerce:null!=(t=null==e?void 0:e.coerce)&&t,...O(e)})};class en extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==i.boolean){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.boolean,received:t.parsedType}),y}return b(e.data)}}en.create=e=>new en({typeName:tE.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class ei extends T{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==i.date){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.date,received:t.parsedType}),y}if(isNaN(e.data.getTime()))return m(this._getOrReturnCtx(e),{code:a.invalid_date}),y;let r=new g;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(m(t=this._getOrReturnCtx(e,t),{code:a.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):tb.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ei({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:tw.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:tw.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ei.create=e=>new ei({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:tE.ZodDate,...O(e)});class eo extends T{_parse(e){if(this._getType(e)!==i.symbol){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.symbol,received:t.parsedType}),y}return b(e.data)}}eo.create=e=>new eo({typeName:tE.ZodSymbol,...O(e)});class ea extends T{_parse(e){if(this._getType(e)!==i.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.undefined,received:t.parsedType}),y}return b(e.data)}}ea.create=e=>new ea({typeName:tE.ZodUndefined,...O(e)});class es extends T{_parse(e){if(this._getType(e)!==i.null){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.null,received:t.parsedType}),y}return b(e.data)}}es.create=e=>new es({typeName:tE.ZodNull,...O(e)});class el extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return b(e.data)}}el.create=e=>new el({typeName:tE.ZodAny,...O(e)});class eu extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b(e.data)}}eu.create=e=>new eu({typeName:tE.ZodUnknown,...O(e)});class ec extends T{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.never,received:t.parsedType}),y}}ec.create=e=>new ec({typeName:tE.ZodNever,...O(e)});class eh extends T{_parse(e){if(this._getType(e)!==i.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.void,received:t.parsedType}),y}return b(e.data)}}eh.create=e=>new eh({typeName:tE.ZodVoid,...O(e)});class ef extends T{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==i.array)return m(t,{code:a.invalid_type,expected:i.array,received:t.parsedType}),y;if(null!==n.exactLength){let e=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;(e||i)&&(m(t,{code:e?a.too_big:a.too_small,minimum:i?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(m(t,{code:a.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(m(t,{code:a.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new A(t,e,t.path,r)))).then(e=>g.mergeArray(r,e));let o=[...t.data].map((e,r)=>n.type._parseSync(new A(t,e,t.path,r)));return g.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ef({...this._def,minLength:{value:e,message:tw.toString(t)}})}max(e,t){return new ef({...this._def,maxLength:{value:e,message:tw.toString(t)}})}length(e,t){return new ef({...this._def,exactLength:{value:e,message:tw.toString(t)}})}nonempty(e){return this.min(1,e)}}function ed(e){if(e instanceof ep){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=eR.create(ed(n))}return new ep({...e._def,shape:()=>t})}if(e instanceof ef)return new ef({...e._def,type:ed(e.element)});if(e instanceof eR)return eR.create(ed(e.unwrap()));if(e instanceof eM)return eM.create(ed(e.unwrap()));if(e instanceof e_)return e_.create(e.items.map(e=>ed(e)));else return e}ef.create=(e,t)=>new ef({type:e,minLength:null,maxLength:null,exactLength:null,typeName:tE.ZodArray,...O(t)});class ep extends T{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=tb.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==i.object){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.object,received:t.parsedType}),y}let{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ec&&"strip"===this._def.unknownKeys))for(let e in r.data)o.includes(e)||s.push(e);let l=[];for(let e of o){let t=n[e],i=r.data[e];l.push({key:{status:"valid",value:e},value:t._parse(new A(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ec){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of s)l.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(m(r,{code:a.unrecognized_keys,keys:s}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of s){let n=r.data[t];l.push({key:{status:"valid",value:t},value:e._parse(new A(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of l){let r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>g.mergeObjectSync(t,e)):g.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return tw.errToObj,new ep({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,i,o,a;let s=null!=(o=null==(i=(n=this._def).errorMap)?void 0:i.call(n,t,r).message)?o:r.defaultError;return"unrecognized_keys"===t.code?{message:null!=(a=tw.errToObj(e).message)?a:s}:{message:s}}}:{}})}strip(){return new ep({...this._def,unknownKeys:"strip"})}passthrough(){return new ep({...this._def,unknownKeys:"passthrough"})}extend(e){return new ep({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ep({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:tE.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ep({...this._def,catchall:e})}pick(e){let t={};return tb.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ep({...this._def,shape:()=>t})}omit(e){let t={};return tb.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ep({...this._def,shape:()=>t})}deepPartial(){return ed(this)}partial(e){let t={};return tb.objectKeys(this.shape).forEach(r=>{let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ep({...this._def,shape:()=>t})}required(e){let t={};return tb.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eR;)e=e._def.innerType;t[r]=e}}),new ep({...this._def,shape:()=>t})}keyof(){return ek(tb.objectKeys(this.shape))}}ep.create=(e,t)=>new ep({shape:()=>e,unknownKeys:"strip",catchall:ec.create(),typeName:tE.ZodObject,...O(t)}),ep.strictCreate=(e,t)=>new ep({shape:()=>e,unknownKeys:"strict",catchall:ec.create(),typeName:tE.ZodObject,...O(t)}),ep.lazycreate=(e,t)=>new ep({shape:e,unknownKeys:"strip",catchall:ec.create(),typeName:tE.ZodObject,...O(t)});class em extends T{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new l(e.ctx.common.issues));return m(t,{code:a.invalid_union,unionErrors:r}),y}if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(n);{let e,n=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=n.map(e=>new l(e));return m(t,{code:a.invalid_union,unionErrors:i}),y}}get options(){return this._def.options}}em.create=(e,t)=>new em({options:e,typeName:tE.ZodUnion,...O(t)});let eg=e=>{if(e instanceof eC)return eg(e.schema);if(e instanceof eP)return eg(e.innerType());if(e instanceof eA)return[e.value];if(e instanceof eO)return e.options;if(e instanceof eT)return tb.objectValues(e.enum);else if(e instanceof e$)return eg(e._def.innerType);else if(e instanceof ea)return[void 0];else if(e instanceof es)return[null];else if(e instanceof eR)return[void 0,...eg(e.unwrap())];else if(e instanceof eM)return[null,...eg(e.unwrap())];else if(e instanceof eL)return eg(e.unwrap());else if(e instanceof eD)return eg(e.unwrap());else if(e instanceof eN)return eg(e._def.innerType);else return[]};class ey extends T{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return m(t,{code:a.invalid_type,expected:i.object,received:t.parsedType}),y;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:a.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let r of t){let t=eg(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(n.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,r)}}return new ey({typeName:tE.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...O(r)})}}function ev(e,t){let r=o(e),n=o(t);if(e===t)return{valid:!0,data:e};if(r===i.object&&n===i.object){let r=tb.objectKeys(t),n=tb.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(let r of n){let n=ev(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===i.array&&n===i.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let n=0;n<e.length;n++){let i=ev(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}if(r===i.date&&n===i.date&&+e==+t)return{valid:!0,data:e};return{valid:!1}}class eb extends T{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(_(e)||_(n))return y;let i=ev(e.value,n.value);return i.valid?((w(e)||w(n))&&t.dirty(),{status:t.value,value:i.data}):(m(r,{code:a.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}eb.create=(e,t,r)=>new eb({left:e,right:t,typeName:tE.ZodIntersection,...O(r)});class e_ extends T{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return m(r,{code:a.invalid_type,expected:i.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return m(r,{code:a.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(m(r,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let n=[...r.data].map((e,t)=>{let n=this._def.items[t]||this._def.rest;return n?n._parse(new A(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>g.mergeArray(t,e)):g.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new e_({...this._def,rest:e})}}e_.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new e_({items:e,typeName:tE.ZodTuple,rest:null,...O(t)})};class ew extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return m(r,{code:a.invalid_type,expected:i.object,received:r.parsedType}),y;let n=[],o=this._def.keyType,s=this._def.valueType;for(let e in r.data)n.push({key:o._parse(new A(r,e,r.path,e)),value:s._parse(new A(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?g.mergeObjectAsync(t,n):g.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ew(t instanceof T?{keyType:e,valueType:t,typeName:tE.ZodRecord,...O(r)}:{keyType:Q.create(),valueType:e,typeName:tE.ZodRecord,...O(t)})}}class ex extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return m(r,{code:a.invalid_type,expected:i.map,received:r.parsedType}),y;let n=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new A(r,e,r.path,[i,"key"])),value:o._parse(new A(r,t,r.path,[i,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of s){let n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return y;("dirty"===n.status||"dirty"===i.status)&&t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of s){let n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return y;("dirty"===n.status||"dirty"===i.status)&&t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}ex.create=(e,t,r)=>new ex({valueType:t,keyType:e,typeName:tE.ZodMap,...O(r)});class eS extends T{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return m(r,{code:a.invalid_type,expected:i.set,received:r.parsedType}),y;let n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(m(r,{code:a.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(m(r,{code:a.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let o=this._def.valueType;function s(e){let r=new Set;for(let n of e){if("aborted"===n.status)return y;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}let l=[...r.data.values()].map((e,t)=>o._parse(new A(r,e,r.path,t)));return r.common.async?Promise.all(l).then(e=>s(e)):s(l)}min(e,t){return new eS({...this._def,minSize:{value:e,message:tw.toString(t)}})}max(e,t){return new eS({...this._def,maxSize:{value:e,message:tw.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}eS.create=(e,t)=>new eS({valueType:e,minSize:null,maxSize:null,typeName:tE.ZodSet,...O(t)});class eE extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.function)return m(t,{code:a.invalid_type,expected:i.function,received:t.parsedType}),y;function r(e,r){return d({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,f(),u].filter(e=>!!e),issueData:{code:a.invalid_arguments,argumentsError:r}})}function n(e,r){return d({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,f(),u].filter(e=>!!e),issueData:{code:a.invalid_return_type,returnTypeError:r}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof eI){let e=this;return b(async function(...t){let i=new l([]),a=await e._def.args.parseAsync(t,o).catch(e=>{throw i.addIssue(r(t,e)),i}),u=await Reflect.apply(s,this,a);return await e._def.returns._def.type.parseAsync(u,o).catch(e=>{throw i.addIssue(n(u,e)),i})})}{let e=this;return b(function(...t){let i=e._def.args.safeParse(t,o);if(!i.success)throw new l([r(t,i.error)]);let a=Reflect.apply(s,this,i.data),u=e._def.returns.safeParse(a,o);if(!u.success)throw new l([n(a,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new eE({...this._def,args:e_.create(e).rest(eu.create())})}returns(e){return new eE({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new eE({args:e||e_.create([]).rest(eu.create()),returns:t||eu.create(),typeName:tE.ZodFunction,...O(r)})}}class eC extends T{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}eC.create=(e,t)=>new eC({getter:e,typeName:tE.ZodLazy,...O(t)});class eA extends T{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:a.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ek(e,t){return new eO({values:e,typeName:tE.ZodEnum,...O(t)})}eA.create=(e,t)=>new eA({value:e,typeName:tE.ZodLiteral,...O(t)});class eO extends T{constructor(){super(...arguments),tx.set(this,void 0)}_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{expected:tb.joinValues(r),received:t.parsedType,code:a.invalid_type}),y}if(E(this,tx,"f")||C(this,tx,new Set(this._def.values),"f"),!E(this,tx,"f").has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{received:t.data,code:a.invalid_enum_value,options:r}),y}return b(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return eO.create(e,{...this._def,...t})}exclude(e,t=this._def){return eO.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}tx=new WeakMap,eO.create=ek;class eT extends T{constructor(){super(...arguments),tS.set(this,void 0)}_parse(e){let t=tb.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==i.string&&r.parsedType!==i.number){let e=tb.objectValues(t);return m(r,{expected:tb.joinValues(e),received:r.parsedType,code:a.invalid_type}),y}if(E(this,tS,"f")||C(this,tS,new Set(tb.getValidEnumValues(this._def.values)),"f"),!E(this,tS,"f").has(e.data)){let e=tb.objectValues(t);return m(r,{received:r.data,code:a.invalid_enum_value,options:e}),y}return b(e.data)}get enum(){return this._def.values}}tS=new WeakMap,eT.create=(e,t)=>new eT({values:e,typeName:tE.ZodNativeEnum,...O(t)});class eI extends T{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==i.promise&&!1===t.common.async?(m(t,{code:a.invalid_type,expected:i.promise,received:t.parsedType}),y):b((t.parsedType===i.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eI.create=(e,t)=>new eI({type:e,typeName:tE.ZodPromise,...O(t)});class eP extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===tE.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{m(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){let e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return y;let n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?v(n.value):n});{if("aborted"===t.value)return y;let n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?v(n.value):n}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?y:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}}if("transform"===n.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>x(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):e);else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!x(e))return e;let o=n.transform(e.value,i);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}tb.assertNever(n)}}eP.create=(e,t,r)=>new eP({schema:e,typeName:tE.ZodEffects,effect:t,...O(r)}),eP.createWithPreprocess=(e,t,r)=>new eP({schema:t,effect:{type:"preprocess",transform:e},typeName:tE.ZodEffects,...O(r)});class eR extends T{_parse(e){return this._getType(e)===i.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eR.create=(e,t)=>new eR({innerType:e,typeName:tE.ZodOptional,...O(t)});class eM extends T{_parse(e){return this._getType(e)===i.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eM.create=(e,t)=>new eM({innerType:e,typeName:tE.ZodNullable,...O(t)});class e$ extends T{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}e$.create=(e,t)=>new e$({innerType:e,typeName:tE.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...O(t)});class eN extends T{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return S(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new l(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new l(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}eN.create=(e,t)=>new eN({innerType:e,typeName:tE.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...O(t)});class ej extends T{_parse(e){if(this._getType(e)!==i.nan){let t=this._getOrReturnCtx(e);return m(t,{code:a.invalid_type,expected:i.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}ej.create=e=>new ej({typeName:tE.ZodNaN,...O(e)});let eB=Symbol("zod_brand");class eL extends T{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eF extends T{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),v(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eF({in:e,out:t,typeName:tE.ZodPipeline})}}class eD extends T{_parse(e){let t=this._def.innerType._parse(e),r=e=>(x(e)&&(e.value=Object.freeze(e.value)),e);return S(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function ez(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function eU(e,t={},r){return e?el.create().superRefine((n,i)=>{var o,a;let s=e(n);if(s instanceof Promise)return s.then(e=>{var o,a;if(!e){let e=ez(t,n),s=null==(a=null!=(o=e.fatal)?o:r)||a;i.addIssue({code:"custom",...e,fatal:s})}});if(!s){let e=ez(t,n),s=null==(a=null!=(o=e.fatal)?o:r)||a;i.addIssue({code:"custom",...e,fatal:s})}}):el.create()}eD.create=(e,t)=>new eD({innerType:e,typeName:tE.ZodReadonly,...O(t)});let eZ={object:ep.lazycreate};!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"}(tE||(tE={}));let eH=(e,t={message:`Input not instance of ${e.name}`})=>eU(t=>t instanceof e,t),eG=Q.create,eW=et.create,eq=ej.create,eV=er.create,eX=en.create,eY=ei.create,eK=eo.create,eJ=ea.create,eQ=es.create,e0=el.create,e1=eu.create,e2=ec.create,e3=eh.create,e5=ef.create,e4=ep.create,e6=ep.strictCreate,e8=em.create,e9=ey.create,e7=eb.create,te=e_.create,tt=ew.create,tr=ex.create,tn=eS.create,ti=eE.create,to=eC.create,ta=eA.create,ts=eO.create,tl=eT.create,tu=eI.create,tc=eP.create,th=eR.create,tf=eM.create,td=eP.createWithPreprocess,tp=eF.create,tm=()=>eW().optional(),tg=()=>eX().optional(),ty={string:e=>Q.create({...e,coerce:!0}),number:e=>et.create({...e,coerce:!0}),boolean:e=>en.create({...e,coerce:!0}),bigint:e=>er.create({...e,coerce:!0}),date:e=>ei.create({...e,coerce:!0})},tv=y;var tb,t_,tw,tx,tS,tE,tC=Object.freeze({__proto__:null,defaultErrorMap:u,setErrorMap:h,getErrorMap:f,makeIssue:d,EMPTY_PATH:p,addIssueToContext:m,ParseStatus:g,INVALID:y,DIRTY:v,OK:b,isAborted:_,isDirty:w,isValid:x,isAsync:S,get util(){return tb},get objectUtil(){return t_},ZodParsedType:i,getParsedType:o,ZodType:T,datetimeRegex:X,ZodString:Q,ZodNumber:et,ZodBigInt:er,ZodBoolean:en,ZodDate:ei,ZodSymbol:eo,ZodUndefined:ea,ZodNull:es,ZodAny:el,ZodUnknown:eu,ZodNever:ec,ZodVoid:eh,ZodArray:ef,ZodObject:ep,ZodUnion:em,ZodDiscriminatedUnion:ey,ZodIntersection:eb,ZodTuple:e_,ZodRecord:ew,ZodMap:ex,ZodSet:eS,ZodFunction:eE,ZodLazy:eC,ZodLiteral:eA,ZodEnum:eO,ZodNativeEnum:eT,ZodPromise:eI,ZodEffects:eP,ZodTransformer:eP,ZodOptional:eR,ZodNullable:eM,ZodDefault:e$,ZodCatch:eN,ZodNaN:ej,BRAND:eB,ZodBranded:eL,ZodPipeline:eF,ZodReadonly:eD,custom:eU,Schema:T,ZodSchema:T,late:eZ,get ZodFirstPartyTypeKind(){return tE},coerce:ty,any:e0,array:e5,bigint:eV,boolean:eX,date:eY,discriminatedUnion:e9,effect:tc,enum:ts,function:ti,instanceof:eH,intersection:e7,lazy:to,literal:ta,map:tr,nan:eq,nativeEnum:tl,never:e2,null:eQ,nullable:tf,number:eW,object:e4,oboolean:tg,onumber:tm,optional:th,ostring:()=>eG().optional(),pipeline:tp,preprocess:td,promise:tu,record:tt,set:tn,strictObject:e6,string:eG,symbol:eK,transformer:tc,tuple:te,undefined:eJ,union:e8,unknown:e1,void:e3,NEVER:tv,ZodIssueCode:a,quotelessJson:s,ZodError:l})},62858:function(e,t,r){"use strict";r.d(t,{Ue:()=>d});let n=e=>{let t,r=new Set,n=(e,n)=>{let i="function"==typeof e?e(t):e;if(!Object.is(i,t)){let e=t;t=(null!=n?n:"object"!=typeof i||null===i)?i:Object.assign({},t,i),r.forEach(r=>r(t,e))}},i=()=>t,o={setState:n,getState:i,getInitialState:()=>a,subscribe:e=>(r.add(e),()=>r.delete(e)),destroy:()=>{console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},a=t=e(n,i,o);return o},i=e=>e?n(e):n;var o=r(44194),a=r(67591);let{useDebugValue:s}=o,{useSyncExternalStoreWithSelector:l}=a,u=!1,c=e=>e;function h(e,t=c,r){r&&!u&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),u=!0);let n=l(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return s(n),n}let f=e=>{"function"!=typeof e&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");let t="function"==typeof e?i(e):e,r=(e,r)=>h(t,e,r);return Object.assign(r,t),r},d=e=>e?f(e):f}}]);
650
+ //# sourceMappingURL=806.8de50496.js.map