#!/usr/bin/env node "use strict";var e,t=require("util"),r=require("path"),n=require("fs"),i=require("assert"),a=require("url"),s=require("node:path"),o=require("ora"),u=require("chalk"),l=require("chalk-table"),c=require("fs/promises"),d=require("node:fs"),h=require("markdown-pdf"),p=require("pdf-lib"),f=require("@langchain/ollama"),m="undefined"!=typeof document?document.currentScript:null;Error;function g(){return process.versions.electron&&!process.defaultApp?0:1} /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ function y(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",r=!1;const n=e.match(/^-+/);for(let i=n?n[0].length:0;i0?`${t}${r.charAt(i)}`:s}return n}function v(e){return null!=e&&("number"==typeof e||(!!/^0x[0-9a-f]+$/i.test(e)||!/^0[^.]/.test(e)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)))} /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ let _;!function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(e||(e={}));function w(e){return void 0!==e?e+1:1}function D(e){return"__proto__"===e?"___proto___":e} /** * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js * CJS and ESM environments. * * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ var E,O,C;const x=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,k=null!==(O=null===(E=null===process||void 0===process?void 0:process.versions)||void 0===E?void 0:E.node)&&void 0!==O?O:null===(C=null===process||void 0===process?void 0:process.version)||void 0===C?void 0:C.slice(1);if(k){if(Number(k.match(/^([^.]+)/)[1])"string"!=typeof e?e+"":e));e=e.trim();let t=0,r=null,n=null,i=null;const a=[];for(let s=0;s{"number"==typeof t&&(g.nargs[e]=t,g.keys.push(e))})),"object"==typeof n.coerce&&Object.entries(n.coerce).forEach((([e,t])=>{"function"==typeof t&&(g.coercions[e]=t,g.keys.push(e))})),void 0!==n.config&&(Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach((function(e){g.configs[e]=!0})):"object"==typeof n.config&&Object.entries(n.config).forEach((([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(g.configs[e]=t)}))),function(...e){e.forEach((function(e){Object.keys(e||{}).forEach((function(e){g.aliases[e]||(g.aliases[e]=[].concat(s[e]||[]),g.aliases[e].concat(e).forEach((function(t){if(/-/.test(t)&&o["camel-case-expansion"]){const r=y(t);r!==e&&-1===g.aliases[e].indexOf(r)&&(g.aliases[e].push(r),p[r]=!0)}})),g.aliases[e].concat(e).forEach((function(t){if(t.length>1&&/[A-Z]/.test(t)&&o["camel-case-expansion"]){const r=b(t,"-");r!==e&&-1===g.aliases[e].indexOf(r)&&(g.aliases[e].push(r),p[r]=!0)}})),g.aliases[e].forEach((function(t){g.aliases[t]=[e].concat(g.aliases[e].filter((function(e){return t!==e})))})))}))}))}(n.key,s,n.default,g.arrays),Object.keys(u).forEach((function(e){(g.aliases[e]||[]).forEach((function(t){u[t]=u[e]}))}));let C=null;Object.keys(g.counts).find((e=>U(e,g.arrays)?(C=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!U(e,g.nargs)&&(C=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0)));let x=[];const k=Object.assign(Object.create(null),{_:[]}),j={};for(let e=0;e=3&&(U(u[1],g.arrays)?e=P(e,u[1],i,u[2]):!1!==U(u[1],g.nargs)?e=S(e,u[1],i,u[2]):I(u[1],u[2],!0));else if(t.match(O)&&o["boolean-negation"])u=t.match(O),null!==u&&Array.isArray(u)&&u.length>=2&&(a=u[1],I(a,!!U(a,g.arrays)&&[!1]));else if(t.match(/^--.+/)||!o["short-option-groups"]&&t.match(/^-[^-]+/))u=t.match(/^--?(.+)/),null!==u&&Array.isArray(u)&&u.length>=2&&(a=u[1],U(a,g.arrays)?e=P(e,a,i):!1!==U(a,g.nargs)?e=S(e,a,i):(l=i[e+1],void 0===l||l.match(/^-/)&&!l.match(E)||U(a,g.bools)||U(a,g.counts)?/^(true|false)$/.test(l)?(I(a,l),e++):I(a,H(a)):(I(a,l),e++)));else if(t.match(/^-.\..+=/))u=t.match(/^-([^=]+)=([\s\S]*)$/),null!==u&&Array.isArray(u)&&u.length>=3&&I(u[1],u[2]);else if(t.match(/^-.\..+/)&&!t.match(E))l=i[e+1],u=t.match(/^-(.\..+)/),null!==u&&Array.isArray(u)&&u.length>=2&&(a=u[1],void 0===l||l.match(/^-/)||U(a,g.bools)||U(a,g.counts)?I(a,H(a)):(I(a,l),e++));else if(t.match(/^-[^-]+/)&&!t.match(E)){s=t.slice(1,-1).split(""),n=!1;for(let r=0;r0&&(I(t,n),u--),i=e+1;i0||l&&"number"==typeof l&&i.length>=l)&&(s=r[n],!/^-/.test(s)||E.test(s)||Z(s));n++)e=n,i.push(F(t,s,a))}return"number"==typeof l&&(l&&i.length1&&o["dot-notation"]&&(g.aliases[i[0]]||[]).forEach((function(t){let r=t.split(".");const a=[].concat(i);a.shift(),r=r.concat(a),(g.aliases[e]||[]).includes(r.join("."))||B(k,r,n)})),U(e,g.normalize)&&!U(e,g.arrays)){[e].concat(g.aliases[e]||[]).forEach((function(e){Object.defineProperty(j,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?_.normalize(e):e}})}))}}function T(e,t){g.aliases[e]&&g.aliases[e].length||(g.aliases[e]=[t],p[t]=!0),g.aliases[t]&&g.aliases[t].length||T(t,e)}function F(e,t,r){r&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(U(e,g.bools)||U(e,g.counts))&&"string"==typeof t&&(t="true"===t);let n=Array.isArray(t)?t.map((function(t){return N(e,t)})):N(e,t);return U(e,g.counts)&&(V(n)||"boolean"==typeof n)&&(n=w()),U(e,g.normalize)&&U(e,g.arrays)&&(n=Array.isArray(t)?t.map((e=>_.normalize(e))):_.normalize(t)),n}function N(e,t){if(!o["parse-positional-numbers"]&&"_"===e)return t;if(!U(e,g.strings)&&!U(e,g.bools)&&!Array.isArray(t)){(v(t)&&o["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!V(t)&&U(e,g.numbers))&&(t=Number(t))}return t}function $(e,t){Object.keys(e).forEach((function(r){const n=e[r],i=t?t+"."+r:r;"object"==typeof n&&null!==n&&!Array.isArray(n)&&o["dot-notation"]?$(n,i):(!L(k,i.split("."))||U(i,g.arrays)&&o["combine-arrays"])&&I(i,n)}))}function R(e,t){if(void 0===c)return;const r="string"==typeof c?c:"",n=_.env();Object.keys(n).forEach((function(i){if(""===r||0===i.lastIndexOf(r,0)){const a=i.split("__").map((function(e,t){return 0===t&&(e=e.substring(r.length)),y(e)}));(t&&g.configs[a.join(".")]||!t)&&!L(e,a)&&I(a.join("."),n[i])}}))}function M(e,t,r,n=!1){Object.keys(r).forEach((function(i){L(e,i.split("."))||(B(e,i.split("."),r[i]),n&&(f[i]=!0),(t[i]||[]).forEach((function(t){L(e,t.split("."))||B(e,t.split("."),r[i])})))}))}function L(e,t){let r=e;o["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){r=r[e]||{}}));const n=t[t.length-1];return"object"==typeof r&&n in r}function B(e,t,r){let n=e;o["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){e=D(e),"object"==typeof n&&void 0===n[e]&&(n[e]={}),"object"!=typeof n[e]||Array.isArray(n[e])?(Array.isArray(n[e])?n[e].push({}):n[e]=[n[e],{}],n=n[e][n[e].length-1]):n=n[e]}));const i=D(t[t.length-1]),a=U(t.join("."),g.arrays),s=Array.isArray(r);let u=o["duplicate-arguments-array"];!u&&U(i,g.nargs)&&(u=!0,(!V(n[i])&&1===g.nargs[i]||Array.isArray(n[i])&&n[i].length===g.nargs[i])&&(n[i]=void 0)),r===w()?n[i]=w(n[i]):Array.isArray(n[i])?u&&a&&s?n[i]=o["flatten-duplicate-arrays"]?n[i].concat(r):(Array.isArray(n[i][0])?n[i]:[n[i]]).concat([r]):u||Boolean(a)!==Boolean(s)?n[i]=n[i].concat([r]):n[i]=r:void 0===n[i]&&a?n[i]=s?r:[r]:!u||void 0===n[i]||U(i,g.counts)||U(i,g.bools)?n[i]=r:n[i]=[n[i],r]}function U(e,t){const r=[].concat(g.aliases[e]||[],e),n=Object.keys(t),i=r.find((e=>n.includes(e)));return!!i&&t[i]}function z(e){const t=Object.keys(g);return[].concat(t.map((e=>g[e]))).some((function(t){return Array.isArray(t)?t.includes(e):t[e]}))}function Z(e){return o["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(E))return!1;if(function(e){if(e.match(E)||!e.match(/^-[^-]+/))return!1;let t,r=!0;const n=e.slice(1).split("");for(let i=0;i{r.add(t),e[t]=i}))}catch(e){C=e}}))}(k),o["set-placeholder-key"]&&function(e){g.keys.forEach((t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)}))}(k),Object.keys(g.counts).forEach((function(e){L(k,e.split("."))||I(e,0)})),d&&x.length&&(k[h]=[]),x.forEach((function(e){k[h].push(e)})),o["camel-case-expansion"]&&o["strip-dashed"]&&Object.keys(k).filter((e=>"--"!==e&&e.includes("-"))).forEach((e=>{delete k[e]})),o["strip-aliased"]&&[].concat(...Object.keys(s).map((e=>s[e]))).forEach((e=>{o["camel-case-expansion"]&&e.includes("-")&&delete k[e.split(".").map((e=>y(e))).join(".")],delete k[e]})),{aliases:Object.assign({},g.aliases),argv:Object.assign(j,k),configuration:o,defaulted:Object.assign({},f),error:C,newAliases:Object.assign({},p)}}}({cwd:process.cwd,env:()=>j,format:t.format,normalize:r.normalize,resolve:r.resolve,require:e=>{if("undefined"!=typeof require)return require(e);if(e.match(/\.json$/))return JSON.parse(n.readFileSync(e,"utf8"));throw Error("only .json config files are supported in ESM")}}),S=function(e,t){return A.parse(e.slice(),t).argv};S.detailed=function(e,t){return A.parse(e.slice(),t)},S.camelCase=y,S.decamelize=b,S.looksLikeNumber=v;new RegExp("(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");var P={fs:{readFileSync:n.readFileSync,writeFile:n.writeFile},format:t.format,resolve:r.resolve,exists:e=>{try{return n.statSync(e).isFile()}catch(e){return!1}}};let I;class T{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let r=function(){};return"function"==typeof e[e.length-1]&&(r=e.pop()),r=r||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r})):r(),I.format.apply(I.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),r=e.shift(),n=e.shift();let i=function(){};"function"==typeof e[e.length-1]&&(i=e.pop()),this.cache[this.locale]||this._readLocaleFile();let a=1===n?t:r;if(this.cache[this.locale][t]){a=this.cache[this.locale][t][1===n?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:r},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:i})):i();const s=[a];return~a.indexOf("%d")&&s.push(n),I.format.apply(I.format,s.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let r="";return e.forEach((function(e,n){const i=t[n+1];r+=e,void 0!==i&&(r+="%s")})),this.__.apply(this,[r].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],r=t.directory,n=t.locale,i=t.cb,a=this._resolveLocaleFile(r,n),s=JSON.stringify(this.cache[n],null,2);I.fs.writeFile(a,s,"utf-8",(function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),i(t)}))}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{I.fs.readFileSync&&(e=JSON.parse(I.fs.readFileSync(t,"utf-8")))}catch(r){if(r instanceof SyntaxError&&(r.message="syntax error in "+t),"ENOENT"!==r.code)throw r;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let r=I.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(r)&&~t.lastIndexOf("_")){const n=I.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(n)&&(r=n)}return r}_fileExistsSync(e){return I.exists(e)}}let F;try{F=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href)}catch(e){F=process.cwd()}const N=F.substring(0,F.lastIndexOf("node_modules"));var $,R,M,L;function B(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function U(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}function z(){if(R)return $;R=1;var e=n,i=t,a=r;let s;class o{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let r=function(){};return"function"==typeof e[e.length-1]&&(r=e.pop()),r=r||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r})):r(),s.format.apply(s.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),r=e.shift(),n=e.shift();let i=function(){};"function"==typeof e[e.length-1]&&(i=e.pop()),this.cache[this.locale]||this._readLocaleFile();let a=1===n?t:r;if(this.cache[this.locale][t]){a=this.cache[this.locale][t][1===n?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:r},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:i})):i();const o=[a];return~a.indexOf("%d")&&o.push(n),s.format.apply(s.format,o.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let r="";return e.forEach((function(e,n){const i=t[n+1];r+=e,void 0!==i&&(r+="%s")})),this.__.apply(this,[r].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],r=t.directory,n=t.locale,i=t.cb,a=this._resolveLocaleFile(r,n),o=JSON.stringify(this.cache[n],null,2);s.fs.writeFile(a,o,"utf-8",(function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),i(t)}))}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{s.fs.readFileSync&&(e=JSON.parse(s.fs.readFileSync(t,"utf-8")))}catch(r){if(r instanceof SyntaxError&&(r.message="syntax error in "+t),"ENOENT"!==r.code)throw r;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let r=s.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(r)&&~t.lastIndexOf("_")){const n=s.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(n)&&(r=n)}return r}_fileExistsSync(e){return s.exists(e)}}var u={fs:{readFileSync:e.readFileSync,writeFile:e.writeFile},format:i.format,resolve:a.resolve,exists:t=>{try{return e.statSync(t).isFile()}catch(e){return!1}}};return $=e=>function(e,t){s=t;const r=new o(e);return{__:r.__.bind(r),__n:r.__n.bind(r),setLocale:r.setLocale.bind(r),getLocale:r.getLocale.bind(r),updateLocale:r.updateLocale.bind(r),locale:r.locale}}(e,u),$}function Z(){if(L)return M;L=1;var e,i=t,a=r,s=n;function o(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",r=!1;const n=e.match(/^-+/);for(let i=n?n[0].length:0;i0?`${t}${r.charAt(i)}`:s}return n}function l(e){return null!=e&&("number"==typeof e||(!!/^0x[0-9a-f]+$/i.test(e)||!/^0[^.]/.test(e)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)))}let c;!function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(e||(e={}));function d(e){return void 0!==e?e+1:1}function h(e){return"__proto__"===e?"___proto___":e}var p,f,m;const g=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,y=null!==(f=null===(p=null===process||void 0===process?void 0:process.versions)||void 0===p?void 0:p.node)&&void 0!==f?f:null===(m=null===process||void 0===process?void 0:process.version)||void 0===m?void 0:m.slice(1);if(y){if(Number(y.match(/^([^.]+)/)[1])"string"!=typeof e?e+"":e));e=e.trim();let t=0,r=null,n=null,i=null;const a=[];for(let s=0;s{"number"==typeof t&&(D.nargs[e]=t,D.keys.push(e))})),"object"==typeof n.coerce&&Object.entries(n.coerce).forEach((([e,t])=>{"function"==typeof t&&(D.coercions[e]=t,D.keys.push(e))})),void 0!==n.config&&(Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach((function(e){D.configs[e]=!0})):"object"==typeof n.config&&Object.entries(n.config).forEach((([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(D.configs[e]=t)}))),function(...e){e.forEach((function(e){Object.keys(e||{}).forEach((function(e){D.aliases[e]||(D.aliases[e]=[].concat(s[e]||[]),D.aliases[e].concat(e).forEach((function(t){if(/-/.test(t)&&p["camel-case-expansion"]){const r=o(t);r!==e&&-1===D.aliases[e].indexOf(r)&&(D.aliases[e].push(r),v[r]=!0)}})),D.aliases[e].concat(e).forEach((function(t){if(t.length>1&&/[A-Z]/.test(t)&&p["camel-case-expansion"]){const r=u(t,"-");r!==e&&-1===D.aliases[e].indexOf(r)&&(D.aliases[e].push(r),v[r]=!0)}})),D.aliases[e].forEach((function(t){D.aliases[t]=[e].concat(D.aliases[e].filter((function(e){return t!==e})))})))}))}))}(n.key,s,n.default,D.arrays),Object.keys(f).forEach((function(e){(D.aliases[e]||[]).forEach((function(t){f[t]=f[e]}))}));let C=null;Object.keys(D.counts).find((e=>U(e,D.arrays)?(C=Error(w("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!U(e,D.nargs)&&(C=Error(w("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0)));let x=[];const k=Object.assign(Object.create(null),{_:[]}),j={};for(let e=0;e=3&&(U(o[1],D.arrays)?e=P(e,o[1],i,o[2]):!1!==U(o[1],D.nargs)?e=S(e,o[1],i,o[2]):I(o[1],o[2],!0));else if(t.match(O)&&p["boolean-negation"])o=t.match(O),null!==o&&Array.isArray(o)&&o.length>=2&&(a=o[1],I(a,!!U(a,D.arrays)&&[!1]));else if(t.match(/^--.+/)||!p["short-option-groups"]&&t.match(/^-[^-]+/))o=t.match(/^--?(.+)/),null!==o&&Array.isArray(o)&&o.length>=2&&(a=o[1],U(a,D.arrays)?e=P(e,a,i):!1!==U(a,D.nargs)?e=S(e,a,i):(u=i[e+1],void 0===u||u.match(/^-/)&&!u.match(E)||U(a,D.bools)||U(a,D.counts)?/^(true|false)$/.test(u)?(I(a,u),e++):I(a,H(a)):(I(a,u),e++)));else if(t.match(/^-.\..+=/))o=t.match(/^-([^=]+)=([\s\S]*)$/),null!==o&&Array.isArray(o)&&o.length>=3&&I(o[1],o[2]);else if(t.match(/^-.\..+/)&&!t.match(E))u=i[e+1],o=t.match(/^-(.\..+)/),null!==o&&Array.isArray(o)&&o.length>=2&&(a=o[1],void 0===u||u.match(/^-/)||U(a,D.bools)||U(a,D.counts)?I(a,H(a)):(I(a,u),e++));else if(t.match(/^-[^-]+/)&&!t.match(E)){s=t.slice(1,-1).split(""),n=!1;for(let r=0;r0&&(I(t,n),o--),i=e+1;i0||o&&"number"==typeof o&&i.length>=o)&&(s=r[n],!/^-/.test(s)||E.test(s)||Z(s));n++)e=n,i.push(F(t,s,a))}return"number"==typeof o&&(o&&i.length1&&p["dot-notation"]&&(D.aliases[i[0]]||[]).forEach((function(t){let r=t.split(".");const a=[].concat(i);a.shift(),r=r.concat(a),(D.aliases[e]||[]).includes(r.join("."))||B(k,r,n)})),U(e,D.normalize)&&!U(e,D.arrays)){[e].concat(D.aliases[e]||[]).forEach((function(e){Object.defineProperty(j,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?c.normalize(e):e}})}))}}function T(e,t){D.aliases[e]&&D.aliases[e].length||(D.aliases[e]=[t],v[t]=!0),D.aliases[t]&&D.aliases[t].length||T(t,e)}function F(e,t,r){r&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(U(e,D.bools)||U(e,D.counts))&&"string"==typeof t&&(t="true"===t);let n=Array.isArray(t)?t.map((function(t){return N(e,t)})):N(e,t);return U(e,D.counts)&&(V(n)||"boolean"==typeof n)&&(n=d()),U(e,D.normalize)&&U(e,D.arrays)&&(n=Array.isArray(t)?t.map((e=>c.normalize(e))):c.normalize(t)),n}function N(e,t){if(!p["parse-positional-numbers"]&&"_"===e)return t;if(!U(e,D.strings)&&!U(e,D.bools)&&!Array.isArray(t)){(l(t)&&p["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!V(t)&&U(e,D.numbers))&&(t=Number(t))}return t}function $(e,t){Object.keys(e).forEach((function(r){const n=e[r],i=t?t+"."+r:r;"object"==typeof n&&null!==n&&!Array.isArray(n)&&p["dot-notation"]?$(n,i):(!L(k,i.split("."))||U(i,D.arrays)&&p["combine-arrays"])&&I(i,n)}))}function R(e,t){if(void 0===g)return;const r="string"==typeof g?g:"",n=c.env();Object.keys(n).forEach((function(i){if(""===r||0===i.lastIndexOf(r,0)){const a=i.split("__").map((function(e,t){return 0===t&&(e=e.substring(r.length)),o(e)}));(t&&D.configs[a.join(".")]||!t)&&!L(e,a)&&I(a.join("."),n[i])}}))}function M(e,t,r,n=!1){Object.keys(r).forEach((function(i){L(e,i.split("."))||(B(e,i.split("."),r[i]),n&&(_[i]=!0),(t[i]||[]).forEach((function(t){L(e,t.split("."))||B(e,t.split("."),r[i])})))}))}function L(e,t){let r=e;p["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){r=r[e]||{}}));const n=t[t.length-1];return"object"==typeof r&&n in r}function B(e,t,r){let n=e;p["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){e=h(e),"object"==typeof n&&void 0===n[e]&&(n[e]={}),"object"!=typeof n[e]||Array.isArray(n[e])?(Array.isArray(n[e])?n[e].push({}):n[e]=[n[e],{}],n=n[e][n[e].length-1]):n=n[e]}));const i=h(t[t.length-1]),a=U(t.join("."),D.arrays),s=Array.isArray(r);let o=p["duplicate-arguments-array"];!o&&U(i,D.nargs)&&(o=!0,(!V(n[i])&&1===D.nargs[i]||Array.isArray(n[i])&&n[i].length===D.nargs[i])&&(n[i]=void 0)),r===d()?n[i]=d(n[i]):Array.isArray(n[i])?o&&a&&s?n[i]=p["flatten-duplicate-arrays"]?n[i].concat(r):(Array.isArray(n[i][0])?n[i]:[n[i]]).concat([r]):o||Boolean(a)!==Boolean(s)?n[i]=n[i].concat([r]):n[i]=r:void 0===n[i]&&a?n[i]=s?r:[r]:!o||void 0===n[i]||U(i,D.counts)||U(i,D.bools)?n[i]=r:n[i]=[n[i],r]}function U(e,t){const r=[].concat(D.aliases[e]||[],e),n=Object.keys(t),i=r.find((e=>n.includes(e)));return!!i&&t[i]}function z(e){const t=Object.keys(D);return[].concat(t.map((e=>D[e]))).some((function(t){return Array.isArray(t)?t.includes(e):t[e]}))}function Z(e){return p["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(E))return!1;if(function(e){if(e.match(E)||!e.match(/^-[^-]+/))return!1;let t,r=!0;const n=e.slice(1).split("");for(let i=0;i{r.add(t),e[t]=i}))}catch(e){C=e}}))}(k),p["set-placeholder-key"]&&function(e){D.keys.forEach((t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)}))}(k),Object.keys(D.counts).forEach((function(e){L(k,e.split("."))||I(e,0)})),y&&x.length&&(k[b]=[]),x.forEach((function(e){k[b].push(e)})),p["camel-case-expansion"]&&p["strip-dashed"]&&Object.keys(k).filter((e=>"--"!==e&&e.includes("-"))).forEach((e=>{delete k[e]})),p["strip-aliased"]&&[].concat(...Object.keys(s).map((e=>s[e]))).forEach((e=>{p["camel-case-expansion"]&&e.includes("-")&&delete k[e.split(".").map((e=>o(e))).join(".")],delete k[e]})),{aliases:Object.assign({},D.aliases),argv:Object.assign(j,k),configuration:p,defaulted:Object.assign({},_),error:C,newAliases:Object.assign({},v)}}}({cwd:process.cwd,env:()=>b,format:i.format,normalize:a.normalize,resolve:a.resolve,require:e=>{if(void 0!==U)return U(e);if(e.match(/\.json$/))return JSON.parse(s.readFileSync(e,"utf8"));throw Error("only .json config files are supported in ESM")}}),_=function(e,t){return v.parse(e.slice(),t).argv};return _.detailed=function(e,t){return v.parse(e.slice(),t)},_.camelCase=o,_.decamelize=u,_.looksLikeNumber=l,M=_}i.notStrictEqual,i.strictEqual,t.inspect,N||process.cwd(),r.basename,r.dirname,r.extname,r.relative,r.resolve,process.cwd,process.exit,process.nextTick,void 0!==process.stdout.columns&&process.stdout.columns,n.readFileSync,function(e,t){I=t;const r=new T(e);r.__.bind(r),r.__n.bind(r),r.setLocale.bind(r),r.getLocale.bind(r),r.updateLocale.bind(r),r.locale}({directory:r.resolve(F,"../../../locales"),updateFiles:!1},P);var H,V,q,W,G={exports:{}};function J(){return V?H:(V=1,H=({onlyFirst:e=!1}={})=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")})}function K(){if(W)return q;W=1;const e=J();return q=t=>"string"==typeof t?t.replace(e(),""):t}var Y,X,Q,ee,te={exports:{}};function re(){if(Y)return te.exports;Y=1;const e=e=>!Number.isNaN(e)&&(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&12351!==e||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141));return te.exports=e,te.exports.default=e,te.exports}function ne(){if(ee)return G.exports;ee=1;const e=K(),t=re(),r=Q?X:(Q=1,X=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}),n=n=>{if("string"!=typeof n||0===n.length)return 0;if(0===(n=e(n)).length)return 0;n=n.replace(r()," ");let i=0;for(let e=0;e=127&&r<=159||(r>=768&&r<=879||(r>65535&&e++,i+=t(r)?2:1))}return i};return G.exports=n,G.exports.default=n,G.exports}var ie,ae,se,oe,ue,le,ce,de,he,pe,fe,me,ge,ye,be,ve,_e,we={exports:{}};function De(){if(oe)return se;oe=1;const e=ae?ie:(ae=1,ie={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(const r of Object.keys(e))t[e[r]]=r;const r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};se=r;for(const e of Object.keys(r)){if(!("channels"in r[e]))throw new Error("missing channels property: "+e);if(!("labels"in r[e]))throw new Error("missing channel labels property: "+e);if(r[e].labels.length!==r[e].channels)throw new Error("channel and label counts mismatch: "+e);const{channels:t,labels:n}=r[e];delete r[e].channels,delete r[e].labels,Object.defineProperty(r[e],"channels",{value:t}),Object.defineProperty(r[e],"labels",{value:n})}return r.rgb.hsl=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,i=Math.min(t,r,n),a=Math.max(t,r,n),s=a-i;let o,u;a===i?o=0:t===a?o=(r-n)/s:r===a?o=2+(n-t)/s:n===a&&(o=4+(t-r)/s),o=Math.min(60*o,360),o<0&&(o+=360);const l=(i+a)/2;return u=a===i?0:l<=.5?s/(a+i):s/(2-a-i),[o,100*u,100*l]},r.rgb.hsv=function(e){let t,r,n,i,a;const s=e[0]/255,o=e[1]/255,u=e[2]/255,l=Math.max(s,o,u),c=l-Math.min(s,o,u),d=function(e){return(l-e)/6/c+.5};return 0===c?(i=0,a=0):(a=c/l,t=d(s),r=d(o),n=d(u),s===l?i=n-r:o===l?i=1/3+t-n:u===l&&(i=2/3+r-t),i<0?i+=1:i>1&&(i-=1)),[360*i,100*a,100*l]},r.rgb.hwb=function(e){const t=e[0],n=e[1];let i=e[2];const a=r.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(n,i));return i=1-1/255*Math.max(t,Math.max(n,i)),[a,100*s,100*i]},r.rgb.cmyk=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,i=Math.min(1-t,1-r,1-n);return[100*((1-t-i)/(1-i)||0),100*((1-r-i)/(1-i)||0),100*((1-n-i)/(1-i)||0),100*i]},r.rgb.keyword=function(r){const n=t[r];if(n)return n;let i,a=1/0;for(const t of Object.keys(e)){const n=e[t],u=(o=n,((s=r)[0]-o[0])**2+(s[1]-o[1])**2+(s[2]-o[2])**2);u.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;return[100*(.4124*t+.3576*r+.1805*n),100*(.2126*t+.7152*r+.0722*n),100*(.0193*t+.1192*r+.9505*n)]},r.rgb.lab=function(e){const t=r.rgb.xyz(e);let n=t[0],i=t[1],a=t[2];n/=95.047,i/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,i=i>.008856?i**(1/3):7.787*i+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;return[116*i-16,500*(n-i),200*(i-a)]},r.hsl.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;let i,a,s;if(0===r)return s=255*n,[s,s,s];i=n<.5?n*(1+r):n+r-n*r;const o=2*n-i,u=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,s=6*a<1?o+6*(i-o)*a:2*a<1?i:3*a<2?o+(i-o)*(2/3-a)*6:o,u[e]=255*s;return u},r.hsl.hsv=function(e){const t=e[0];let r=e[1]/100,n=e[2]/100,i=r;const a=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,i*=a<=1?a:2-a;return[t,100*(0===n?2*i/(a+i):2*r/(n+r)),100*((n+r)/2)]},r.hsv.rgb=function(e){const t=e[0]/60,r=e[1]/100;let n=e[2]/100;const i=Math.floor(t)%6,a=t-Math.floor(t),s=255*n*(1-r),o=255*n*(1-r*a),u=255*n*(1-r*(1-a));switch(n*=255,i){case 0:return[n,u,s];case 1:return[o,n,s];case 2:return[s,n,u];case 3:return[s,o,n];case 4:return[u,s,n];case 5:return[n,s,o]}},r.hsv.hsl=function(e){const t=e[0],r=e[1]/100,n=e[2]/100,i=Math.max(n,.01);let a,s;s=(2-r)*n;const o=(2-r)*i;return a=r*i,a/=o<=1?o:2-o,a=a||0,s/=2,[t,100*a,100*s]},r.hwb.rgb=function(e){const t=e[0]/360;let r=e[1]/100,n=e[2]/100;const i=r+n;let a;i>1&&(r/=i,n/=i);const s=Math.floor(6*t),o=1-n;a=6*t-s,1&s&&(a=1-a);const u=r+a*(o-r);let l,c,d;switch(s){default:case 6:case 0:l=o,c=u,d=r;break;case 1:l=u,c=o,d=r;break;case 2:l=r,c=o,d=u;break;case 3:l=r,c=u,d=o;break;case 4:l=u,c=r,d=o;break;case 5:l=o,c=r,d=u}return[255*l,255*c,255*d]},r.cmyk.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100,i=e[3]/100;return[255*(1-Math.min(1,t*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i))]},r.xyz.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100;let i,a,s;return i=3.2406*t+-1.5372*r+-.4986*n,a=-.9689*t+1.8758*r+.0415*n,s=.0557*t+-.204*r+1.057*n,i=i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,a=a>.0031308?1.055*a**(1/2.4)-.055:12.92*a,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),s=Math.min(Math.max(0,s),1),[255*i,255*a,255*s]},r.xyz.lab=function(e){let t=e[0],r=e[1],n=e[2];t/=95.047,r/=100,n/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;return[116*r-16,500*(t-r),200*(r-n)]},r.lab.xyz=function(e){let t,r,n;r=(e[0]+16)/116,t=e[1]/500+r,n=r-e[2]/200;const i=r**3,a=t**3,s=n**3;return r=i>.008856?i:(r-16/116)/7.787,t=a>.008856?a:(t-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,t*=95.047,r*=100,n*=108.883,[t,r,n]},r.lab.lch=function(e){const t=e[0],r=e[1],n=e[2];let i;i=360*Math.atan2(n,r)/2/Math.PI,i<0&&(i+=360);return[t,Math.sqrt(r*r+n*n),i]},r.lch.lab=function(e){const t=e[0],r=e[1],n=e[2]/360*2*Math.PI;return[t,r*Math.cos(n),r*Math.sin(n)]},r.rgb.ansi16=function(e,t=null){const[n,i,a]=e;let s=null===t?r.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),0===s)return 30;let o=30+(Math.round(a/255)<<2|Math.round(i/255)<<1|Math.round(n/255));return 2===s&&(o+=60),o},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){const t=e[0],r=e[1],n=e[2];if(t===r&&r===n)return t<8?16:t>248?231:Math.round((t-8)/247*24)+232;return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},r.ansi16.rgb=function(e){let t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];const r=.5*(1+~~(e>50));return[(1&t)*r*255,(t>>1&1)*r*255,(t>>2&1)*r*255]},r.ansi256.rgb=function(e){if(e>=232){const t=10*(e-232)+8;return[t,t,t]}let t;e-=16;return[Math.floor(e/36)/5*255,Math.floor((t=e%36)/6)/5*255,t%6/5*255]},r.rgb.hex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){const t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];3===t[0].length&&(r=r.split("").map((e=>e+e)).join(""));const n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},r.rgb.hcg=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,i=Math.max(Math.max(t,r),n),a=Math.min(Math.min(t,r),n),s=i-a;let o,u;return o=s<1?a/(1-s):0,u=s<=0?0:i===t?(r-n)/s%6:i===r?2+(n-t)/s:4+(t-r)/s,u/=6,u%=1,[360*u,100*s,100*o]},r.hsl.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=r<.5?2*t*r:2*t*(1-r);let i=0;return n<1&&(i=(r-.5*n)/(1-n)),[e[0],100*n,100*i]},r.hsv.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=t*r;let i=0;return n<1&&(i=(r-n)/(1-n)),[e[0],100*n,100*i]},r.hcg.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;if(0===r)return[255*n,255*n,255*n];const i=[0,0,0],a=t%1*6,s=a%1,o=1-s;let u=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=s,i[2]=0;break;case 1:i[0]=o,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=s;break;case 3:i[0]=0,i[1]=o,i[2]=1;break;case 4:i[0]=s,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=o}return u=(1-r)*n,[255*(r*i[0]+u),255*(r*i[1]+u),255*(r*i[2]+u)]},r.hcg.hsv=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);let n=0;return r>0&&(n=t/r),[e[0],100*n,100*r]},r.hcg.hsl=function(e){const t=e[1]/100,r=e[2]/100*(1-t)+.5*t;let n=0;return r>0&&r<.5?n=t/(2*r):r>=.5&&r<1&&(n=t/(2*(1-r))),[e[0],100*n,100*r]},r.hcg.hwb=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);return[e[0],100*(r-t),100*(1-r)]},r.hwb.hcg=function(e){const t=e[1]/100,r=1-e[2]/100,n=r-t;let i=0;return n<1&&(i=(r-n)/(1-n)),[e[0],100*n,100*i]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=function(e){return[0,0,e[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){const t=255&Math.round(e[0]/100*255),r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},se}function Ee(){if(le)return ue;le=1;const e=De();function t(t){const r=function(){const t={},r=Object.keys(e);for(let e=r.length,n=0;n{r[n]={},Object.defineProperty(r[n],"channels",{value:e[n].channels}),Object.defineProperty(r[n],"labels",{value:e[n].labels});const i=t(n);Object.keys(i).forEach((e=>{const t=i[e];r[n][e]=function(e){const t=function(...t){const r=t[0];if(null==r)return r;r.length>1&&(t=r);const n=e(t);if("object"==typeof n)for(let e=n.length,t=0;t1&&(t=r),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)}))})),ce=r}function Ce(){if(fe)return pe;fe=1;const e=ne(),t=K(),r=(he||(he=1,function(e){const t=(e,t)=>(...r)=>`[${e(...r)+t}m`,r=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};5;${n}m`},n=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};2;${n[0]};${n[1]};${n[2]}m`},i=e=>e,a=(e,t,r)=>[e,t,r],s=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{const n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})};let o;const u=(e,t,r,n)=>{void 0===o&&(o=Oe());const i=n?10:0,a={};for(const[n,s]of Object.entries(o)){const o="ansi16"===n?"ansi":n;n===t?a[o]=e(r,i):"object"==typeof s&&(a[o]=e(s[t],i))}return a};Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,o={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],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]}};o.color.gray=o.color.blackBright,o.bgColor.bgGray=o.bgColor.bgBlackBright,o.color.grey=o.color.blackBright,o.bgColor.bgGrey=o.bgColor.bgBlackBright;for(const[t,r]of Object.entries(o)){for(const[t,n]of Object.entries(r))o[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=o[t],e.set(n[0],n[1]);Object.defineProperty(o,t,{value:r,enumerable:!1})}return Object.defineProperty(o,"codes",{value:e,enumerable:!1}),o.color.close="",o.bgColor.close="",s(o.color,"ansi",(()=>u(t,"ansi16",i,!1))),s(o.color,"ansi256",(()=>u(r,"ansi256",i,!1))),s(o.color,"ansi16m",(()=>u(n,"rgb",a,!1))),s(o.bgColor,"ansi",(()=>u(t,"ansi16",i,!0))),s(o.bgColor,"ansi256",(()=>u(r,"ansi256",i,!0))),s(o.bgColor,"ansi16m",(()=>u(n,"rgb",a,!0))),o}})}(we)),we.exports),n=new Set(["","›"]),i="]8;;",a=e=>`${n.values().next().value}[${e}m`,s=e=>`${n.values().next().value}${i}${e}`,o=(r,a,s)=>{const o=[...a];let u=!1,l=!1,c=e(t(r[r.length-1]));for(const[t,a]of o.entries()){const d=e(a);c+d<=s?r[r.length-1]+=a:(r.push(a),c=0),n.has(a)&&(u=!0,l=o.slice(t+1).join("").startsWith(i)),u?l?""===a&&(u=!1,l=!1):"m"===a&&(u=!1):(c+=d,c===s&&t0&&r.length>1&&(r[r.length-2]+=r.pop())},u=t=>{const r=t.split(" ");let n=r.length;for(;n>0&&!(e(r[n-1])>0);)n--;return n===r.length?t:r.slice(0,n).join(" ")+r.slice(n).join("")},l=(t,l,c={})=>{if(!1!==c.trim&&""===t.trim())return"";let d,h,p="";const f=(t=>t.split(" ").map((t=>e(t))))(t);let m=[""];for(const[r,n]of t.split(" ").entries()){!1!==c.trim&&(m[m.length-1]=m[m.length-1].trimStart());let t=e(m[m.length-1]);if(0!==r&&(t>=l&&(!1===c.wordWrap||!1===c.trim)&&(m.push(""),t=0),(t>0||!1===c.trim)&&(m[m.length-1]+=" ",t++)),c.hard&&f[r]>l){const e=l-t,i=1+Math.floor((f[r]-e-1)/l);Math.floor((f[r]-1)/l)l&&t>0&&f[r]>0){if(!1===c.wordWrap&&tl&&!1===c.wordWrap?o(m,n,l):m[m.length-1]+=n}}!1!==c.trim&&(m=m.map(u));const g=[...m.join("\n")];for(const[e,t]of g.entries()){if(p+=t,n.has(t)){const{groups:t}=new RegExp(`(?:\\[(?\\d+)m|\\${i}(?.*))`).exec(g.slice(e).join(""))||{groups:{}};if(void 0!==t.code){const e=Number.parseFloat(t.code);d=39===e?void 0:e}else void 0!==t.uri&&(h=0===t.uri.length?void 0:t.uri)}const o=r.codes.get(Number(d));"\n"===g[e+1]?(h&&(p+=s("")),d&&o&&(p+=a(o))):"\n"===t&&(d&&o&&(p+=a(d)),h&&(p+=s(h)))}return p};return pe=(e,t,r)=>String(e).normalize().replace(/\r\n/g,"\n").split("\n").map((e=>l(e,t,r))).join("\n")}function xe(){if(ge)return me;ge=1;const e={right:function(e,t){e=e.trim();const r=n.stringWidth(e);if(r=t)return e;return" ".repeat(t-r>>1)+e}};class t{constructor(e){var t;this.width=e.width,this.wrap=null===(t=e.wrap)||void 0===t||t,this.rows=[]}span(...e){this.div(...e).span=!0}resetOutput(){this.rows=[]}div(...e){if(0===e.length&&this.div(""),this.wrap&&this.shouldApplyLayoutDSL(...e)&&"string"==typeof e[0])return this.applyLayoutDSL(e[0]);const t=e.map((e=>"string"==typeof e?this.colFromString(e):e));return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return 1===e.length&&"string"==typeof e[0]&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){const t=e.split("\n").map((e=>e.split("\t")));let r=0;return t.forEach((e=>{e.length>1&&n.stringWidth(e[0])>r&&(r=Math.min(Math.floor(.5*this.width),n.stringWidth(e[0])))})),t.forEach((e=>{this.div(...e.map(((t,n)=>({text:t.trim(),padding:this.measurePadding(t),width:0===n&&e.length>1?r:void 0}))))})),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){const t=n.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){const e=[];return this.rows.forEach((t=>{this.rowToString(t,e)})),e.filter((e=>!e.hidden)).map((e=>e.text)).join("\n")}rowToString(t,i){return this.rasterize(t).forEach(((a,s)=>{let o="";a.forEach(((a,u)=>{const{width:l}=t[u],c=this.negatePadding(t[u]);let d=a;if(c>n.stringWidth(a)&&(d+=" ".repeat(c-n.stringWidth(a))),t[u].align&&"left"!==t[u].align&&this.wrap){d=(0,e[t[u].align])(d,c),n.stringWidth(d)0&&(o=this.renderInline(o,i[i.length-1]))})),i.push({text:o.replace(/ +$/,""),span:t.span})})),i}renderInline(e,t){const r=e.match(/^ */),i=r?r[0].length:0,a=t.text,s=n.stringWidth(a.trimRight());return t.span?this.wrap?i{e.width=r[a],i=this.wrap?n.wrap(e.text,this.negatePadding(e),{hard:!0}).split("\n"):e.text.split("\n"),e.border&&(i.unshift("."+"-".repeat(this.negatePadding(e)+2)+"."),i.push("'"+"-".repeat(this.negatePadding(e)+2)+"'")),e.padding&&(i.unshift(...new Array(e.padding[0]||0).fill("")),i.push(...new Array(e.padding[2]||0).fill(""))),i.forEach(((e,r)=>{t[r]||t.push([]);const n=t[r];for(let e=0;ee.width||n.stringWidth(e.text)));let t=e.length,r=this.width;const i=e.map((e=>{if(e.width)return t--,r-=e.width,e.width})),a=t?Math.floor(r/t):0;return i.map(((t,r)=>void 0===t?Math.max(a,function(e){const t=e.padding||[],r=1+(t[3]||0)+(t[1]||0);if(e.border)return r+4;return r}(e[r])):t))}}function r(e,t,r){return e.border?/[.']-+[.']/.test(t)?"":0!==t.trim().length?r:" ":""}let n;const i=ne(),a=K(),s=Ce();return me=function(e){return function(e,r){return n=r,new t({width:(null==e?void 0:e.width)||("object"==typeof process&&process.stdout&&process.stdout.columns?process.stdout.columns:80),wrap:null==e?void 0:e.wrap})}(e,{stringWidth:i,stripAnsi:a,wrap:s})},me}function ke(){if(be)return ye;be=1;const{dirname:e,resolve:t}=r,{readdirSync:i,statSync:a}=n;return ye=function(r,n){let s,o=t(".",r);for(a(o).isDirectory()||(o=e(o));;){if(s=n(o,i(o)),s)return t(o,s);if(o=e(s=o),s===o)break}}}var je,Ae,Se,Pe={exports:{}};function Ie(){if(je)return Pe.exports;je=1;var e=n,t=r.join,i=r.resolve,a=r.dirname,s={extensions:["js","json","coffee"],recurse:!0,rename:function(e){return e},visit:function(e){return e}};return Pe.exports=function r(n,o,u){var l={};for(var c in o&&!u&&"string"!=typeof o&&(u=o,o=null),u=u||{},s)void 0===u[c]&&(u[c]=s[c]);return o=o?i(a(n.filename),o):a(n.filename),e.readdirSync(o).forEach((function(i){var a,s,c,d=t(o,i);e.statSync(d).isDirectory()&&u.recurse?(a=r(n,d,u),Object.keys(a).length&&(l[u.rename(i,d,i)]=a)):d!==n.filename&&function(e,t,r){return new RegExp("\\.("+r.extensions.join("|")+")$","i").test(t)&&!(r.include&&r.include instanceof RegExp&&!r.include.test(e))&&!(r.include&&"function"==typeof r.include&&!r.include(e,t))&&!(r.exclude&&r.exclude instanceof RegExp&&r.exclude.test(e))&&!(r.exclude&&"function"==typeof r.exclude&&r.exclude(e,t))}(d,i,u)&&(s=i.substring(0,i.lastIndexOf(".")),c=n.require(d),l[u.rename(s,d,i)]=u.visit(c,d,i)||c)})),l},Pe.exports.defaults=s,Pe.exports}var Te=function(){if(Se)return Ae;Se=1;var e=i;class a extends Error{constructor(e){super(e||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,a)}}let s,o=[];function u(e,t,r,n){s=n;let i={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if("string"!=typeof e.extends)return i;const n=/\.json|\..*rc$/.test(e.extends);let l=null;if(n)l=function(e,t){return s.path.resolve(e,t)}(t,e.extends);else try{l=require.resolve(e.extends)}catch(t){return e}!function(e){if(o.indexOf(e)>-1)throw new a(`Circular extended configurations: '${e}'.`)}(l),o.push(l),i=n?JSON.parse(s.readFileSync(l,"utf8")):U(e.extends),delete e.extends,i=u(i,s.path.dirname(l),r,s)}return o=[],r?l(i,e):Object.assign({},i,e)}function l(e,t){const r={};function n(e){return e&&"object"==typeof e&&!Array.isArray(e)}Object.assign(r,e);for(const i of Object.keys(t))n(t[i])&&n(r[i])?r[i]=l(e[i],t[i]):r[i]=t[i];return r}function c(e){const t=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),r=/\.*[\][<>]/g,n=t.shift();if(!n)throw new Error(`No command found in: ${e}`);const i={cmd:n.replace(r,""),demanded:[],optional:[]};return t.forEach(((e,n)=>{let a=!1;e=e.replace(/\s/g,""),/\.+[\]>]/.test(e)&&n===t.length-1&&(a=!0),/^\[/.test(e)?i.optional.push({cmd:e.replace(r,"").split("|"),variadic:a}):i.demanded.push({cmd:e.replace(r,"").split("|"),variadic:a})})),i}const d=["first","second","third","fourth","fifth","sixth"];function h(e,t,r){try{let n=0;const[i,s,o]="object"==typeof e?[{demanded:[],optional:[]},e,t]:[c(`cmd ${e}`),t,r],u=[].slice.call(s);for(;u.length&&void 0===u[u.length-1];)u.pop();const l=o||u.length;if(ld)throw new a(`Too many arguments provided. Expected max ${d} but received ${l}.`);i.demanded.forEach((e=>{const t=p(u.shift());0===e.cmd.filter((e=>e===t||"*"===e)).length&&f(t,e.cmd,n),n+=1})),i.optional.forEach((e=>{if(0===u.length)return;const t=p(u.shift());0===e.cmd.filter((e=>e===t||"*"===e)).length&&f(t,e.cmd,n),n+=1}))}catch(e){console.warn(e.stack)}}function p(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function f(e,t,r){throw new a(`Invalid ${d[r]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}function m(e){return!!e&&!!e.then&&"function"==typeof e.then}function g(e,t,r,n){r.assert.notStrictEqual(e,t,n)}function y(e,t){t.assert.strictEqual(typeof e,"string")}function b(e){return Object.keys(e)}function v(e={},t=()=>!0){const r={};return b(e).forEach((n=>{t(n,e[n])&&(r[n]=e[n])})),r}function _(){return process.versions.electron&&!process.defaultApp?0:1}function w(){return process.argv[_()]}var D=Object.freeze({__proto__:null,hideBin:function(e){return e.slice(_()+1)},getProcessArgvBin:w});function E(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new 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 O(e,t,r,n,i){if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}class C{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,r=!0,n=!1){if(h(" [boolean] [boolean] [boolean]",[e,t,r],arguments.length),Array.isArray(e)){for(let n=0;n{const n=[...r[t]||[],t];return!e.option||!n.includes(e.option)})),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){const e=this.frozens.pop();void 0!==e&&(this.globalMiddleware=e)}reset(){this.globalMiddleware=this.globalMiddleware.filter((e=>e.global))}}function x(e,t,r,n){return r.reduce(((e,r)=>{if(r.applyBeforeValidation!==n)return e;if(r.mutates){if(r.applied)return e;r.applied=!0}if(m(e))return e.then((e=>Promise.all([e,r(e,t)]))).then((([e,t])=>Object.assign(e,t)));{const n=r(e,t);return m(n)?n.then((t=>Object.assign(e,t))):Object.assign(e,n)}}),e)}function k(e,t,r=e=>{throw e}){try{const r="function"==typeof e?e():e;return m(r)?r.then((e=>t(e))):t(r)}catch(e){return r(e)}}const j=/(^\*)|(^\$0)/;class A{constructor(e,t,r,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=e,this.globalMiddleware=r,this.validation=t}addDirectory(e,t,r,n){"boolean"!=typeof(n=n||{}).recurse&&(n.recurse=!1),Array.isArray(n.extensions)||(n.extensions=["js"]);const i="function"==typeof n.visit?n.visit:e=>e;n.visit=(e,t,r)=>{const n=i(e,t,r);if(n){if(this.requireCache.has(t))return n;this.requireCache.add(t),this.addHandler(n)}return n},this.shim.requireDirectory({require:t,filename:r},e,n)}addHandler(e,t,r,n,i,a){let s=[];const o=function(e){return e?e.map((e=>(e.applyBeforeValidation=!1,e))):[]}(i);if(n=n||(()=>{}),Array.isArray(e))if(function(e){return e.every((e=>"string"==typeof e))}(e))[e,...s]=e;else for(const t of e)this.addHandler(t);else{if(function(e){return"object"==typeof e&&!Array.isArray(e)}(e)){let t=Array.isArray(e.command)||"string"==typeof e.command?e.command:this.moduleName(e);return e.aliases&&(t=[].concat(t).concat(e.aliases)),void this.addHandler(t,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated)}if(S(r))return void this.addHandler([e].concat(s),t,r.builder,r.handler,r.middlewares,r.deprecated)}if("string"==typeof e){const i=c(e);s=s.map((e=>c(e).cmd));let u=!1;const l=[i.cmd].concat(s).filter((e=>!j.test(e)||(u=!0,!1)));0===l.length&&u&&l.push("$0"),u&&(i.cmd=l[0],s=l.slice(1),e=e.replace(j,i.cmd)),s.forEach((e=>{this.aliasMap[e]=i.cmd})),!1!==t&&this.usage.command(e,t,u,s,a),this.handlers[i.cmd]={original:e,description:t,handler:n,builder:r||{},middlewares:o,deprecated:a,demanded:i.demanded,optional:i.optional},u&&(this.defaultCommand=this.handlers[i.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,r,n,i,a){const s=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,o=t.getInternalMethods().getContext(),u=o.commands.slice(),l=!e;e&&(o.commands.push(e),o.fullCommands.push(s.original));const c=this.applyBuilderUpdateUsageAndParse(l,s,t,r.aliases,u,n,i,a);return m(c)?c.then((e=>this.applyMiddlewareAndGetResult(l,s,e.innerArgv,o,i,e.aliases,t))):this.applyMiddlewareAndGetResult(l,s,c.innerArgv,o,i,c.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,r,n,i,a,s,o){const u=t.builder;let l=r;if(P(u)){r.getInternalMethods().getUsageInstance().freeze();const c=u(r.getInternalMethods().reset(n),o);if(m(c))return c.then((n=>{var o;return l=(o=n)&&"function"==typeof o.getInternalMethods?n:r,this.parseAndUpdateUsage(e,t,l,i,a,s)}))}else(function(e){return"object"==typeof e})(u)&&(r.getInternalMethods().getUsageInstance().freeze(),l=r.getInternalMethods().reset(n),Object.keys(t.builder).forEach((e=>{l.option(e,u[e])})));return this.parseAndUpdateUsage(e,t,l,i,a,s)}parseAndUpdateUsage(e,t,r,n,i,a){e&&r.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(r)&&r.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,t),t.description);const s=r.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,i,a);return m(s)?s.then((e=>({aliases:r.parsed.aliases,innerArgv:e}))):{aliases:r.parsed.aliases,innerArgv:s}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&0===e.getInternalMethods().getUsageInstance().getUsage().length}usageFromParentCommandsCommandHandler(e,t){const r=j.test(t.original)?t.original.replace(j,"").trim():t.original,n=e.filter((e=>!j.test(e)));return n.push(r),`$0 ${n.join(" ")}`}handleValidationAndGetResult(e,t,r,n,i,a,s,o){if(!a.getInternalMethods().getHasOutput()){const t=a.getInternalMethods().runValidation(i,o,a.parsed.error,e);r=k(r,(e=>(t(e),e)))}if(t.handler&&!a.getInternalMethods().getHasOutput()){a.getInternalMethods().setHasOutput();const n=!!a.getOptions().configuration["populate--"];a.getInternalMethods().postProcess(r,n,!1,!1),r=k(r=x(r,a,s,!1),(e=>{const r=t.handler(e);return m(r)?r.then((()=>e)):e})),e||a.getInternalMethods().getUsageInstance().cacheHelpMessage(),m(r)&&!a.getInternalMethods().hasParseCallback()&&r.catch((e=>{try{a.getInternalMethods().getUsageInstance().fail(null,e)}catch(e){}}))}return e||(n.commands.pop(),n.fullCommands.pop()),r}applyMiddlewareAndGetResult(e,t,r,n,i,a,s){let o={};if(i)return r;s.getInternalMethods().getHasOutput()||(o=this.populatePositionals(t,r,n,s));const u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=x(r,s,u,!0);return m(l)?l.then((r=>this.handleValidationAndGetResult(e,t,r,n,a,s,u,o))):this.handleValidationAndGetResult(e,t,l,n,a,s,u,o)}populatePositionals(e,t,r,n){t._=t._.slice(r.commands.length);const i=e.demanded.slice(0),a=e.optional.slice(0),s={};for(this.validation.positionalCount(i.length,t._.length);i.length;){const e=i.shift();this.populatePositional(e,t,s)}for(;a.length;){const e=a.shift();this.populatePositional(e,t,s)}return t._=r.commands.concat(t._.map((e=>""+e))),this.postProcessPositionals(t,s,this.cmdToParseOptions(e.original),n),s}populatePositional(e,t,r){const n=e.cmd[0];e.variadic?r[n]=t._.splice(0).map(String):t._.length&&(r[n]=[String(t._.shift())])}cmdToParseOptions(e){const t={array:[],default:{},alias:{},demand:{}},r=c(e);return r.demanded.forEach((e=>{const[r,...n]=e.cmd;e.variadic&&(t.array.push(r),t.default[r]=[]),t.alias[r]=n,t.demand[r]=!0})),r.optional.forEach((e=>{const[r,...n]=e.cmd;e.variadic&&(t.array.push(r),t.default[r]=[]),t.alias[r]=n})),t}postProcessPositionals(e,t,r,n){const i=Object.assign({},n.getOptions());i.default=Object.assign(r.default,i.default);for(const e of Object.keys(r.alias))i.alias[e]=(i.alias[e]||[]).concat(r.alias[e]);i.array=i.array.concat(r.array),i.config={};const a=[];if(Object.keys(t).forEach((e=>{t[e].map((t=>{i.configuration["unknown-options-as-args"]&&(i.key[e]=!0),a.push(`--${e}`),a.push(t)}))})),!a.length)return;const s=Object.assign({},i.configuration,{"populate--":!1}),o=this.shim.Parser.detailed(a,Object.assign({},i,{configuration:s}));if(o.error)n.getInternalMethods().getUsageInstance().fail(o.error.message,o.error);else{const r=Object.keys(t);Object.keys(t).forEach((e=>{r.push(...o.aliases[e])})),Object.keys(o.argv).forEach((i=>{r.includes(i)&&(t[i]||(t[i]=o.argv[i]),!this.isInConfigs(n,i)&&!this.isDefaulted(n,i)&&Object.prototype.hasOwnProperty.call(e,i)&&Object.prototype.hasOwnProperty.call(o.argv,i)&&(Array.isArray(e[i])||Array.isArray(o.argv[i]))?e[i]=[].concat(e[i],o.argv[i]):e[i]=o.argv[i])}))}}isDefaulted(e,t){const{default:r}=e.getOptions();return Object.prototype.hasOwnProperty.call(r,t)||Object.prototype.hasOwnProperty.call(r,this.shim.Parser.camelCase(t))}isInConfigs(e,t){const{configObjects:r}=e.getOptions();return r.some((e=>Object.prototype.hasOwnProperty.call(e,t)))||r.some((e=>Object.prototype.hasOwnProperty.call(e,this.shim.Parser.camelCase(t))))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){const t=j.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");e.getInternalMethods().getUsageInstance().usage(t,this.defaultCommand.description)}const t=this.defaultCommand.builder;if(P(t))return t(e,!0);S(t)||Object.keys(t).forEach((r=>{e.option(r,t[r])}))}moduleName(e){const t=function(e){if(void 0===U)return null;for(let t,r=0,n=Object.keys(require.cache);r{const r=t;r._handle&&r.isTTY&&"function"==typeof r._handle.setBlocking&&r._handle.setBlocking(e)}))}function T(e){return"boolean"==typeof e}function F(e,t){const r=t.y18n.__,n={},i=[];n.failFn=function(e){i.push(e)};let s=null,o=null,u=!0;n.showHelpOnFail=function(t=!0,r){const[i,a]="string"==typeof t?[!0,t]:[t,r];return e.getInternalMethods().isGlobalContext()&&(o=a),s=a,u=i,n};let l=!1;n.fail=function(t,r){const c=e.getInternalMethods().getLoggerInstance();if(!i.length){if(e.getExitProcess()&&I(!0),!l){l=!0,u&&(e.showHelp("error"),c.error()),(t||r)&&c.error(t||r);const n=s||o;n&&((t||r)&&c.error(""),c.error(n))}if(r=r||new a(t),e.getExitProcess())return e.exit(1);if(e.getInternalMethods().hasParseCallback())return e.exit(1,r);throw r}for(let e=i.length-1;e>=0;--e){const a=i[e];if(T(a)){if(r)throw r;if(t)throw Error(t)}else a(t,r,n)}};let c=[],d=!1;n.usage=(e,t)=>null===e?(d=!0,c=[],n):(d=!1,c.push([e,t||""]),n),n.getUsage=()=>c,n.getUsageDisabled=()=>d,n.getPositionalGroupName=()=>r("Positionals:");let h=[];n.example=(e,t)=>{h.push([e,t||""])};let p=[];n.command=function(e,t,r,n,i=!1){r&&(p=p.map((e=>(e[2]=!1,e)))),p.push([e,t||"",r,n,i])},n.getCommands=()=>p;let f={};n.describe=function(e,t){Array.isArray(e)?e.forEach((e=>{n.describe(e,t)})):"object"==typeof e?Object.keys(e).forEach((t=>{n.describe(t,e[t])})):f[e]=t},n.getDescriptions=()=>f;let m=[];n.epilog=e=>{m.push(e)};let g,y=!1;n.wrap=e=>{y=!0,g=e},n.getWrap=()=>t.getEnv("YARGS_DISABLE_WRAP")?null:(y||(g=t.process.stdColumns?Math.min(80,t.process.stdColumns):80,y=!0),g);const b="__yargsString__:";function _(e,r,n){let i=0;return Array.isArray(e)||(e=Object.values(e).map((e=>[e]))),e.forEach((e=>{i=Math.max(t.stringWidth(n?`${n} ${R(e[0])}`:R(e[0]))+$(e[0]),i)})),r&&(i=Math.min(i,parseInt((.5*r).toString(),10))),i}let w;function D(t){return e.getOptions().hiddenOptions.indexOf(t)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}function E(e,t){let n=`[${r("default:")} `;if(void 0===e&&!t)return null;if(t)n+=t;else switch(typeof e){case"string":n+=`"${e}"`;break;case"object":n+=JSON.stringify(e);break;default:n+=e}return`${n}]`}n.deferY18nLookup=e=>b+e,n.help=function(){if(w)return w;!function(){const t=e.getDemandedOptions(),r=e.getOptions();(Object.keys(r.alias)||[]).forEach((i=>{r.alias[i].forEach((a=>{f[a]&&n.describe(i,f[a]),a in t&&e.demandOption(i,t[a]),r.boolean.includes(a)&&e.boolean(i),r.count.includes(a)&&e.count(i),r.string.includes(a)&&e.string(i),r.normalize.includes(a)&&e.normalize(i),r.array.includes(a)&&e.array(i),r.number.includes(a)&&e.number(i)}))}))}();const i=e.customScriptName?e.$0:t.path.basename(e.$0),a=e.getDemandedOptions(),s=e.getDemandedCommands(),o=e.getDeprecatedOptions(),u=e.getGroups(),l=e.getOptions();let g=[];g=g.concat(Object.keys(f)),g=g.concat(Object.keys(a)),g=g.concat(Object.keys(s)),g=g.concat(Object.keys(l.default)),g=g.filter(D),g=Object.keys(g.reduce(((e,t)=>("_"!==t&&(e[t]=!0),e)),{}));const y=n.getWrap(),v=t.cliui({width:y,wrap:!!y});if(!d)if(c.length)c.forEach((e=>{v.div({text:`${e[0].replace(/\$0/g,i)}`}),e[1]&&v.div({text:`${e[1]}`,padding:[1,0,0,0]})})),v.div();else if(p.length){let e=null;e=s._?`${i} <${r("command")}>\n`:`${i} [${r("command")}]\n`,v.div(`${e}`)}if(p.length>1||1===p.length&&!p[0][2]){v.div(r("Commands:"));const t=e.getInternalMethods().getContext(),n=t.commands.length?`${t.commands.join(" ")} `:"";!0===e.getInternalMethods().getParserConfiguration()["sort-commands"]&&(p=p.sort(((e,t)=>e[0].localeCompare(t[0]))));const a=i?`${i} `:"";p.forEach((e=>{const t=`${a}${n}${e[0].replace(/^\$0 ?/,"")}`;v.span({text:t,padding:[0,2,0,2],width:_(p,y,`${i}${n}`)+4},{text:e[1]});const s=[];e[2]&&s.push(`[${r("default")}]`),e[3]&&e[3].length&&s.push(`[${r("aliases:")} ${e[3].join(", ")}]`),e[4]&&("string"==typeof e[4]?s.push(`[${r("deprecated: %s",e[4])}]`):s.push(`[${r("deprecated")}]`)),s.length?v.div({text:s.join(" "),padding:[0,0,0,2],align:"right"}):v.div()})),v.div()}const O=(Object.keys(l.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);g=g.filter((t=>!e.parsed.newAliases[t]&&O.every((e=>-1===(l.alias[e]||[]).indexOf(t)))));const C=r("Options:");u[C]||(u[C]=[]),function(e,t,r,n){let i=[],a=null;Object.keys(r).forEach((e=>{i=i.concat(r[e])})),e.forEach((e=>{a=[e].concat(t[e]),a.some((e=>-1!==i.indexOf(e)))||r[n].push(e)}))}(g,l.alias,u,C);const x=e=>/^--/.test(R(e)),k=Object.keys(u).filter((e=>u[e].length>0)).map((e=>({groupName:e,normalizedKeys:u[e].filter(D).map((e=>{if(O.includes(e))return e;for(let t,r=0;void 0!==(t=O[r]);r++)if((l.alias[t]||[]).includes(e))return t;return e}))}))).filter((({normalizedKeys:e})=>e.length>0)).map((({groupName:e,normalizedKeys:t})=>{const r=t.reduce(((t,r)=>(t[r]=[r].concat(l.alias[r]||[]).map((t=>e===n.getPositionalGroupName()?t:(/^[0-9]$/.test(t)?l.boolean.includes(r)?"-":"--":t.length>1?"--":"-")+t)).sort(((e,t)=>x(e)===x(t)?0:x(e)?1:-1)).join(", "),t)),{});return{groupName:e,normalizedKeys:t,switches:r}}));if(k.filter((({groupName:e})=>e!==n.getPositionalGroupName())).some((({normalizedKeys:e,switches:t})=>!e.every((e=>x(t[e])))))&&k.filter((({groupName:e})=>e!==n.getPositionalGroupName())).forEach((({normalizedKeys:e,switches:t})=>{e.forEach((e=>{var r;x(t[e])&&(t[e]=N(r=t[e])?{text:r.text,indentation:r.indentation+4}:{text:r,indentation:4})}))})),k.forEach((({groupName:t,normalizedKeys:i,switches:s})=>{v.div(t),i.forEach((t=>{const i=s[t];let u=f[t]||"",c=null;u.includes(b)&&(u=r(u.substring(16))),l.boolean.includes(t)&&(c=`[${r("boolean")}]`),l.count.includes(t)&&(c=`[${r("count")}]`),l.string.includes(t)&&(c=`[${r("string")}]`),l.normalize.includes(t)&&(c=`[${r("string")}]`),l.array.includes(t)&&(c=`[${r("array")}]`),l.number.includes(t)&&(c=`[${r("number")}]`);const d=[t in o?(h=o[t],"string"==typeof h?`[${r("deprecated: %s",h)}]`:`[${r("deprecated")}]`):null,c,t in a?`[${r("required")}]`:null,l.choices&&l.choices[t]?`[${r("choices:")} ${n.stringifiedValues(l.choices[t])}]`:null,E(l.default[t],l.defaultDescription[t])].filter(Boolean).join(" ");var h;v.span({text:R(i),padding:[0,2,0,2+$(i)],width:_(s,y)+4},u);const p=!0===e.getInternalMethods().getUsageConfiguration()["hide-types"];d&&!p?v.div({text:d,padding:[0,0,0,2],align:"right"}):v.div()})),v.div()})),h.length&&(v.div(r("Examples:")),h.forEach((e=>{e[0]=e[0].replace(/\$0/g,i)})),h.forEach((e=>{""===e[1]?v.div({text:e[0],padding:[0,2,0,2]}):v.div({text:e[0],padding:[0,2,0,2],width:_(h,y)+4},{text:e[1]})})),v.div()),m.length>0){const e=m.map((e=>e.replace(/\$0/g,i))).join("\n");v.div(`${e}\n`)}return v.toString().replace(/\s*$/,"")},n.cacheHelpMessage=function(){w=this.help()},n.clearCachedHelpMessage=function(){w=void 0},n.hasCachedHelpMessage=function(){return!!w},n.showHelp=t=>{const r=e.getInternalMethods().getLoggerInstance();t||(t="error"),("function"==typeof t?t:r[t])(n.help())},n.functionDescription=e=>["(",e.name?t.Parser.decamelize(e.name,"-"):r("generated-value"),")"].join(""),n.stringifiedValues=function(e,t){let r="";const n=t||", ",i=[].concat(e);return e&&i.length?(i.forEach((e=>{r.length&&(r+=n),r+=JSON.stringify(e)})),r):r};let O=null;n.version=e=>{O=e},n.showVersion=t=>{const r=e.getInternalMethods().getLoggerInstance();t||(t="error"),("function"==typeof t?t:r[t])(O)},n.reset=function(e){return s=null,l=!1,c=[],d=!1,m=[],h=[],p=[],f=v(f,(t=>!e[t])),n};const C=[];return n.freeze=function(){C.push({failMessage:s,failureOutput:l,usages:c,usageDisabled:d,epilogs:m,examples:h,commands:p,descriptions:f})},n.unfreeze=function(e=!1){const t=C.pop();t&&(e?(f={...t.descriptions,...f},p=[...t.commands,...p],c=[...t.usages,...c],h=[...t.examples,...h],m=[...t.epilogs,...m]):({failMessage:s,failureOutput:l,usages:c,usageDisabled:d,epilogs:m,examples:h,commands:p,descriptions:f}=t))},n}function N(e){return"object"==typeof e}function $(e){return N(e)?e.indentation:0}function R(e){return N(e)?e.text:e}class M{constructor(e,t,r,n){var i,a,s;this.yargs=e,this.usage=t,this.command=r,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=null!==(s=(null===(i=this.shim.getEnv("SHELL"))||void 0===i?void 0:i.includes("zsh"))||(null===(a=this.shim.getEnv("ZSH_NAME"))||void 0===a?void 0:a.includes("zsh")))&&void 0!==s&&s}defaultCompletion(e,t,r,n){const i=this.command.getCommandHandlers();for(let t=0,r=e.length;t{const n=c(r[0]).cmd;if(-1===t.indexOf(n))if(this.zshShell){const t=r[1]||"";e.push(n.replace(/:/g,"\\:")+":"+t)}else e.push(n)}))}optionCompletions(e,t,r,n){if((n.match(/^-/)||""===n&&0===e.length)&&!this.previousArgHasChoices(t)){const r=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((a=>{const s=!!r.configuration["boolean-negation"]&&r.boolean.includes(a);i.includes(a)||r.hiddenOptions.includes(a)||this.argsContainKey(t,a,s)||this.completeOptionKey(a,e,n,s&&!!r.default[a])}))}}choicesFromOptionsCompletions(e,t,r,n){if(this.previousArgHasChoices(t)){const r=this.getPreviousArgChoices(t);r&&r.length>0&&e.push(...r.map((e=>e.replace(/:/g,"\\:"))))}}choicesFromPositionalsCompletions(e,t,r,n){if(""===n&&e.length>0&&this.previousArgHasChoices(t))return;const i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],a=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),s=i[r._.length-a-1];if(!s)return;const o=this.yargs.getOptions().choices[s]||[];for(const t of o)t.startsWith(n)&&e.push(t.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],r="";if(!t.startsWith("-")&&e.length>1&&(r=t,t=e[e.length-2]),!t.startsWith("-"))return;const n=t.replace(/^-+/,""),i=this.yargs.getOptions(),a=[n,...this.yargs.getAliases()[n]||[]];let s;for(const e of a)if(Object.prototype.hasOwnProperty.call(i.key,e)&&Array.isArray(i.choices[e])){s=i.choices[e];break}return s?s.filter((e=>!r||e.startsWith(r))):void 0}previousArgHasChoices(e){const t=this.getPreviousArgChoices(e);return void 0!==t&&t.length>0}argsContainKey(e,t,r){const n=t=>-1!==e.indexOf((/^[^0-9]$/.test(t)?"-":"--")+t);if(n(t))return!0;if(r&&n(`no-${t}`))return!0;if(this.aliases)for(const e of this.aliases[t])if(n(e))return!0;return!1}completeOptionKey(e,t,r,n){var i,a,s,o;let u=e;if(this.zshShell){const t=this.usage.getDescriptions(),r=null===(a=null===(i=null==this?void 0:this.aliases)||void 0===i?void 0:i[e])||void 0===a?void 0:a.find((e=>{const r=t[e];return"string"==typeof r&&r.length>0})),n=r?t[r]:void 0,l=null!==(o=null!==(s=t[e])&&void 0!==s?s:n)&&void 0!==o?o:"";u=`${e.replace(/:/g,"\\:")}:${l.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}const l=!/^--/.test(r)&&(e=>/^[^0-9]$/.test(e))(e)?"-":"--";t.push(l+u),n&&t.push(l+"no-"+u)}customCompletion(e,t,r,n){if(g(this.customCompletionFunction,null,this.shim),this.customCompletionFunction.length<3){const e=this.customCompletionFunction(r,t);return m(e)?e.then((e=>{this.shim.process.nextTick((()=>{n(null,e)}))})).catch((e=>{this.shim.process.nextTick((()=>{n(e,void 0)}))})):n(null,e)}return function(e){return e.length>3}(this.customCompletionFunction)?this.customCompletionFunction(r,t,((i=n)=>this.defaultCompletion(e,t,r,i)),(e=>{n(null,e)})):this.customCompletionFunction(r,t,(e=>{n(null,e)}))}getCompletion(e,t){const r=e.length?e[e.length-1]:"",n=this.yargs.parse(e,!0),i=this.customCompletionFunction?n=>this.customCompletion(e,n,r,t):n=>this.defaultCompletion(e,n,r,t);return m(n)?n.then(i):i(n)}generateCompletionScript(e,t){let r=this.zshShell?'#compdef {{app_name}}\n###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n IFS=$si\n _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n':'###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word="${COMP_WORDS[COMP_CWORD]}"\n args=("${COMP_WORDS[@]}")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';const n=this.shim.path.basename(e);return e.match(/\.js$/)&&(e=`./${e}`),r=r.replace(/{{app_name}}/g,n),r=r.replace(/{{completion_command}}/g,t),r.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function L(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;const r=[];let n,i;for(n=0;n<=t.length;n++)r[n]=[n];for(i=0;i<=e.length;i++)r[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?r[n][i]=r[n-1][i-1]:n>1&&i>1&&t.charAt(n-2)===e.charAt(i-1)&&t.charAt(n-1)===e.charAt(i-2)?r[n][i]=r[n-2][i-2]+1:r[n][i]=Math.min(r[n-1][i-1]+1,Math.min(r[n][i-1]+1,r[n-1][i]+1));return r[t.length][e.length]}const B=["$0","--","_"];var H,V,q,W,G,J,K,Y,X,Q,ee,te,re,ie,ae,se,oe,ue,le,ce,de,he,pe,fe,me,ge,ye,be,we,De,Ee,Oe,Ce,je,Pe;const Te=Symbol("copyDoubleDash"),Fe=Symbol("copyDoubleDash"),Ne=Symbol("deleteFromParserHintObject"),$e=Symbol("emitWarning"),Re=Symbol("freeze"),Me=Symbol("getDollarZero"),Le=Symbol("getParserConfiguration"),Be=Symbol("getUsageConfiguration"),Ue=Symbol("guessLocale"),ze=Symbol("guessVersion"),Ze=Symbol("parsePositionalNumbers"),He=Symbol("pkgUp"),Ve=Symbol("populateParserHintArray"),qe=Symbol("populateParserHintSingleValueDictionary"),We=Symbol("populateParserHintArrayDictionary"),Ge=Symbol("populateParserHintDictionary"),Je=Symbol("sanitizeKey"),Ke=Symbol("setKey"),Ye=Symbol("unfreeze"),Xe=Symbol("validateAsync"),Qe=Symbol("getCommandInstance"),et=Symbol("getContext"),tt=Symbol("getHasOutput"),rt=Symbol("getLoggerInstance"),nt=Symbol("getParseContext"),it=Symbol("getUsageInstance"),at=Symbol("getValidationInstance"),st=Symbol("hasParseCallback"),ot=Symbol("isGlobalContext"),ut=Symbol("postProcess"),lt=Symbol("rebase"),ct=Symbol("reset"),dt=Symbol("runYargsParserAndExecuteCommands"),ht=Symbol("runValidation"),pt=Symbol("setHasOutput"),ft=Symbol("kTrackManuallySetKeys");class mt{constructor(e=[],t,r,n){this.customScriptName=!1,this.parsed=!1,H.set(this,void 0),V.set(this,void 0),q.set(this,{commands:[],fullCommands:[]}),W.set(this,null),G.set(this,null),J.set(this,"show-hidden"),K.set(this,null),Y.set(this,!0),X.set(this,{}),Q.set(this,!0),ee.set(this,[]),te.set(this,void 0),re.set(this,{}),ie.set(this,!1),ae.set(this,null),se.set(this,!0),oe.set(this,void 0),ue.set(this,""),le.set(this,void 0),ce.set(this,void 0),de.set(this,{}),he.set(this,null),pe.set(this,null),fe.set(this,{}),me.set(this,{}),ge.set(this,void 0),ye.set(this,!1),be.set(this,void 0),we.set(this,!1),De.set(this,!1),Ee.set(this,!1),Oe.set(this,void 0),Ce.set(this,{}),je.set(this,null),Pe.set(this,void 0),O(this,be,n),O(this,ge,e),O(this,V,t),O(this,ce,r),O(this,te,new C(this)),this.$0=this[Me](),this[ct](),O(this,H,E(this,H,"f")),O(this,Oe,E(this,Oe,"f")),O(this,Pe,E(this,Pe,"f")),O(this,le,E(this,le,"f")),E(this,le,"f").showHiddenOpt=E(this,J,"f"),O(this,oe,this[Fe]())}addHelpOpt(e,t){return h("[string|boolean] [string]",[e,t],arguments.length),E(this,ae,"f")&&(this[Ne](E(this,ae,"f")),O(this,ae,null)),!1===e&&void 0===t||(O(this,ae,"string"==typeof e?e:"help"),this.boolean(E(this,ae,"f")),this.describe(E(this,ae,"f"),t||E(this,Oe,"f").deferY18nLookup("Show help"))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(h("[string|boolean] [string]",[e,t],arguments.length),!1===e&&void 0===t)return this;const r="string"==typeof e?e:E(this,J,"f");return this.boolean(r),this.describe(r,t||E(this,Oe,"f").deferY18nLookup("Show hidden options")),E(this,le,"f").showHiddenOpt=r,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return h(" [string|array]",[e,t],arguments.length),this[We](this.alias.bind(this),"alias",e,t),this}array(e){return h("",[e],arguments.length),this[Ve]("array",e),this[ft](e),this}boolean(e){return h("",[e],arguments.length),this[Ve]("boolean",e),this[ft](e),this}check(e,t){return h(" [boolean]",[e,t],arguments.length),this.middleware(((t,r)=>k((()=>e(t,r.getOptions())),(r=>(r?("string"==typeof r||r instanceof Error)&&E(this,Oe,"f").fail(r.toString(),r):E(this,Oe,"f").fail(E(this,be,"f").y18n.__("Argument check failed: %s",e.toString())),t)),(e=>(E(this,Oe,"f").fail(e.message?e.message:e.toString(),e),t)))),!1,t),this}choices(e,t){return h(" [string|array]",[e,t],arguments.length),this[We](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(h(" [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new a("coerce callback must be provided");for(const r of e)this.coerce(r,t);return this}if("object"==typeof e){for(const t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new a("coerce callback must be provided");return E(this,le,"f").key[e]=!0,E(this,te,"f").addCoerceMiddleware(((r,n)=>{let i;return Object.prototype.hasOwnProperty.call(r,e)?k((()=>(i=n.getAliases(),t(r[e]))),(t=>{r[e]=t;const a=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(i[e]&&!0!==a)for(const n of i[e])r[n]=t;return r}),(e=>{throw new a(e.message)})):r}),e),this}conflicts(e,t){return h(" [string|array]",[e,t],arguments.length),E(this,Pe,"f").conflicts(e,t),this}config(e="config",t,r){return h("[object|string] [string|function] [function]",[e,t,r],arguments.length),"object"!=typeof e||Array.isArray(e)?("function"==typeof t&&(r=t,t=void 0),this.describe(e,t||E(this,Oe,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((e=>{E(this,le,"f").config[e]=r||!0})),this):(e=u(e,E(this,V,"f"),this[Le]()["deep-merge-config"]||!1,E(this,be,"f")),E(this,le,"f").configObjects=(E(this,le,"f").configObjects||[]).concat(e),this)}completion(e,t,r){return h("[string] [string|boolean|function] [function]",[e,t,r],arguments.length),"function"==typeof t&&(r=t,t=void 0),O(this,G,e||E(this,G,"f")||"completion"),t||!1===t||(t="generate completion script"),this.command(E(this,G,"f"),t),r&&E(this,W,"f").registerFunction(r),this}command(e,t,r,n,i,a){return h(" [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,r,n,i,a],arguments.length),E(this,H,"f").addHandler(e,t,r,n,i,a),this}commands(e,t,r,n,i,a){return this.command(e,t,r,n,i,a)}commandDir(e,t){h(" [object]",[e,t],arguments.length);const r=E(this,ce,"f")||E(this,be,"f").require;return E(this,H,"f").addDirectory(e,r,E(this,be,"f").getCallerFile(),t),this}count(e){return h("",[e],arguments.length),this[Ve]("count",e),this[ft](e),this}default(e,t,r){return h(" [*] [string]",[e,t,r],arguments.length),r&&(y(e,E(this,be,"f")),E(this,le,"f").defaultDescription[e]=r),"function"==typeof t&&(y(e,E(this,be,"f")),E(this,le,"f").defaultDescription[e]||(E(this,le,"f").defaultDescription[e]=E(this,Oe,"f").functionDescription(t)),t=t.call()),this[qe](this.default.bind(this),"default",e,t),this}defaults(e,t,r){return this.default(e,t,r)}demandCommand(e=1,t,r,n){return h("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,r,n],arguments.length),"number"!=typeof t&&(r=t,t=1/0),this.global("_",!1),E(this,le,"f").demandedCommands._={min:e,max:t,minMsg:r,maxMsg:n},this}demand(e,t,r){return Array.isArray(t)?(t.forEach((e=>{g(r,!0,E(this,be,"f")),this.demandOption(e,r)})),t=1/0):"number"!=typeof t&&(r=t,t=1/0),"number"==typeof e?(g(r,!0,E(this,be,"f")),this.demandCommand(e,t,r,r)):Array.isArray(e)?e.forEach((e=>{g(r,!0,E(this,be,"f")),this.demandOption(e,r)})):"string"==typeof r?this.demandOption(e,r):!0!==r&&void 0!==r||this.demandOption(e),this}demandOption(e,t){return h(" [string]",[e,t],arguments.length),this[qe](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return h(" [string|boolean]",[e,t],arguments.length),E(this,le,"f").deprecatedOptions[e]=t,this}describe(e,t){return h(" [string]",[e,t],arguments.length),this[Ke](e,!0),E(this,Oe,"f").describe(e,t),this}detectLocale(e){return h("",[e],arguments.length),O(this,Y,e),this}env(e){return h("[string|boolean]",[e],arguments.length),!1===e?delete E(this,le,"f").envPrefix:E(this,le,"f").envPrefix=e||"",this}epilogue(e){return h("",[e],arguments.length),E(this,Oe,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return h(" [string]",[e,t],arguments.length),Array.isArray(e)?e.forEach((e=>this.example(...e))):E(this,Oe,"f").example(e,t),this}exit(e,t){O(this,ie,!0),O(this,K,t),E(this,Q,"f")&&E(this,be,"f").process.exit(e)}exitProcess(e=!0){return h("[boolean]",[e],arguments.length),O(this,Q,e),this}fail(e){if(h("",[e],arguments.length),"boolean"==typeof e&&!1!==e)throw new a("Invalid first argument. Expected function or boolean 'false'");return E(this,Oe,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return h(" [function]",[e,t],arguments.length),t?E(this,W,"f").getCompletion(e,t):new Promise(((t,r)=>{E(this,W,"f").getCompletion(e,((e,n)=>{e?r(e):t(n)}))}))}getDemandedOptions(){return h([],0),E(this,le,"f").demandedOptions}getDemandedCommands(){return h([],0),E(this,le,"f").demandedCommands}getDeprecatedOptions(){return h([],0),E(this,le,"f").deprecatedOptions}getDetectLocale(){return E(this,Y,"f")}getExitProcess(){return E(this,Q,"f")}getGroups(){return Object.assign({},E(this,re,"f"),E(this,me,"f"))}getHelp(){if(O(this,ie,!0),!E(this,Oe,"f").hasCachedHelpMessage()){if(!this.parsed){const e=this[dt](E(this,ge,"f"),void 0,void 0,0,!0);if(m(e))return e.then((()=>E(this,Oe,"f").help()))}const e=E(this,H,"f").runDefaultBuilderOn(this);if(m(e))return e.then((()=>E(this,Oe,"f").help()))}return Promise.resolve(E(this,Oe,"f").help())}getOptions(){return E(this,le,"f")}getStrict(){return E(this,we,"f")}getStrictCommands(){return E(this,De,"f")}getStrictOptions(){return E(this,Ee,"f")}global(e,t){return h(" [boolean]",[e,t],arguments.length),e=[].concat(e),!1!==t?E(this,le,"f").local=E(this,le,"f").local.filter((t=>-1===e.indexOf(t))):e.forEach((e=>{E(this,le,"f").local.includes(e)||E(this,le,"f").local.push(e)})),this}group(e,t){h(" ",[e,t],arguments.length);const r=E(this,me,"f")[t]||E(this,re,"f")[t];E(this,me,"f")[t]&&delete E(this,me,"f")[t];const n={};return E(this,re,"f")[t]=(r||[]).concat(e).filter((e=>!n[e]&&(n[e]=!0))),this}hide(e){return h("",[e],arguments.length),E(this,le,"f").hiddenOptions.push(e),this}implies(e,t){return h(" [number|string|array]",[e,t],arguments.length),E(this,Pe,"f").implies(e,t),this}locale(e){return h("[string]",[e],arguments.length),void 0===e?(this[Ue](),E(this,be,"f").y18n.getLocale()):(O(this,Y,!1),E(this,be,"f").y18n.setLocale(e),this)}middleware(e,t,r){return E(this,te,"f").addMiddleware(e,!!t,r)}nargs(e,t){return h(" [number]",[e,t],arguments.length),this[qe](this.nargs.bind(this),"narg",e,t),this}normalize(e){return h("",[e],arguments.length),this[Ve]("normalize",e),this}number(e){return h("",[e],arguments.length),this[Ve]("number",e),this[ft](e),this}option(e,t){if(h(" [object]",[e,t],arguments.length),"object"==typeof e)Object.keys(e).forEach((t=>{this.options(t,e[t])}));else{"object"!=typeof t&&(t={}),this[ft](e),!E(this,je,"f")||"version"!==e&&"version"!==(null==t?void 0:t.alias)||this[$e](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join("\n"),void 0,"versionWarning"),E(this,le,"f").key[e]=!0,t.alias&&this.alias(e,t.alias);const r=t.deprecate||t.deprecated;r&&this.deprecateOption(e,r);const n=t.demand||t.required||t.require;n&&this.demand(e,n),t.demandOption&&this.demandOption(e,"string"==typeof t.demandOption?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),"default"in t&&this.default(e,t.default),void 0!==t.implies&&this.implies(e,t.implies),void 0!==t.nargs&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||"boolean"===t.type)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||"array"===t.type)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||"number"===t.type)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||"string"===t.type)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||"count"===t.type)&&this.count(e),"boolean"==typeof t.global&&this.global(e,t.global),t.defaultDescription&&(E(this,le,"f").defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);const i=t.describe||t.description||t.desc,a=E(this,Oe,"f").getDescriptions();Object.prototype.hasOwnProperty.call(a,e)&&"string"!=typeof i||this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,r){h("[string|array] [function|boolean|object] [function]",[e,t,r],arguments.length),this[Re](),void 0===e&&(e=E(this,ge,"f")),"object"==typeof t&&(O(this,pe,t),t=r),"function"==typeof t&&(O(this,he,t),t=!1),t||O(this,ge,e),E(this,he,"f")&&O(this,Q,!1);const n=this[dt](e,!!t),i=this.parsed;return E(this,W,"f").setParsed(this.parsed),m(n)?n.then((e=>(E(this,he,"f")&&E(this,he,"f").call(this,E(this,K,"f"),e,E(this,ue,"f")),e))).catch((e=>{throw E(this,he,"f")&&E(this,he,"f")(e,this.parsed.argv,E(this,ue,"f")),e})).finally((()=>{this[Ye](),this.parsed=i})):(E(this,he,"f")&&E(this,he,"f").call(this,E(this,K,"f"),n,E(this,ue,"f")),this[Ye](),this.parsed=i,n)}parseAsync(e,t,r){const n=this.parse(e,t,r);return m(n)?n:Promise.resolve(n)}parseSync(e,t,r){const n=this.parse(e,t,r);if(m(n))throw new a(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(e){return h("",[e],arguments.length),O(this,de,e),this}pkgConf(e,t){h(" [string]",[e,t],arguments.length);let r=null;const n=this[He](t||E(this,V,"f"));return n[e]&&"object"==typeof n[e]&&(r=u(n[e],t||E(this,V,"f"),this[Le]()["deep-merge-config"]||!1,E(this,be,"f")),E(this,le,"f").configObjects=(E(this,le,"f").configObjects||[]).concat(r)),this}positional(e,t){h(" ",[e,t],arguments.length);const r=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=v(t,((e,t)=>!("type"===e&&!["string","number","boolean"].includes(t))&&r.includes(e)));const n=E(this,q,"f").fullCommands[E(this,q,"f").fullCommands.length-1],i=n?E(this,H,"f").cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return b(i).forEach((r=>{const n=i[r];Array.isArray(n)?-1!==n.indexOf(e)&&(t[r]=!0):n[e]&&!(r in t)&&(t[r]=n[e])})),this.group(e,E(this,Oe,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return h("[boolean]",[e],arguments.length),O(this,ye,e),this}required(e,t,r){return this.demand(e,t,r)}require(e,t,r){return this.demand(e,t,r)}requiresArg(e){return h(" [number]",[e],arguments.length),"string"==typeof e&&E(this,le,"f").narg[e]||this[qe](this.requiresArg.bind(this),"narg",e,NaN),this}showCompletionScript(e,t){return h("[string] [string]",[e,t],arguments.length),e=e||this.$0,E(this,oe,"f").log(E(this,W,"f").generateCompletionScript(e,t||E(this,G,"f")||"completion")),this}showHelp(e){if(h("[string|function]",[e],arguments.length),O(this,ie,!0),!E(this,Oe,"f").hasCachedHelpMessage()){if(!this.parsed){const t=this[dt](E(this,ge,"f"),void 0,void 0,0,!0);if(m(t))return t.then((()=>{E(this,Oe,"f").showHelp(e)})),this}const t=E(this,H,"f").runDefaultBuilderOn(this);if(m(t))return t.then((()=>{E(this,Oe,"f").showHelp(e)})),this}return E(this,Oe,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return h("[boolean|string] [string]",[e,t],arguments.length),E(this,Oe,"f").showHelpOnFail(e,t),this}showVersion(e){return h("[string|function]",[e],arguments.length),E(this,Oe,"f").showVersion(e),this}skipValidation(e){return h("",[e],arguments.length),this[Ve]("skipValidation",e),this}strict(e){return h("[boolean]",[e],arguments.length),O(this,we,!1!==e),this}strictCommands(e){return h("[boolean]",[e],arguments.length),O(this,De,!1!==e),this}strictOptions(e){return h("[boolean]",[e],arguments.length),O(this,Ee,!1!==e),this}string(e){return h("",[e],arguments.length),this[Ve]("string",e),this[ft](e),this}terminalWidth(){return h([],0),E(this,be,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return h("",[e],arguments.length),O(this,Y,!1),E(this,be,"f").y18n.updateLocale(e),this}usage(e,t,r,n){if(h(" [string|boolean] [function|object] [function]",[e,t,r,n],arguments.length),void 0!==t){if(g(e,null,E(this,be,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,r,n);throw new a(".usage() description must start with $0 if being used as alias for .command()")}return E(this,Oe,"f").usage(e),this}usageConfiguration(e){return h("",[e],arguments.length),O(this,Ce,e),this}version(e,t,r){const n="version";if(h("[boolean|string] [string] [string]",[e,t,r],arguments.length),E(this,je,"f")&&(this[Ne](E(this,je,"f")),E(this,Oe,"f").version(void 0),O(this,je,null)),0===arguments.length)r=this[ze](),e=n;else if(1===arguments.length){if(!1===e)return this;r=e,e=n}else 2===arguments.length&&(r=t,t=void 0);return O(this,je,"string"==typeof e?e:n),t=t||E(this,Oe,"f").deferY18nLookup("Show version number"),E(this,Oe,"f").version(r||void 0),this.boolean(E(this,je,"f")),this.describe(E(this,je,"f"),t),this}wrap(e){return h("",[e],arguments.length),E(this,Oe,"f").wrap(e),this}[(H=new WeakMap,V=new WeakMap,q=new WeakMap,W=new WeakMap,G=new WeakMap,J=new WeakMap,K=new WeakMap,Y=new WeakMap,X=new WeakMap,Q=new WeakMap,ee=new WeakMap,te=new WeakMap,re=new WeakMap,ie=new WeakMap,ae=new WeakMap,se=new WeakMap,oe=new WeakMap,ue=new WeakMap,le=new WeakMap,ce=new WeakMap,de=new WeakMap,he=new WeakMap,pe=new WeakMap,fe=new WeakMap,me=new WeakMap,ge=new WeakMap,ye=new WeakMap,be=new WeakMap,we=new WeakMap,De=new WeakMap,Ee=new WeakMap,Oe=new WeakMap,Ce=new WeakMap,je=new WeakMap,Pe=new WeakMap,Te)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(e){}return e}[Fe](){return{log:(...e)=>{this[st]()||console.log(...e),O(this,ie,!0),E(this,ue,"f").length&&O(this,ue,E(this,ue,"f")+"\n"),O(this,ue,E(this,ue,"f")+e.join(" "))},error:(...e)=>{this[st]()||console.error(...e),O(this,ie,!0),E(this,ue,"f").length&&O(this,ue,E(this,ue,"f")+"\n"),O(this,ue,E(this,ue,"f")+e.join(" "))}}}[Ne](e){b(E(this,le,"f")).forEach((t=>{if("configObjects"===t)return;const r=E(this,le,"f")[t];Array.isArray(r)?r.includes(e)&&r.splice(r.indexOf(e),1):"object"==typeof r&&delete r[e]})),delete E(this,Oe,"f").getDescriptions()[e]}[$e](e,t,r){E(this,X,"f")[r]||(E(this,be,"f").process.emitWarning(e,t),E(this,X,"f")[r]=!0)}[Re](){E(this,ee,"f").push({options:E(this,le,"f"),configObjects:E(this,le,"f").configObjects.slice(0),exitProcess:E(this,Q,"f"),groups:E(this,re,"f"),strict:E(this,we,"f"),strictCommands:E(this,De,"f"),strictOptions:E(this,Ee,"f"),completionCommand:E(this,G,"f"),output:E(this,ue,"f"),exitError:E(this,K,"f"),hasOutput:E(this,ie,"f"),parsed:this.parsed,parseFn:E(this,he,"f"),parseContext:E(this,pe,"f")}),E(this,Oe,"f").freeze(),E(this,Pe,"f").freeze(),E(this,H,"f").freeze(),E(this,te,"f").freeze()}[Me](){let e,t="";return e=/\b(node|iojs|electron)(\.exe)?$/.test(E(this,be,"f").process.argv()[0])?E(this,be,"f").process.argv().slice(1,2):E(this,be,"f").process.argv().slice(0,1),t=e.map((e=>{const t=this[lt](E(this,V,"f"),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.lengtht.includes("package.json")?"package.json":void 0));g(n,void 0,E(this,be,"f")),r=JSON.parse(E(this,be,"f").readFileSync(n,"utf8"))}catch(e){}return E(this,fe,"f")[t]=r||{},E(this,fe,"f")[t]}[Ve](e,t){(t=[].concat(t)).forEach((t=>{t=this[Je](t),E(this,le,"f")[e].push(t)}))}[qe](e,t,r,n){this[Ge](e,t,r,n,((e,t,r)=>{E(this,le,"f")[e][t]=r}))}[We](e,t,r,n){this[Ge](e,t,r,n,((e,t,r)=>{E(this,le,"f")[e][t]=(E(this,le,"f")[e][t]||[]).concat(r)}))}[Ge](e,t,r,n,i){if(Array.isArray(r))r.forEach((t=>{e(t,n)}));else if((e=>"object"==typeof e)(r))for(const t of b(r))e(t,r[t]);else i(t,this[Je](r),n)}[Je](e){return"__proto__"===e?"___proto___":e}[Ke](e,t){return this[qe](this[Ke].bind(this),"key",e,t),this}[Ye](){var e,t,r,n,i,a,s,o,u,l,c,d;const h=E(this,ee,"f").pop();let p;g(h,void 0,E(this,be,"f")),e=this,t=this,r=this,n=this,i=this,a=this,s=this,o=this,u=this,l=this,c=this,d=this,({options:{set value(t){O(e,le,t)}}.value,configObjects:p,exitProcess:{set value(e){O(t,Q,e)}}.value,groups:{set value(e){O(r,re,e)}}.value,output:{set value(e){O(n,ue,e)}}.value,exitError:{set value(e){O(i,K,e)}}.value,hasOutput:{set value(e){O(a,ie,e)}}.value,parsed:this.parsed,strict:{set value(e){O(s,we,e)}}.value,strictCommands:{set value(e){O(o,De,e)}}.value,strictOptions:{set value(e){O(u,Ee,e)}}.value,completionCommand:{set value(e){O(l,G,e)}}.value,parseFn:{set value(e){O(c,he,e)}}.value,parseContext:{set value(e){O(d,pe,e)}}.value}=h),E(this,le,"f").configObjects=p,E(this,Oe,"f").unfreeze(),E(this,Pe,"f").unfreeze(),E(this,H,"f").unfreeze(),E(this,te,"f").unfreeze()}[Xe](e,t){return k(t,(t=>(e(t),t)))}getInternalMethods(){return{getCommandInstance:this[Qe].bind(this),getContext:this[et].bind(this),getHasOutput:this[tt].bind(this),getLoggerInstance:this[rt].bind(this),getParseContext:this[nt].bind(this),getParserConfiguration:this[Le].bind(this),getUsageConfiguration:this[Be].bind(this),getUsageInstance:this[it].bind(this),getValidationInstance:this[at].bind(this),hasParseCallback:this[st].bind(this),isGlobalContext:this[ot].bind(this),postProcess:this[ut].bind(this),reset:this[ct].bind(this),runValidation:this[ht].bind(this),runYargsParserAndExecuteCommands:this[dt].bind(this),setHasOutput:this[pt].bind(this)}}[Qe](){return E(this,H,"f")}[et](){return E(this,q,"f")}[tt](){return E(this,ie,"f")}[rt](){return E(this,oe,"f")}[nt](){return E(this,pe,"f")||{}}[it](){return E(this,Oe,"f")}[at](){return E(this,Pe,"f")}[st](){return!!E(this,he,"f")}[ot](){return E(this,se,"f")}[ut](e,t,r,n){return r||m(e)||(t||(e=this[Te](e)),(this[Le]()["parse-positional-numbers"]||void 0===this[Le]()["parse-positional-numbers"])&&(e=this[Ze](e)),n&&(e=x(e,this,E(this,te,"f").getMiddleware(),!1))),e}[ct](e={}){O(this,le,E(this,le,"f")||{});const t={};t.local=E(this,le,"f").local||[],t.configObjects=E(this,le,"f").configObjects||[];const r={};return t.local.forEach((t=>{r[t]=!0,(e[t]||[]).forEach((e=>{r[e]=!0}))})),Object.assign(E(this,me,"f"),Object.keys(E(this,re,"f")).reduce(((e,t)=>{const n=E(this,re,"f")[t].filter((e=>!(e in r)));return n.length>0&&(e[t]=n),e}),{})),O(this,re,{}),["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((e=>{t[e]=(E(this,le,"f")[e]||[]).filter((e=>!r[e]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"].forEach((e=>{t[e]=v(E(this,le,"f")[e],(e=>!r[e]))})),t.envPrefix=E(this,le,"f").envPrefix,O(this,le,t),O(this,Oe,E(this,Oe,"f")?E(this,Oe,"f").reset(r):F(this,E(this,be,"f"))),O(this,Pe,E(this,Pe,"f")?E(this,Pe,"f").reset(r):function(e,t,r){const n=r.y18n.__,i=r.y18n.__n,a={nonOptionCount:function(r){const n=e.getDemandedCommands(),a=r._.length+(r["--"]?r["--"].length:0)-e.getInternalMethods().getContext().commands.length;n._&&(an._.max)&&(an._.max&&(void 0!==n._.maxMsg?t.fail(n._.maxMsg?n._.maxMsg.replace(/\$0/g,a.toString()).replace(/\$1/,n._.max.toString()):null):t.fail(i("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",a,a.toString(),n._.max.toString()))))},positionalCount:function(e,r){r{B.includes(t)||Object.prototype.hasOwnProperty.call(s,t)||Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),t)||a.isValidAndSomeAliasIsNotNew(t,n)||d.push(t)})),u&&(h.commands.length>0||c.length>0||o)&&r._.slice(h.commands.length).forEach((e=>{c.includes(""+e)||d.push(""+e)})),u){const t=(null===(l=e.getDemandedCommands()._)||void 0===l?void 0:l.max)||0,n=h.commands.length+t;n{e=String(e),h.commands.includes(e)||d.includes(e)||d.push(e)}))}d.length&&t.fail(i("Unknown argument: %s","Unknown arguments: %s",d.length,d.map((e=>e.trim()?e:`"${e}"`)).join(", ")))},unknownCommands:function(r){const n=e.getInternalMethods().getCommandInstance().getCommands(),a=[],s=e.getInternalMethods().getContext();return(s.commands.length>0||n.length>0)&&r._.slice(s.commands.length).forEach((e=>{n.includes(""+e)||a.push(""+e)})),a.length>0&&(t.fail(i("Unknown command: %s","Unknown commands: %s",a.length,a.join(", "))),!0)},isValidAndSomeAliasIsNotNew:function(t,r){if(!Object.prototype.hasOwnProperty.call(r,t))return!1;const n=e.parsed.newAliases;return[t,...r[t]].some((e=>!Object.prototype.hasOwnProperty.call(n,e)||!n[t]))},limitedChoices:function(r){const i=e.getOptions(),a={};if(!Object.keys(i.choices).length)return;Object.keys(r).forEach((e=>{-1===B.indexOf(e)&&Object.prototype.hasOwnProperty.call(i.choices,e)&&[].concat(r[e]).forEach((t=>{-1===i.choices[e].indexOf(t)&&void 0!==t&&(a[e]=(a[e]||[]).concat(t))}))}));const s=Object.keys(a);if(!s.length)return;let o=n("Invalid values:");s.forEach((e=>{o+=`\n ${n("Argument: %s, Given: %s, Choices: %s",e,t.stringifiedValues(a[e]),t.stringifiedValues(i.choices[e]))}`})),t.fail(o)}};let s={};function o(e,t){const r=Number(t);return"number"==typeof(t=isNaN(r)?t:r)?t=e._.length>=t:t.match(/^--no-.+/)?(t=t.match(/^--no-(.+)/)[1],t=!Object.prototype.hasOwnProperty.call(e,t)):t=Object.prototype.hasOwnProperty.call(e,t),t}a.implies=function(t,n){h(" [array|number|string]",[t,n],arguments.length),"object"==typeof t?Object.keys(t).forEach((e=>{a.implies(e,t[e])})):(e.global(t),s[t]||(s[t]=[]),Array.isArray(n)?n.forEach((e=>a.implies(t,e))):(g(n,void 0,r),s[t].push(n)))},a.getImplied=function(){return s},a.implications=function(e){const r=[];if(Object.keys(s).forEach((t=>{const n=t;(s[t]||[]).forEach((t=>{let i=n;const a=t;i=o(e,i),t=o(e,t),i&&!t&&r.push(` ${n} -> ${a}`)}))})),r.length){let e=`${n("Implications failed:")}\n`;r.forEach((t=>{e+=t})),t.fail(e)}};let u={};a.conflicts=function(t,r){h(" [array|string]",[t,r],arguments.length),"object"==typeof t?Object.keys(t).forEach((e=>{a.conflicts(e,t[e])})):(e.global(t),u[t]||(u[t]=[]),Array.isArray(r)?r.forEach((e=>a.conflicts(t,e))):u[t].push(r))},a.getConflicting=()=>u,a.conflicting=function(i){Object.keys(i).forEach((e=>{u[e]&&u[e].forEach((r=>{r&&void 0!==i[e]&&void 0!==i[r]&&t.fail(n("Arguments %s and %s are mutually exclusive",e,r))}))})),e.getInternalMethods().getParserConfiguration()["strip-dashed"]&&Object.keys(u).forEach((e=>{u[e].forEach((a=>{a&&void 0!==i[r.Parser.camelCase(e)]&&void 0!==i[r.Parser.camelCase(a)]&&t.fail(n("Arguments %s and %s are mutually exclusive",e,a))}))}))},a.recommendCommands=function(e,r){r=r.sort(((e,t)=>t.length-e.length));let i=null,a=1/0;for(let t,n=0;void 0!==(t=r[n]);n++){const r=L(e,t);r<=3&&r!e[t])),u=v(u,(t=>!e[t])),a};const l=[];return a.freeze=function(){l.push({implied:s,conflicting:u})},a.unfreeze=function(){const e=l.pop();g(e,void 0,r),({implied:s,conflicting:u}=e)},a}(this,E(this,Oe,"f"),E(this,be,"f"))),O(this,H,E(this,H,"f")?E(this,H,"f").reset():function(e,t,r,n){return new A(e,t,r,n)}(E(this,Oe,"f"),E(this,Pe,"f"),E(this,te,"f"),E(this,be,"f"))),E(this,W,"f")||O(this,W,function(e,t,r,n){return new M(e,t,r,n)}(this,E(this,Oe,"f"),E(this,H,"f"),E(this,be,"f"))),E(this,te,"f").reset(),O(this,G,null),O(this,ue,""),O(this,K,null),O(this,ie,!1),this.parsed=!1,this}[lt](e,t){return E(this,be,"f").path.relative(e,t)}[dt](e,t,r,n=0,i=!1){let s=!!r||i;e=e||E(this,ge,"f"),E(this,le,"f").__=E(this,be,"f").y18n.__,E(this,le,"f").configuration=this[Le]();const o=!!E(this,le,"f").configuration["populate--"],u=Object.assign({},E(this,le,"f").configuration,{"populate--":!0}),l=E(this,be,"f").Parser.detailed(e,Object.assign({},E(this,le,"f"),{configuration:{"parse-positional-numbers":!1,...u}})),c=Object.assign(l.argv,E(this,pe,"f"));let d;const h=l.aliases;let p=!1,f=!1;Object.keys(c).forEach((e=>{e===E(this,ae,"f")&&c[e]?p=!0:e===E(this,je,"f")&&c[e]&&(f=!0)})),c.$0=this.$0,this.parsed=l,0===n&&E(this,Oe,"f").clearCachedHelpMessage();try{if(this[Ue](),t)return this[ut](c,o,!!r,!1);E(this,ae,"f")&&[E(this,ae,"f")].concat(h[E(this,ae,"f")]||[]).filter((e=>e.length>1)).includes(""+c._[c._.length-1])&&(c._.pop(),p=!0),O(this,se,!1,"f");const u=E(this,H,"f").getCommands(),g=E(this,W,"f").completionKey in c,y=p||g||i;if(c._.length){if(u.length){let e;for(let t,a=n||0;void 0!==c._[a];a++){if(t=String(c._[a]),u.includes(t)&&t!==E(this,G,"f")){const e=E(this,H,"f").runCommand(t,this,l,a+1,i,p||f||i);return this[ut](e,o,!!r,!1)}if(!e&&t!==E(this,G,"f")){e=t;break}}!E(this,H,"f").hasDefaultCommand()&&E(this,ye,"f")&&e&&!y&&E(this,Pe,"f").recommendCommands(e,u)}E(this,G,"f")&&c._.includes(E(this,G,"f"))&&!g&&(E(this,Q,"f")&&I(!0),this.showCompletionScript(),this.exit(0))}if(E(this,H,"f").hasDefaultCommand()&&!y){const e=E(this,H,"f").runCommand(null,this,l,0,i,p||f||i);return this[ut](e,o,!!r,!1)}if(g){E(this,Q,"f")&&I(!0);const t=(e=[].concat(e)).slice(e.indexOf(`--${E(this,W,"f").completionKey}`)+1);return E(this,W,"f").getCompletion(t,((e,t)=>{if(e)throw new a(e.message);(t||[]).forEach((e=>{E(this,oe,"f").log(e)})),this.exit(0)})),this[ut](c,!o,!!r,!1)}if(E(this,ie,"f")||(p?(E(this,Q,"f")&&I(!0),s=!0,this.showHelp("log"),this.exit(0)):f&&(E(this,Q,"f")&&I(!0),s=!0,E(this,Oe,"f").showVersion("log"),this.exit(0))),!s&&E(this,le,"f").skipValidation.length>0&&(s=Object.keys(c).some((e=>E(this,le,"f").skipValidation.indexOf(e)>=0&&!0===c[e]))),!s){if(l.error)throw new a(l.error.message);if(!g){const e=this[ht](h,{},l.error);r||(d=x(c,this,E(this,te,"f").getMiddleware(),!0)),d=this[Xe](e,null!=d?d:c),m(d)&&!r&&(d=d.then((()=>x(c,this,E(this,te,"f").getMiddleware(),!1))))}}}catch(e){if(!(e instanceof a))throw e;E(this,Oe,"f").fail(e.message,e)}return this[ut](null!=d?d:c,o,!!r,!0)}[ht](e,t,r,n){const i={...this.getDemandedOptions()};return s=>{if(r)throw new a(r.message);E(this,Pe,"f").nonOptionCount(s),E(this,Pe,"f").requiredArguments(s,i);let o=!1;E(this,De,"f")&&(o=E(this,Pe,"f").unknownCommands(s)),E(this,we,"f")&&!o?E(this,Pe,"f").unknownArguments(s,e,t,!!n):E(this,Ee,"f")&&E(this,Pe,"f").unknownArguments(s,e,{},!1,!1),E(this,Pe,"f").limitedChoices(s),E(this,Pe,"f").implications(s),E(this,Pe,"f").conflicting(s)}}[pt](){O(this,ie,!0)}[ft](e){if("string"==typeof e)E(this,le,"f").key[e]=!0;else for(const t of e)E(this,le,"f").key[t]=!0}}var gt,yt;const{readFileSync:bt}=n,{inspect:vt}=t,{resolve:_t}=r,wt=z(),Dt=Z();var Et,Ot={assert:{notStrictEqual:e.notStrictEqual,strictEqual:e.strictEqual},cliui:xe(),findUp:ke(),getEnv:e=>process.env[e],getCallerFile:_e?ve:(_e=1,ve=function(e){if(void 0===e&&(e=2),e>=Error.stackTraceLimit)throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+e+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var t=Error.prepareStackTrace;Error.prepareStackTrace=function(e,t){return t};var r=(new Error).stack;if(Error.prepareStackTrace=t,null!==r&&"object"==typeof r)return r[e]?r[e].getFileName():void 0}),getProcessArgvBin:w,inspect:vt,mainFilename:null!==(yt=null===(gt=null==U?void 0:require.main)||void 0===gt?void 0:gt.filename)&&void 0!==yt?yt:process.cwd(),Parser:Dt,path:r,process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:e=>{process.exit(e)},nextTick:process.nextTick,stdColumns:void 0!==process.stdout.columns?process.stdout.columns:null},readFileSync:bt,require:U,requireDirectory:Ie(),stringWidth:ne(),y18n:wt({directory:_t(__dirname,"../locales"),updateFiles:!1})};const Ct=(null===(Et=null===process||void 0===process?void 0:process.env)||void 0===Et?void 0:Et.YARGS_MIN_NODE_VERSION)?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version&&Number(process.version.match(/v([^.]+)/)[1]){const n=new mt(e,t,r,kt);return Object.defineProperty(n,"argv",{get:()=>n.parse(),enumerable:!0}),n.help(),n.version(),n}),argsert:h,isPromise:m,objFilter:v,parseCommand:c,Parser:xt,processArgv:D,YError:a};return Ae=jt}(),Fe=B(Te);const{applyExtends:Ne,cjsPlatformShim:$e,Parser:Re,processArgv:Me,Yargs:Le}=Fe;function Be(e,t,r,n){return new(r||(r=Promise))((function(i,a){function s(e){try{u(n.next(e))}catch(e){a(e)}}function o(e){try{u(n.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,o)}u((n=n.apply(e,t||[])).next())}))}function Ue(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function ze(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Ue(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}}Le.applyExtends=(e,t,r)=>Ne(e,t,r,$e),Le.hideBin=Me.hideBin,Le.Parser=Re,"function"==typeof SuppressedError&&SuppressedError;var Ze;!function(e){e.MARKDOWN="markdown",e.PDF="pdf",e.CODE="code"}(Ze||(Ze={}));const He={[Ze.MARKDOWN]:[".md"],[Ze.PDF]:[".pdf"],[Ze.CODE]:[".html",".ts",".tsx",".js",".jsx",".css",".sass",".scss"]},Ve=(e,...t)=>Be(void 0,[e,...t],void 0,(function*(e,t=[".md"],r=[]){if(!e)return r;const n=yield d.promises.readdir(e);return yield Be(void 0,void 0,void 0,(function*(){let i=[];for(const a of n){const n=`${e}/${a}`;if((yield d.promises.stat(n)).isDirectory()){const e=yield Ve(n,t,r);i=[...i,...e]}else t.some((e=>n.substring(n.lastIndexOf("."))===e))&&i.push(n)}return i}))})),qe=e=>{e.output||(console.error("The --output or --o argument is required."),process.exit(1)),e.input||(console.error("The --input or --i argument is required."),process.exit(1))},We=(e,t)=>new Promise(((r,n)=>{try{h().from.string(t).to(e.output,(()=>{r({})}))}catch(e){n(e)}}));var Ge,Je;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const 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=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const 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}(Ge||(Ge={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Je||(Je={}));const Ke=Ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ye=e=>{switch(typeof e){case"undefined":return Ke.undefined;case"string":return Ke.string;case"number":return isNaN(e)?Ke.nan:Ke.number;case"boolean":return Ke.boolean;case"function":return Ke.function;case"bigint":return Ke.bigint;case"symbol":return Ke.symbol;case"object":return Array.isArray(e)?Ke.array:null===e?Ke.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Ke.promise:"undefined"!=typeof Map&&e instanceof Map?Ke.map:"undefined"!=typeof Set&&e instanceof Set?Ke.set:"undefined"!=typeof Date&&e instanceof Date?Ke.date:Ke.object;default:return Ke.unknown}},Xe=Ge.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"]);class Qe extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const 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(;ne.message){const t={},r=[];for(const 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()}}Qe.create=e=>new Qe(e);const et=(e,t)=>{let r;switch(e.code){case Xe.invalid_type:r=e.received===Ke.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Xe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ge.jsonStringifyReplacer)}`;break;case Xe.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ge.joinValues(e.keys,", ")}`;break;case Xe.invalid_union:r="Invalid input";break;case Xe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ge.joinValues(e.options)}`;break;case Xe.invalid_enum_value:r=`Invalid enum value. Expected ${Ge.joinValues(e.options)}, received '${e.received}'`;break;case Xe.invalid_arguments:r="Invalid function arguments";break;case Xe.invalid_return_type:r="Invalid function return type";break;case Xe.invalid_date:r="Invalid date";break;case Xe.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}"`:Ge.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Xe.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 Xe.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 Xe.custom:r="Invalid input";break;case Xe.invalid_intersection_types:r="Intersection results could not be merged";break;case Xe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Xe.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ge.assertNever(e)}return{message:r}};let tt=et;function rt(){return tt}const nt=e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,a=[...r,...i.path||[]],s={...i,path:a};if(void 0!==i.message)return{...i,path:a,message:i.message};let o="";const u=n.filter((e=>!!e)).slice().reverse();for(const e of u)o=e(s,{data:t,defaultError:o}).message;return{...i,path:a,message:o}};function it(e,t){const r=rt(),n=nt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===et?void 0:et].filter((e=>!!e))});e.common.issues.push(n)}class at{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return st;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return at.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:i}=n;if("aborted"===t.status)return st;if("aborted"===i.status)return st;"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}}}const st=Object.freeze({status:"aborted"}),ot=e=>({status:"dirty",value:e}),ut=e=>({status:"valid",value:e}),lt=e=>"aborted"===e.status,ct=e=>"dirty"===e.status,dt=e=>"valid"===e.status,ht=e=>"undefined"!=typeof Promise&&e instanceof Promise;function pt(e,t,r,n){if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function ft(e,t,r,n,i){if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var mt,gt,yt;"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}(mt||(mt={}));class bt{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}}const vt=(e,t)=>{if(dt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Qe(e.common.issues);return this._error=t,this._error}}};function _t(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{var a,s;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:i.defaultError}:void 0===i.data?{message:null!==(a=null!=o?o:n)&&void 0!==a?a:i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:null!==(s=null!=o?o:r)&&void 0!==s?s:i.defaultError}},description:i}}class wt{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)}get description(){return this._def.description}_getType(e){return Ye(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new at,ctx:{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ht(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)},i=this._parseSync({data:e,path:n.path,parent:n});return vt(n,i)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const 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:Ye(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(ht(n)?n:Promise.resolve(n));return vt(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const i=e(t),a=()=>n.addIssue({code:Xe.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then((e=>!!e||(a(),!1))):!!i||(a(),!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 mr({schema:this,typeName:kr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return gr.create(this,this._def)}nullable(){return yr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this,this._def)}promise(){return fr.create(this,this._def)}or(e){return Qt.create([this,e],this._def)}and(e){return nr.create(this,e,this._def)}transform(e){return new mr({..._t(this._def),schema:this,typeName:kr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new br({..._t(this._def),innerType:this,defaultValue:t,typeName:kr.ZodDefault})}brand(){return new Dr({typeName:kr.ZodBranded,type:this,..._t(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new vr({..._t(this._def),innerType:this,catchValue:t,typeName:kr.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Er.create(this,e)}readonly(){return Or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Dt=/^c[^\s-]{8,}$/i,Et=/^[0-9a-z]+$/,Ot=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ct=/^[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,xt=/^[a-z0-9_-]{21}$/i,kt=/^[-+]?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)?)??$/,jt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let At;const St=/^(?:(?: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])$/,Pt=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,It=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tt="((\\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])))",Ft=new RegExp(`^${Tt}$`);function Nt(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 $t(e){let t=`${Tt}T${Nt(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}class Rt extends wt{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Ke.string){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.string,received:t.parsedType}),st}const t=new at;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.lengtha.value&&(r=this._getOrReturnCtx(e,r),it(r,{code:Xe.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,i=e.data.lengthe.test(t)),{validation:t,code:Xe.invalid_string,...mt.errToObj(r)})}_addCheck(e){return new Rt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...mt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...mt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...mt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...mt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...mt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...mt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...mt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...mt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...mt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...mt.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)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...mt.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,...mt.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...mt.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...mt.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...mt.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...mt.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...mt.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...mt.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...mt.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...mt.errToObj(t)})}nonempty(e){return this.min(1,mt.errToObj(e))}trim(){return new Rt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Rt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Rt({...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 isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuen?r:n;return parseInt(e.toFixed(i).replace(".",""))%parseInt(t.toFixed(i).replace(".",""))/Math.pow(10,i)}Rt.create=e=>{var t;return new Rt({checks:[],typeName:kr.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,..._t(e)})};class Lt extends wt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==Ke.number){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.number,received:t.parsedType}),st}let t;const r=new at;for(const n of this._def.checks)if("int"===n.kind)Ge.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.datan.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==Mt(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.not_finite,message:n.message}),r.dirty()):Ge.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,mt.toString(t))}gt(e,t){return this.setLimit("min",e,!1,mt.toString(t))}lte(e,t){return this.setLimit("max",e,!0,mt.toString(t))}lt(e,t){return this.setLimit("max",e,!1,mt.toString(t))}setLimit(e,t,r,n){return new Lt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:mt.toString(n)}]})}_addCheck(e){return new Lt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:mt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:mt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:mt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:mt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:mt.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:mt.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:mt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:mt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:mt.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===e.kind||"multipleOf"===e.kind&&Ge.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.valuenew Lt({checks:[],typeName:kr.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,..._t(e)});class Bt extends wt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==Ke.bigint){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.bigint,received:t.parsedType}),st}let t;const r=new at;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.datan.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),it(t,{code:Xe.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):Ge.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,mt.toString(t))}gt(e,t){return this.setLimit("min",e,!1,mt.toString(t))}lte(e,t){return this.setLimit("max",e,!0,mt.toString(t))}lt(e,t){return this.setLimit("max",e,!1,mt.toString(t))}setLimit(e,t,r,n){return new Bt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:mt.toString(n)}]})}_addCheck(e){return new Bt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:mt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:mt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:mt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:mt.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:mt.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value{var t;return new Bt({checks:[],typeName:kr.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,..._t(e)})};class Ut extends wt{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Ke.boolean){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.boolean,received:t.parsedType}),st}return ut(e.data)}}Ut.create=e=>new Ut({typeName:kr.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,..._t(e)});class zt extends wt{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Ke.date){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.date,received:t.parsedType}),st}if(isNaN(e.data.getTime())){return it(this._getOrReturnCtx(e),{code:Xe.invalid_date}),st}const t=new at;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()n.value&&(r=this._getOrReturnCtx(e,r),it(r,{code:Xe.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):Ge.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new zt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:mt.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:mt.toString(t)})}get minDate(){let e=null;for(const 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(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew zt({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:kr.ZodDate,..._t(e)});class Zt extends wt{_parse(e){if(this._getType(e)!==Ke.symbol){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.symbol,received:t.parsedType}),st}return ut(e.data)}}Zt.create=e=>new Zt({typeName:kr.ZodSymbol,..._t(e)});class Ht extends wt{_parse(e){if(this._getType(e)!==Ke.undefined){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.undefined,received:t.parsedType}),st}return ut(e.data)}}Ht.create=e=>new Ht({typeName:kr.ZodUndefined,..._t(e)});class Vt extends wt{_parse(e){if(this._getType(e)!==Ke.null){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.null,received:t.parsedType}),st}return ut(e.data)}}Vt.create=e=>new Vt({typeName:kr.ZodNull,..._t(e)});class qt extends wt{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}}qt.create=e=>new qt({typeName:kr.ZodAny,..._t(e)});class Wt extends wt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}}Wt.create=e=>new Wt({typeName:kr.ZodUnknown,..._t(e)});class Gt extends wt{_parse(e){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.never,received:t.parsedType}),st}}Gt.create=e=>new Gt({typeName:kr.ZodNever,..._t(e)});class Jt extends wt{_parse(e){if(this._getType(e)!==Ke.undefined){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.void,received:t.parsedType}),st}return ut(e.data)}}Jt.create=e=>new Jt({typeName:kr.ZodVoid,..._t(e)});class Kt extends wt{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==Ke.array)return it(t,{code:Xe.invalid_type,expected:Ke.array,received:t.parsedType}),st;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,i=t.data.lengthn.maxLength.value&&(it(t,{code:Xe.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 bt(t,e,t.path,r))))).then((e=>at.mergeArray(r,e)));const i=[...t.data].map(((e,r)=>n.type._parseSync(new bt(t,e,t.path,r))));return at.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Kt({...this._def,minLength:{value:e,message:mt.toString(t)}})}max(e,t){return new Kt({...this._def,maxLength:{value:e,message:mt.toString(t)}})}length(e,t){return new Kt({...this._def,exactLength:{value:e,message:mt.toString(t)}})}nonempty(e){return this.min(1,e)}}function Yt(e){if(e instanceof Xt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=gr.create(Yt(n))}return new Xt({...e._def,shape:()=>t})}return e instanceof Kt?new Kt({...e._def,type:Yt(e.element)}):e instanceof gr?gr.create(Yt(e.unwrap())):e instanceof yr?yr.create(Yt(e.unwrap())):e instanceof ir?ir.create(e.items.map((e=>Yt(e)))):e}Kt.create=(e,t)=>new Kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:kr.ZodArray,..._t(t)});class Xt extends wt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Ge.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==Ke.object){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.object,received:t.parsedType}),st}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gt&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||a.push(e);const s=[];for(const e of i){const t=n[e],i=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new bt(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof Gt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(it(r,{code:Xe.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new bt(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of s){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>at.mergeObjectSync(t,e))):at.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return mt.errToObj,new Xt({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,i,a,s;const o=null!==(a=null===(i=(n=this._def).errorMap)||void 0===i?void 0:i.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(s=mt.errToObj(e).message)&&void 0!==s?s:o}:{message:o}}}:{}})}strip(){return new Xt({...this._def,unknownKeys:"strip"})}passthrough(){return new Xt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Xt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Xt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:kr.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Xt({...this._def,catchall:e})}pick(e){const t={};return Ge.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new Xt({...this._def,shape:()=>t})}omit(e){const t={};return Ge.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new Xt({...this._def,shape:()=>t})}deepPartial(){return Yt(this)}partial(e){const t={};return Ge.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new Xt({...this._def,shape:()=>t})}required(e){const t={};return Ge.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof gr;)e=e._def.innerType;t[r]=e}})),new Xt({...this._def,shape:()=>t})}keyof(){return dr(Ge.objectKeys(this.shape))}}Xt.create=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strip",catchall:Gt.create(),typeName:kr.ZodObject,..._t(t)}),Xt.strictCreate=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strict",catchall:Gt.create(),typeName:kr.ZodObject,..._t(t)}),Xt.lazycreate=(e,t)=>new Xt({shape:e,unknownKeys:"strip",catchall:Gt.create(),typeName:kr.ZodObject,..._t(t)});class Qt extends wt{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new Qe(e.ctx.common.issues)));return it(t,{code:Xe.invalid_union,unionErrors:r}),st}));{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=n.map((e=>new Qe(e)));return it(t,{code:Xe.invalid_union,unionErrors:i}),st}}get options(){return this._def.options}}Qt.create=(e,t)=>new Qt({options:e,typeName:kr.ZodUnion,..._t(t)});const er=e=>e instanceof lr?er(e.schema):e instanceof mr?er(e.innerType()):e instanceof cr?[e.value]:e instanceof hr?e.options:e instanceof pr?Ge.objectValues(e.enum):e instanceof br?er(e._def.innerType):e instanceof Ht?[void 0]:e instanceof Vt?[null]:e instanceof gr?[void 0,...er(e.unwrap())]:e instanceof yr?[null,...er(e.unwrap())]:e instanceof Dr||e instanceof Or?er(e.unwrap()):e instanceof vr?er(e._def.innerType):[];class tr extends wt{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Ke.object)return it(t,{code:Xe.invalid_type,expected:Ke.object,received:t.parsedType}),st;const 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}):(it(t,{code:Xe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),st)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=er(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,r)}}return new tr({typeName:kr.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._t(r)})}}function rr(e,t){const r=Ye(e),n=Ye(t);if(e===t)return{valid:!0,data:e};if(r===Ke.object&&n===Ke.object){const r=Ge.objectKeys(t),n=Ge.objectKeys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const r of n){const n=rr(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===Ke.array&&n===Ke.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n{if(lt(e)||lt(n))return st;const i=rr(e.value,n.value);return i.valid?((ct(e)||ct(n))&&t.dirty(),{status:t.value,value:i.data}):(it(r,{code:Xe.invalid_intersection_types}),st)};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}))}}nr.create=(e,t,r)=>new nr({left:e,right:t,typeName:kr.ZodIntersection,..._t(r)});class ir extends wt{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ke.array)return it(r,{code:Xe.invalid_type,expected:Ke.array,received:r.parsedType}),st;if(r.data.lengththis._def.items.length&&(it(r,{code:Xe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new bt(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>at.mergeArray(t,e))):at.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ir({...this._def,rest:e})}}ir.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ir({items:e,typeName:kr.ZodTuple,rest:null,..._t(t)})};class ar extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ke.object)return it(r,{code:Xe.invalid_type,expected:Ke.object,received:r.parsedType}),st;const n=[],i=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:i._parse(new bt(r,e,r.path,e)),value:a._parse(new bt(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?at.mergeObjectAsync(t,n):at.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ar(t instanceof wt?{keyType:e,valueType:t,typeName:kr.ZodRecord,..._t(r)}:{keyType:Rt.create(),valueType:e,typeName:kr.ZodRecord,..._t(t)})}}class sr extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ke.map)return it(r,{code:Xe.invalid_type,expected:Ke.map,received:r.parsedType}),st;const n=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map((([e,t],a)=>({key:n._parse(new bt(r,e,r.path,[a,"key"])),value:i._parse(new bt(r,t,r.path,[a,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of a){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return st;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of a){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return st;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}sr.create=(e,t,r)=>new sr({valueType:t,keyType:e,typeName:kr.ZodMap,..._t(r)});class or extends wt{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ke.set)return it(r,{code:Xe.invalid_type,expected:Ke.set,received:r.parsedType}),st;const n=this._def;null!==n.minSize&&r.data.sizen.maxSize.value&&(it(r,{code:Xe.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const i=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return st;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const s=[...r.data.values()].map(((e,t)=>i._parse(new bt(r,e,r.path,t))));return r.common.async?Promise.all(s).then((e=>a(e))):a(s)}min(e,t){return new or({...this._def,minSize:{value:e,message:mt.toString(t)}})}max(e,t){return new or({...this._def,maxSize:{value:e,message:mt.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}or.create=(e,t)=>new or({valueType:e,minSize:null,maxSize:null,typeName:kr.ZodSet,..._t(t)});class ur extends wt{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Ke.function)return it(t,{code:Xe.invalid_type,expected:Ke.function,received:t.parsedType}),st;function r(e,r){return nt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,rt(),et].filter((e=>!!e)),issueData:{code:Xe.invalid_arguments,argumentsError:r}})}function n(e,r){return nt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,rt(),et].filter((e=>!!e)),issueData:{code:Xe.invalid_return_type,returnTypeError:r}})}const i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof fr){const e=this;return ut((async function(...t){const s=new Qe([]),o=await e._def.args.parseAsync(t,i).catch((e=>{throw s.addIssue(r(t,e)),s})),u=await Reflect.apply(a,this,o);return await e._def.returns._def.type.parseAsync(u,i).catch((e=>{throw s.addIssue(n(u,e)),s}))}))}{const e=this;return ut((function(...t){const s=e._def.args.safeParse(t,i);if(!s.success)throw new Qe([r(t,s.error)]);const o=Reflect.apply(a,this,s.data),u=e._def.returns.safeParse(o,i);if(!u.success)throw new Qe([n(o,u.error)]);return u.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ur({...this._def,args:ir.create(e).rest(Wt.create())})}returns(e){return new ur({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ur({args:e||ir.create([]).rest(Wt.create()),returns:t||Wt.create(),typeName:kr.ZodFunction,..._t(r)})}}class lr extends wt{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}lr.create=(e,t)=>new lr({getter:e,typeName:kr.ZodLazy,..._t(t)});class cr extends wt{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return it(t,{received:t.data,code:Xe.invalid_literal,expected:this._def.value}),st}return{status:"valid",value:e.data}}get value(){return this._def.value}}function dr(e,t){return new hr({values:e,typeName:kr.ZodEnum,..._t(t)})}cr.create=(e,t)=>new cr({value:e,typeName:kr.ZodLiteral,..._t(t)});class hr extends wt{constructor(){super(...arguments),gt.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return it(t,{expected:Ge.joinValues(r),received:t.parsedType,code:Xe.invalid_type}),st}if(pt(this,gt)||ft(this,gt,new Set(this._def.values)),!pt(this,gt).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return it(t,{received:t.data,code:Xe.invalid_enum_value,options:r}),st}return ut(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return hr.create(e,{...this._def,...t})}exclude(e,t=this._def){return hr.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}gt=new WeakMap,hr.create=dr;class pr extends wt{constructor(){super(...arguments),yt.set(this,void 0)}_parse(e){const t=Ge.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ke.string&&r.parsedType!==Ke.number){const e=Ge.objectValues(t);return it(r,{expected:Ge.joinValues(e),received:r.parsedType,code:Xe.invalid_type}),st}if(pt(this,yt)||ft(this,yt,new Set(Ge.getValidEnumValues(this._def.values))),!pt(this,yt).has(e.data)){const e=Ge.objectValues(t);return it(r,{received:r.data,code:Xe.invalid_enum_value,options:e}),st}return ut(e.data)}get enum(){return this._def.values}}yt=new WeakMap,pr.create=(e,t)=>new pr({values:e,typeName:kr.ZodNativeEnum,..._t(t)});class fr extends wt{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Ke.promise&&!1===t.common.async)return it(t,{code:Xe.invalid_type,expected:Ke.promise,received:t.parsedType}),st;const r=t.parsedType===Ke.promise?t.data:Promise.resolve(t.data);return ut(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}fr.create=(e,t)=>new fr({type:e,typeName:kr.ZodPromise,..._t(t)});class mr extends wt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===kr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{it(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return st;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?st:"dirty"===n.status||"dirty"===t.value?ot(n.value):n}));{if("aborted"===t.value)return st;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?st:"dirty"===n.status||"dirty"===t.value?ot(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?st:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?st:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!dt(e))return e;const a=n.transform(e.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>dt(e)?Promise.resolve(n.transform(e.value,i)).then((e=>({status:t.value,value:e}))):e))}Ge.assertNever(n)}}mr.create=(e,t,r)=>new mr({schema:e,typeName:kr.ZodEffects,effect:t,..._t(r)}),mr.createWithPreprocess=(e,t,r)=>new mr({schema:t,effect:{type:"preprocess",transform:e},typeName:kr.ZodEffects,..._t(r)});class gr extends wt{_parse(e){return this._getType(e)===Ke.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gr.create=(e,t)=>new gr({innerType:e,typeName:kr.ZodOptional,..._t(t)});class yr extends wt{_parse(e){return this._getType(e)===Ke.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}yr.create=(e,t)=>new yr({innerType:e,typeName:kr.ZodNullable,..._t(t)});class br extends wt{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Ke.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}br.create=(e,t)=>new br({innerType:e,typeName:kr.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,..._t(t)});class vr extends wt{_parse(e){const{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 ht(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Qe(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new Qe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}vr.create=(e,t)=>new vr({innerType:e,typeName:kr.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,..._t(t)});class _r extends wt{_parse(e){if(this._getType(e)!==Ke.nan){const t=this._getOrReturnCtx(e);return it(t,{code:Xe.invalid_type,expected:Ke.nan,received:t.parsedType}),st}return{status:"valid",value:e.data}}}_r.create=e=>new _r({typeName:kr.ZodNaN,..._t(e)});const wr=Symbol("zod_brand");class Dr extends wt{_parse(e){const{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 Er extends wt{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?st:"dirty"===e.status?(t.dirty(),ot(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?st:"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 Er({in:e,out:t,typeName:kr.ZodPipeline})}}class Or extends wt{_parse(e){const t=this._def.innerType._parse(e),r=e=>(dt(e)&&(e.value=Object.freeze(e.value)),e);return ht(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function Cr(e,t={},r){return e?qt.create().superRefine(((n,i)=>{var a,s;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(s=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===s||s,u="string"==typeof e?{message:e}:e;i.addIssue({code:"custom",...u,fatal:o})}})):qt.create()}Or.create=(e,t)=>new Or({innerType:e,typeName:kr.ZodReadonly,..._t(t)});const xr={object:Xt.lazycreate};var kr;!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"}(kr||(kr={}));const jr=Rt.create,Ar=Lt.create,Sr=_r.create,Pr=Bt.create,Ir=Ut.create,Tr=zt.create,Fr=Zt.create,Nr=Ht.create,$r=Vt.create,Rr=qt.create,Mr=Wt.create,Lr=Gt.create,Br=Jt.create,Ur=Kt.create,zr=Xt.create,Zr=Xt.strictCreate,Hr=Qt.create,Vr=tr.create,qr=nr.create,Wr=ir.create,Gr=ar.create,Jr=sr.create,Kr=or.create,Yr=ur.create,Xr=lr.create,Qr=cr.create,en=hr.create,tn=pr.create,rn=fr.create,nn=mr.create,an=gr.create,sn=yr.create,on=mr.createWithPreprocess,un=Er.create,ln={string:e=>Rt.create({...e,coerce:!0}),number:e=>Lt.create({...e,coerce:!0}),boolean:e=>Ut.create({...e,coerce:!0}),bigint:e=>Bt.create({...e,coerce:!0}),date:e=>zt.create({...e,coerce:!0})},cn=st;var dn,hn,pn,fn,mn,gn,yn=Object.freeze({__proto__:null,defaultErrorMap:et,setErrorMap:function(e){tt=e},getErrorMap:rt,makeIssue:nt,EMPTY_PATH:[],addIssueToContext:it,ParseStatus:at,INVALID:st,DIRTY:ot,OK:ut,isAborted:lt,isDirty:ct,isValid:dt,isAsync:ht,get util(){return Ge},get objectUtil(){return Je},ZodParsedType:Ke,getParsedType:Ye,ZodType:wt,datetimeRegex:$t,ZodString:Rt,ZodNumber:Lt,ZodBigInt:Bt,ZodBoolean:Ut,ZodDate:zt,ZodSymbol:Zt,ZodUndefined:Ht,ZodNull:Vt,ZodAny:qt,ZodUnknown:Wt,ZodNever:Gt,ZodVoid:Jt,ZodArray:Kt,ZodObject:Xt,ZodUnion:Qt,ZodDiscriminatedUnion:tr,ZodIntersection:nr,ZodTuple:ir,ZodRecord:ar,ZodMap:sr,ZodSet:or,ZodFunction:ur,ZodLazy:lr,ZodLiteral:cr,ZodEnum:hr,ZodNativeEnum:pr,ZodPromise:fr,ZodEffects:mr,ZodTransformer:mr,ZodOptional:gr,ZodNullable:yr,ZodDefault:br,ZodCatch:vr,ZodNaN:_r,BRAND:wr,ZodBranded:Dr,ZodPipeline:Er,ZodReadonly:Or,custom:Cr,Schema:wt,ZodSchema:wt,late:xr,get ZodFirstPartyTypeKind(){return kr},coerce:ln,any:Rr,array:Ur,bigint:Pr,boolean:Ir,date:Tr,discriminatedUnion:Vr,effect:nn,enum:en,function:Yr,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Cr((t=>t instanceof e),t),intersection:qr,lazy:Xr,literal:Qr,map:Jr,nan:Sr,nativeEnum:tn,never:Lr,null:$r,nullable:sn,number:Ar,object:zr,oboolean:()=>Ir().optional(),onumber:()=>Ar().optional(),optional:an,ostring:()=>jr().optional(),pipeline:un,preprocess:on,promise:rn,record:Gr,set:Kr,strictObject:Zr,string:jr,symbol:Fr,transformer:nn,tuple:Wr,undefined:Nr,union:Hr,unknown:Mr,void:Br,NEVER:cn,ZodIssueCode:Xe,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:Qe}),bn={exports:{}},vn={};function _n(){return pn||(pn=1,e=vn,t=function(){if(hn)return dn;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return hn=1,dn=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=i,r=s)}return t},dn}(),e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;inew Promise(((a,s)=>{i={onFailedAttempt:()=>{},retries:10,...i};const o=e.operation(i);o.attempt((async e=>{try{a(await n(e))}catch(n){if(!(n instanceof Error))return void s(new TypeError(`Non-error was thrown: "${n}". You should only throw errors.`));if(n instanceof r)o.stop(),s(n.originalError);else if(n instanceof TypeError&&(u=n.message,!t.includes(u)))o.stop(),s(n);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(n,e,i);try{await i.onFailedAttempt(n)}catch(e){return void s(e)}o.retry(n)||s(o.mainError())}}var u}))}));return bn.exports=n,bn.exports.default=n,bn.exports.AbortError=r,bn.exports}(),En=B(Dn),On=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Cn(e){return"string"==typeof e&&On.test(e)}for(var xn,kn=[],jn=0;jn<256;++jn)kn.push((jn+256).toString(16).slice(1));var An=new Uint8Array(16);function Sn(){if(!xn&&!(xn="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return xn(An)}var Pn={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function In(e,t,r){if(Pn.randomUUID&&!t&&!e)return Pn.randomUUID();var n=(e=e||{}).random||(e.rng||Sn)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return(kn[e[t+0]]+kn[e[t+1]]+kn[e[t+2]]+kn[e[t+3]]+"-"+kn[e[t+4]]+kn[e[t+5]]+"-"+kn[e[t+6]]+kn[e[t+7]]+"-"+kn[e[t+8]]+kn[e[t+9]]+"-"+kn[e[t+10]]+kn[e[t+11]]+kn[e[t+12]]+kn[e[t+13]]+kn[e[t+14]]+kn[e[t+15]]).toLowerCase()}(n)}const Tn=Symbol.for("ls:tracing_async_local_storage"),Fn=new class{getStore(){}run(e,t){return t()}};const Nn=new class{getInstance(){return globalThis[Tn]??Fn}initializeGlobalInstance(e){void 0===globalThis[Tn]&&(globalThis[Tn]=e)}};function $n(e){return"function"==typeof e&&"langsmith:traceable"in e} /*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017-2022 Joachim Wester * MIT licensed */const Rn=Object.prototype.hasOwnProperty;function Mn(e,t){return Rn.call(e,t)}function Ln(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Bn(e){let t=0;const r=e.length;let n;for(;t=48&&n<=57))return!1;t++}return!0}function Un(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function zn(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==s[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===o&&(void 0===c[u]?o=s.slice(0,d).join("/"):d==h-1&&(o=t.path),void 0!==o&&l(t,0,e,o)),d++,Array.isArray(c)){if("-"===u)u=c.length;else{if(r&&!Bn(u))throw new Vn("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,t,e);Bn(u)&&(u=~~u)}if(d>=h){if(r&&"add"===t.op&&u>c.length)throw new Vn("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);const n=Jn[t.op].call(t,c,u,e);if(!1===n.test)throw new Vn("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return n}}else if(d>=h){const r=qn[t.op].call(t,c,u,e);if(!1===r.test)throw new Vn("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return r}if(c=c[u],r&&d0)throw new Vn('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new Vn("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new Vn("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&zn(e.value))throw new Vn("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var i=e.path.split("/").length,a=n.split("/").length;if(i!==a+1&&i!==a)throw new Vn("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 Vn("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 s=function(e,t,r){try{if(!Array.isArray(e))throw new Vn("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Xn(Ln(t),Ln(e),r||!0);else{r=r||Qn;for(var n=0;n{if("string"!=typeof n&&!Array.isArray(n))throw new TypeError("Expected the input to be `string | string[]`");if(i={pascalCase:!1,preserveConsecutiveUppercase:!1,...i},0===(n=Array.isArray(n)?n.map((e=>e.trim())).filter((e=>e.length)).join("-"):n.trim()).length)return"";const u=!1===i.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(i.locale),l=!1===i.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(i.locale);if(1===n.length)return i.pascalCase?l(n):u(n);return n!==u(n)&&(n=((r,n,i)=>{let a=!1,s=!1,o=!1;for(let u=0;u(r.lastIndex=0,e.replace(r,(e=>t(e)))))(n,u):u(n),i.pascalCase&&(n=l(n.charAt(0))+n.slice(1)),((e,t)=>(s.lastIndex=0,o.lastIndex=0,e.replace(s,((e,r)=>t(r))).replace(o,(e=>t(e)))))(n,l)};ni.exports=u,ni.exports.default=u,ni.exports}();class li{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}constructor(e,...t){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}),this.lc_kwargs=e||{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof li||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce(((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e)),{});for(let n=Object.getPrototypeOf(this);n;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n,"lc_aliases",this)),Object.assign(t,Reflect.get(n,"lc_secrets",this)),Object.assign(r,Reflect.get(n,"lc_attributes",this));return Object.keys(t).forEach((e=>{let t=this,n=r;const[i,...a]=e.split(".").reverse();for(const e of a.reverse()){if(!(e in t)||void 0===t[e])return;e in n&&void 0!==n[e]||("object"==typeof t[e]&&null!=t[e]?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&void 0!==t[i]&&(n[i]=n[i]||t[i])})),{lc:1,type:"constructor",id:this.lc_id,kwargs:ai(Object.keys(t).length?oi(r,t):r,ii,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}const ci=()=>"undefined"!=typeof Deno,di=()=>{let e;return e="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||ci()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":ci()?"deno":"other":"node",e};let hi;async function pi(){if(void 0===hi){const e=di();hi={library:"langchain-js",runtime:e}}return hi}function fi(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}class mi{}class gi extends mi{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,ui(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"===fi("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 li.prototype.toJSON.call(this)}toJSONNotImplemented(){return li.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends gi{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:In()}),Object.assign(this,e)}}}}function yi(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function bi(e){return"function"==typeof e._addRunToRunMap}class vi extends gi{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?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const t=function(e,t,r){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){const 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){const 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){const t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,a,s,o){const u=this._getExecutionOrder(n),l=Date.now(),c=s?{...i,metadata:s}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:c??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,i,a,s,o){const u=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,n,i,a,s,o);return await(this.onRunCreate?.(u)),await(this.onLLMStart?.(u)),u}_createRunForChatModelStart(e,t,r,n,i,a,s,o){const u=this._getExecutionOrder(n),l=Date.now(),c=s?{...i,metadata:s}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:c??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,i,a,s,o){const u=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,n,i,a,s,o);return await(this.onRunCreate?.(u)),await(this.onLLMStart?.(u)),u}async handleLLMEnd(e,t){const r=this.runMap.get(t);if(!r||"llm"!==r?.run_type)throw new 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){const r=this.runMap.get(t);if(!r||"llm"!==r?.run_type)throw new 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,a,s,o){const u=this._getExecutionOrder(n),l=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,n,i,a,s,o){const u=this.runMap.get(r)??this._createRunForChainStart(e,t,r,n,i,a,s,o);return await(this.onRunCreate?.(u)),await(this.onChainStart?.(u)),u}async handleChainEnd(e,t,r,n,i){const a=this.runMap.get(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=yi(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),void 0!==i?.inputs&&(a.inputs=yi(i.inputs,"input")),await(this.onChainEnd?.(a)),await this._endTrace(a),a}async handleChainError(e,t,r,n,i){const a=this.runMap.get(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),void 0!==i?.inputs&&(a.inputs=yi(i.inputs,"input")),await(this.onChainError?.(a)),await this._endTrace(a),a}_createRunForToolStart(e,t,r,n,i,a,s){const o=this._getExecutionOrder(n),u=Date.now(),l={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:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,n,i,a,s){const o=this.runMap.get(r)??this._createRunForToolStart(e,t,r,n,i,a,s);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)throw new 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){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)throw new 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){const r=this.runMap.get(t);if(!r||"chain"!==r?.run_type)return;const 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){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(r)))}_createRunForRetrieverStart(e,t,r,n,i,a,s){const o=this._getExecutionOrder(n),u=Date.now(),l={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:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,n,i,a,s){const o=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,n,i,a,s);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)throw new 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){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)throw new 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){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(r)))}async handleLLMNewToken(e,t,r,n,i,a){const s=this.runMap.get(r);if(!s||"llm"!==s?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await(this.onLLMNewToken?.(s,e,{chunk:a?.chunk})),s}}var _i=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;for(var wi,Di=[],Ei=0;Ei<256;++Ei)Di.push((Ei+256).toString(16).slice(1));var Oi=new Uint8Array(16);function Ci(){if(!wi&&!(wi="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return wi(Oi)}var xi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ki(e,t,r){if(xi.randomUUID&&!t&&!e)return xi.randomUUID();var n=(e=e||{}).random||(e.rng||Ci)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return(Di[e[t+0]]+Di[e[t+1]]+Di[e[t+2]]+Di[e[t+3]]+"-"+Di[e[t+4]]+Di[e[t+5]]+"-"+Di[e[t+6]]+Di[e[t+7]]+"-"+Di[e[t+8]]+Di[e[t+9]]+"-"+Di[e[t+10]]+Di[e[t+11]]+Di[e[t+12]]+Di[e[t+13]]+Di[e[t+14]]+Di[e[t+15]]).toLowerCase()}(n)}var ji,Ai={},Si={exports:{}};var Pi,Ii,Ti,Fi={exports:{}};function Ni(){return Ii?Pi:(Ii=1,Pi=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e}))))))}var $i,Ri,Mi,Li={},Bi={};function Ui(){if(Ri)return Li;Ri=1,Object.defineProperty(Li,"__esModule",{value:!0});const e=($i||($i=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.default=function(e,t,r){let n=0,i=e.length;for(;i>0;){const a=i/2|0;let s=n+a;r(e[s],t)<=0?(n=++s,i-=a+1):i=a}return n}),Bi);return Li.default=class{constructor(){this._queue=[]}enqueue(t,r){const n={priority:(r=Object.assign({priority:0},r)).priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority)return void this._queue.push(n);const i=e.default(this._queue,n,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,n)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}},Li}var zi=function(){if(Mi)return Ai;Mi=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=(ji||(ji=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,n,a,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new i(n,a||e,s),u=r?r+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],o]:e._events[u].push(o):(e._events[u]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);inew Promise(((a,s)=>{if("number"!=typeof n||n<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(n===1/0)return void a(r);const o=setTimeout((()=>{if("function"==typeof i){try{a(i())}catch(e){s(e)}return}const e=i instanceof Error?i:new t("string"==typeof i?i:`Promise timed out after ${n} milliseconds`);"function"==typeof r.cancel&&r.cancel(),s(e)}),n);e(r.then(a,s),(()=>{clearTimeout(o)}))}));return Fi.exports=r,Fi.exports.default=r,Fi.exports.TimeoutError=t,Fi.exports}(),r=Ui(),n=()=>{},i=new t.TimeoutError;return Ai.default=class extends e{constructor(e){var t,i,a,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(i=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==i?i:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(a=e.interval)||void 0===a?void 0:a.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise(((n,a)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===r.timeout?e():t.default(Promise.resolve(e()),void 0===r.timeout?this._timeout:r.timeout,(()=>{(void 0===r.throwOnTimeout?this._throwOnTimeout:r.throwOnTimeout)&&a(i)}));n(await s)}catch(e){a(e)}this._next()}),r),this._tryToStartAnother(),this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}},Ai}(),Zi=B(zi);const Hi=(...e)=>fetch(...e),Vi=Symbol.for("ls:fetch_implementation"),qi=()=>globalThis[Vi]??Hi,Wi=[400,401,403,404,405,406,407,408],Gi=[409];let Ji,Ki=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,this.queue="default"in Zi?new Zi.default({concurrency:this.maxConcurrency}):new Zi({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add((()=>En((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response,n=t?.status;if(n){if(Wi.includes(+n))throw e;if(Gi.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(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>qi()(...e).then((e=>e.ok?e:Promise.reject(e)))))}};function Yi(e){return"function"==typeof e?._getType}function Xi(e){const 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}const Qi=()=>"undefined"!=typeof Deno,ea=()=>Ji||(Ji="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||Qi()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":Qi()?"deno":"other":"node",Ji);let ta,ra;async function na(){if(void 0===ta){const e=ea(),t=function(){if(void 0!==ra)return ra;const e=["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"],t={};for(const r of e){const e=aa(r);void 0!==e&&(t[r]=e)}return ra=t,t}();ta={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Fo,...t}}return ta}function ia(){const e=function(){try{return"undefined"!=typeof process&&process.env?Object.entries(process.env).reduce(((e,[t,r])=>(e[t]=String(r),e)),{}):void 0}catch(e){return}}()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION"];for(const[n,i]of Object.entries(e))!n.startsWith("LANGCHAIN_")||"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 aa(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function sa(e){return aa(`LANGSMITH_${e}`)||aa(`LANGCHAIN_${e}`)}function oa(e,t){if("string"!=typeof(r=e)||!_i.test(r)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}var r;return e}const ua={};function la(e){ua[e]||(ua[e]=!0)}var ca,da,ha,pa,fa,ma,ga,ya,ba,va,_a,wa,Da,Ea,Oa,Ca,xa,ka,ja,Aa,Sa,Pa,Ia,Ta,Fa,Na,$a,Ra,Ma,La,Ba,Ua,za,Za,Ha,Va,qa,Wa,Ga,Ja,Ka,Ya,Xa,Qa,es,ts,rs,ns,is,as,ss,os,us,ls,cs,ds,hs,ps,fs,ms,gs,ys,bs,vs,_s,ws,Ds,Es,Os,Cs,xs,ks,js,As,Ss,Ps,Is,Ts,Fs,Ns,$s,Rs,Ms,Ls,Bs,Us,zs,Zs,Hs,Vs={exports:{}};function qs(){if(da)return ca;da=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return ca={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function Ws(){if(pa)return ha;pa=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>{}:()=>{};return ha=e}function Gs(){return fa||(fa=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=qs(),a=Ws(),s=(t=e.exports={}).re=[],o=t.safeRe=[],u=t.src=[],l=t.t={};let c=0;const d="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",i],[d,n]],p=(e,t,r)=>{const n=(e=>{for(const[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),i=c++;a(e,i,t),l[e]=i,u[i]=t,s[i]=new RegExp(t,r?"g":void 0),o[i]=new RegExp(n,r?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),p("MAINVERSION",`(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${u[l.NUMERICIDENTIFIER]}|${u[l.NONNUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${u[l.NUMERICIDENTIFIERLOOSE]}|${u[l.NONNUMERICIDENTIFIER]})`),p("PRERELEASE",`(?:-(${u[l.PRERELEASEIDENTIFIER]}(?:\\.${u[l.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${u[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[l.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${d}+`),p("BUILD",`(?:\\+(${u[l.BUILDIDENTIFIER]}(?:\\.${u[l.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${u[l.MAINVERSION]}${u[l.PRERELEASE]}?${u[l.BUILD]}?`),p("FULL",`^${u[l.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${u[l.MAINVERSIONLOOSE]}${u[l.PRERELEASELOOSE]}?${u[l.BUILD]}?`),p("LOOSE",`^${u[l.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${u[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${u[l.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:${u[l.PRERELEASE]})?${u[l.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:${u[l.PRERELEASELOOSE]})?${u[l.BUILD]}?)?)?`),p("XRANGE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),p("COERCE",`${u[l.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",u[l.COERCEPLAIN]+`(?:${u[l.PRERELEASE]})?`+`(?:${u[l.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",u[l.COERCE],!0),p("COERCERTLFULL",u[l.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${u[l.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",p("TILDE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${u[l.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",p("CARET",`^${u[l.LONECARET]}${u[l.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${u[l.LONECARET]}${u[l.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${u[l.GTLT]}\\s*(${u[l.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]}|${u[l.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${u[l.XRANGEPLAIN]})\\s+-\\s+(${u[l.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${u[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[l.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(Vs,Vs.exports)),Vs.exports}function Js(){if(ga)return ma;ga=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return ma=r=>r?"object"!=typeof r?e:r:t}function Ks(){if(ba)return ya;ba=1;const e=/^[0-9]+$/,t=(t,r)=>{const n=e.test(t),i=e.test(r);return n&&i&&(t=+t,r=+r),t===r?0:n&&!i?-1:i&&!n?1:tt(r,e)}}function Ys(){if(_a)return va;_a=1;const e=Ws(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=qs(),{safeRe:n,t:i}=Gs(),a=Js(),{compareIdentifiers:s}=Ks();class o{constructor(s,u){if(u=a(u),s instanceof o){if(s.loose===!!u.loose&&s.includePrerelease===!!u.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const l=s.trim().match(u.loose?n[i.LOOSE]:n[i.FULL]);if(!l)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");l[4]?this.prerelease=l[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return va=o}function Xs(){if(Da)return wa;Da=1;const e=Ys();return wa=(t,r,n=!1)=>{if(t instanceof e)return t;try{return new e(t,r)}catch(e){if(!n)return null;throw e}}}function Qs(){if(Ba)return La;Ba=1;const e=Ys();return La=(t,r,n)=>new e(t,n).compare(new e(r,n))}function eo(){if(qa)return Va;qa=1;const e=Ys();return Va=(t,r,n)=>{const i=new e(t,n),a=new e(r,n);return i.compare(a)||i.compareBuild(a)}}function to(){if(Xa)return Ya;Xa=1;const e=Qs();return Ya=(t,r,n)=>e(t,r,n)>0}function ro(){if(es)return Qa;es=1;const e=Qs();return Qa=(t,r,n)=>e(t,r,n)<0}function no(){if(rs)return ts;rs=1;const e=Qs();return ts=(t,r,n)=>0===e(t,r,n)}function io(){if(is)return ns;is=1;const e=Qs();return ns=(t,r,n)=>0!==e(t,r,n)}function ao(){if(ss)return as;ss=1;const e=Qs();return as=(t,r,n)=>e(t,r,n)>=0}function so(){if(us)return os;us=1;const e=Qs();return os=(t,r,n)=>e(t,r,n)<=0}function oo(){if(cs)return ls;cs=1;const e=no(),t=io(),r=to(),n=ao(),i=ro(),a=so();return ls=(s,o,u,l)=>{switch(o){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof u&&(u=u.version),s===u;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof u&&(u=u.version),s!==u;case"":case"=":case"==":return e(s,u,l);case"!=":return t(s,u,l);case">":return r(s,u,l);case">=":return n(s,u,l);case"<":return i(s,u,l);case"<=":return a(s,u,l);default:throw new TypeError(`Invalid operator: ${o}`)}}}function uo(){if(gs)return ms;gs=1;const e=/\s+/g;class t{constructor(r,a){if(a=n(a),r instanceof t)return r.loose===!!a.loose&&r.includePrerelease===!!a.includePrerelease?r:new t(r.raw,a);if(r instanceof i)return this.raw=r.value,this.set=[[r]],this.formatted=void 0,this;if(this.options=a,this.loose=!!a.loose,this.includePrerelease=!!a.includePrerelease,this.raw=r.trim().replace(e," "),this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter((e=>!f(e[0]))),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&m(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+e,n=r.get(t);if(n)return n;const s=this.options.loose,m=s?o[u.HYPHENRANGELOOSE]:o[u.HYPHENRANGE];e=e.replace(m,k(this.options.includePrerelease)),a("hyphen replace",e),e=e.replace(o[u.COMPARATORTRIM],l),a("comparator trim",e),e=e.replace(o[u.TILDETRIM],c),a("tilde trim",e),e=e.replace(o[u.CARETTRIM],d),a("caret trim",e);let g=e.split(" ").map((e=>y(e,this.options))).join(" ").split(/\s+/).map((e=>x(e,this.options)));s&&(g=g.filter((e=>(a("loose invalid filter",e,this.options),!!e.match(o[u.COMPARATORLOOSE]))))),a("range list",g);const b=new Map,v=g.map((e=>new i(e,this.options)));for(const e of v){if(f(e))return[e];b.set(e.value,e)}b.size>1&&b.has("")&&b.delete("");const _=[...b.values()];return r.set(t,_),_}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some((t=>g(t,r)&&e.set.some((e=>g(e,r)&&t.every((t=>e.every((e=>t.intersects(e,r)))))))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(e){return!1}for(let t=0;t=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}})),n=Js(),i=lo(),a=Ws(),s=Ys(),{safeRe:o,t:u,comparatorTrimReplace:l,tildeTrimReplace:c,caretTrimReplace:d}=Gs(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=qs(),f=e=>"<0.0.0-0"===e.value,m=e=>""===e.value,g=(e,t)=>{let r=!0;const n=e.slice();let i=n.pop();for(;r&&n.length;)r=n.every((e=>i.intersects(e,t))),i=n.pop();return r},y=(e,t)=>(a("comp",e,t),e=w(e,t),a("caret",e),e=v(e,t),a("tildes",e),e=E(e,t),a("xrange",e),e=C(e,t),a("stars",e),e),b=e=>!e||"x"===e.toLowerCase()||"*"===e,v=(e,t)=>e.trim().split(/\s+/).map((e=>_(e,t))).join(" "),_=(e,t)=>{const r=t.loose?o[u.TILDELOOSE]:o[u.TILDE];return e.replace(r,((t,r,n,i,s)=>{let o;return a("tilde",e,t,r,n,i,s),b(r)?o="":b(n)?o=`>=${r}.0.0 <${+r+1}.0.0-0`:b(i)?o=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:s?(a("replaceTilde pr",s),o=`>=${r}.${n}.${i}-${s} <${r}.${+n+1}.0-0`):o=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,a("tilde return",o),o}))},w=(e,t)=>e.trim().split(/\s+/).map((e=>D(e,t))).join(" "),D=(e,t)=>{a("caret",e,t);const r=t.loose?o[u.CARETLOOSE]:o[u.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,i,s,o)=>{let u;return a("caret",e,t,r,i,s,o),b(r)?u="":b(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:b(s)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:o?(a("replaceCaret pr",o),u="0"===r?"0"===i?`>=${r}.${i}.${s}-${o} <${r}.${i}.${+s+1}-0`:`>=${r}.${i}.${s}-${o} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${s}-${o} <${+r+1}.0.0-0`):(a("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${s}${n} <${r}.${i}.${+s+1}-0`:`>=${r}.${i}.${s}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${s} <${+r+1}.0.0-0`),a("caret return",u),u}))},E=(e,t)=>(a("replaceXRanges",e,t),e.split(/\s+/).map((e=>O(e,t))).join(" ")),O=(e,t)=>{e=e.trim();const r=t.loose?o[u.XRANGELOOSE]:o[u.XRANGE];return e.replace(r,((r,n,i,s,o,u)=>{a("xRange",e,r,n,i,s,o,u);const l=b(i),c=l||b(s),d=c||b(o),h=d;return"="===n&&h&&(n=""),u=t.includePrerelease?"-0":"",l?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&h?(c&&(s=0),o=0,">"===n?(n=">=",c?(i=+i+1,s=0,o=0):(s=+s+1,o=0)):"<="===n&&(n="<",c?i=+i+1:s=+s+1),"<"===n&&(u="-0"),r=`${n+i}.${s}.${o}${u}`):c?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:d&&(r=`>=${i}.${s}.0${u} <${i}.${+s+1}.0-0`),a("xRange return",r),r}))},C=(e,t)=>(a("replaceStars",e,t),e.trim().replace(o[u.STAR],"")),x=(e,t)=>(a("replaceGTE0",e,t),e.trim().replace(o[t.includePrerelease?u.GTE0PRE:u.GTE0],"")),k=e=>(t,r,n,i,a,s,o,u,l,c,d,h)=>`${r=b(n)?"":b(i)?`>=${n}.0.0${e?"-0":""}`:b(a)?`>=${n}.${i}.0${e?"-0":""}`:s?`>=${r}`:`>=${r}${e?"-0":""}`} ${u=b(l)?"":b(c)?`<${+l+1}.0.0-0`:b(d)?`<${l}.${+c+1}.0-0`:h?`<=${l}.${c}.${d}-${h}`:e?`<${l}.${c}.${+d+1}-0`:`<=${u}`}`.trim(),j=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0};return ms}function lo(){if(bs)return ys;bs=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(n,i){if(i=r(i),n instanceof t){if(n.loose===!!i.loose)return n;n=n.value}n=n.trim().split(/\s+/).join(" "),s("comparator",n,i),this.options=i,this.loose=!!i.loose,this.parse(n),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const r=this.options.loose?n[i.COMPARATORLOOSE]:n[i.COMPARATOR],a=t.match(r);if(!a)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==a[1]?a[1]:"","="===this.operator&&(this.operator=""),a[2]?this.semver=new o(a[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new o(t,this.options)}catch(e){return!1}return a(t,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new u(e.value,n).test(this.value):""===e.operator?""===e.value||new u(this.value,n).test(e.semver):(!(n=r(n)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(a(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(a(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}ys=t;const r=Js(),{safeRe:n,t:i}=Gs(),a=oo(),s=Ws(),o=Ys(),u=uo();return ys}function co(){if(_s)return vs;_s=1;const e=uo();return vs=(t,r,n)=>{try{r=new e(r,n)}catch(e){return!1}return r.test(t)},vs}function ho(){if(Ss)return As;Ss=1;const e=uo();return As=(t,r)=>{try{return new e(t,r).range||"*"}catch(e){return null}},As}function po(){if(Is)return Ps;Is=1;const e=Ys(),t=lo(),{ANY:r}=t,n=uo(),i=co(),a=to(),s=ro(),o=so(),u=ao();return Ps=(l,c,d,h)=>{let p,f,m,g,y;switch(l=new e(l,h),c=new n(c,h),d){case">":p=a,f=o,m=s,g=">",y=">=";break;case"<":p=s,f=u,m=a,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(l,c,h))return!1;for(let e=0;e{e.semver===r&&(e=new t(">=0.0.0")),i=i||e,a=a||e,p(e.semver,i.semver,h)?i=e:m(e.semver,a.semver,h)&&(a=e)})),i.operator===g||i.operator===y)return!1;if((!a.operator||a.operator===g)&&f(l,a.semver))return!1;if(a.operator===y&&m(l,a.semver))return!1}return!0},Ps}var fo=function(){if(Hs)return Zs;Hs=1;const e=Gs(),t=qs(),r=Ys(),n=Ks(),i=Xs(),a=function(){if(Oa)return Ea;Oa=1;const e=Xs();return Ea=(t,r)=>{const n=e(t,r);return n?n.version:null}}(),s=function(){if(xa)return Ca;xa=1;const e=Xs();return Ca=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null}}(),o=function(){if(ja)return ka;ja=1;const e=Ys();return ka=(t,r,n,i,a)=>{"string"==typeof n&&(a=i,i=n,n=void 0);try{return new e(t instanceof e?t.version:t,n).inc(r,i,a).version}catch(e){return null}}}(),u=function(){if(Sa)return Aa;Sa=1;const e=Xs();return Aa=(t,r)=>{const n=e(t,null,!0),i=e(r,null,!0),a=n.compare(i);if(0===a)return null;const s=a>0,o=s?n:i,u=s?i:n,l=!!o.prerelease.length;if(u.prerelease.length&&!l)return u.patch||u.minor?o.patch?"patch":o.minor?"minor":"major":"major";const c=l?"pre":"";return n.major!==i.major?c+"major":n.minor!==i.minor?c+"minor":n.patch!==i.patch?c+"patch":"prerelease"}}(),l=function(){if(Ia)return Pa;Ia=1;const e=Ys();return Pa=(t,r)=>new e(t,r).major}(),c=function(){if(Fa)return Ta;Fa=1;const e=Ys();return Ta=(t,r)=>new e(t,r).minor}(),d=function(){if($a)return Na;$a=1;const e=Ys();return Na=(t,r)=>new e(t,r).patch}(),h=function(){if(Ma)return Ra;Ma=1;const e=Xs();return Ra=(t,r)=>{const n=e(t,r);return n&&n.prerelease.length?n.prerelease:null}}(),p=Qs(),f=function(){if(za)return Ua;za=1;const e=Qs();return Ua=(t,r,n)=>e(r,t,n)}(),m=function(){if(Ha)return Za;Ha=1;const e=Qs();return Za=(t,r)=>e(t,r,!0)}(),g=eo(),y=function(){if(Ga)return Wa;Ga=1;const e=eo();return Wa=(t,r)=>t.sort(((t,n)=>e(t,n,r)))}(),b=function(){if(Ka)return Ja;Ka=1;const e=eo();return Ja=(t,r)=>t.sort(((t,n)=>e(n,t,r)))}(),v=to(),_=ro(),w=no(),D=io(),E=ao(),O=so(),C=oo(),x=function(){if(hs)return ds;hs=1;const e=Ys(),t=Xs(),{safeRe:r,t:n}=Gs();return ds=(i,a)=>{if(i instanceof e)return i;if("number"==typeof i&&(i=String(i)),"string"!=typeof i)return null;let s=null;if((a=a||{}).rtl){const e=a.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let t;for(;(t=e.exec(i))&&(!s||s.index+s[0].length!==i.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=i.match(a.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);if(null===s)return null;const o=s[2],u=s[3]||"0",l=s[4]||"0",c=a.includePrerelease&&s[5]?`-${s[5]}`:"",d=a.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${o}.${u}.${l}${c}${d}`,a)},ds}(),k=lo(),j=uo(),A=co(),S=function(){if(Ds)return ws;Ds=1;const e=uo();return ws=(t,r)=>new e(t,r).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" "))),ws}(),P=function(){if(Os)return Es;Os=1;const e=Ys(),t=uo();return Es=(r,n,i)=>{let a=null,s=null,o=null;try{o=new t(n,i)}catch(e){return null}return r.forEach((t=>{o.test(t)&&(a&&-1!==s.compare(t)||(a=t,s=new e(a,i)))})),a},Es}(),I=function(){if(xs)return Cs;xs=1;const e=Ys(),t=uo();return Cs=(r,n,i)=>{let a=null,s=null,o=null;try{o=new t(n,i)}catch(e){return null}return r.forEach((t=>{o.test(t)&&(a&&1!==s.compare(t)||(a=t,s=new e(a,i)))})),a},Cs}(),T=function(){if(js)return ks;js=1;const e=Ys(),t=uo(),r=to();return ks=(n,i)=>{n=new t(n,i);let a=new e("0.0.0");if(n.test(a))return a;if(a=new e("0.0.0-0"),n.test(a))return a;a=null;for(let t=0;t{const n=new e(t.semver.version);switch(t.operator){case">":0===n.prerelease.length?n.patch++:n.prerelease.push(0),n.raw=n.format();case"":case">=":s&&!r(n,s)||(s=n);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!s||a&&!r(a,s)||(a=s)}return a&&n.test(a)?a:null},ks}(),F=ho(),N=po(),$=function(){if(Fs)return Ts;Fs=1;const e=po();return Ts=(t,r,n)=>e(t,r,">",n),Ts}(),R=function(){if($s)return Ns;$s=1;const e=po();return Ns=(t,r,n)=>e(t,r,"<",n),Ns}(),M=function(){if(Ms)return Rs;Ms=1;const e=uo();return Rs=(t,r,n)=>(t=new e(t,n),r=new e(r,n),t.intersects(r,n))}(),L=function(){if(Bs)return Ls;Bs=1;const e=co(),t=Qs();return Ls=(r,n,i)=>{const a=[];let s=null,o=null;const u=r.sort(((e,r)=>t(e,r,i)));for(const t of u)e(t,n,i)?(o=t,s||(s=t)):(o&&a.push([s,o]),o=null,s=null);s&&a.push([s,null]);const l=[];for(const[e,t]of a)e===t?l.push(e):t||e!==u[0]?t?e===u[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`):l.push("*");const c=l.join(" || "),d="string"==typeof n.raw?n.raw:String(n);return c.length=0.0.0-0")],s=[new t(">=0.0.0")],o=(e,t,o)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===r){if(1===t.length&&t[0].semver===r)return!0;e=o.includePrerelease?a:s}if(1===t.length&&t[0].semver===r){if(o.includePrerelease)return!0;t=s}const c=new Set;let d,h,p,f,m,g,y;for(const t of e)">"===t.operator||">="===t.operator?d=u(d,t,o):"<"===t.operator||"<="===t.operator?h=l(h,t,o):c.add(t.semver);if(c.size>1)return null;if(d&&h){if(p=i(d.semver,h.semver,o),p>0)return null;if(0===p&&(">="!==d.operator||"<="!==h.operator))return null}for(const e of c){if(d&&!n(e,String(d),o))return null;if(h&&!n(e,String(h),o))return null;for(const r of t)if(!n(e,String(r),o))return!1;return!0}let b=!(!h||o.includePrerelease||!h.semver.prerelease.length)&&h.semver,v=!(!d||o.includePrerelease||!d.semver.prerelease.length)&&d.semver;b&&1===b.prerelease.length&&"<"===h.operator&&0===b.prerelease[0]&&(b=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,d)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),">"===e.operator||">="===e.operator){if(f=u(d,e,o),f===e&&f!==d)return!1}else if(">="===d.operator&&!n(d.semver,String(e),o))return!1;if(h)if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),"<"===e.operator||"<="===e.operator){if(m=l(h,e,o),m===e&&m!==h)return!1}else if("<="===h.operator&&!n(h.semver,String(e),o))return!1;if(!e.operator&&(h||d)&&0!==p)return!1}return!(d&&g&&!h&&0!==p||h&&y&&!d&&0!==p||v||b)},u=(e,t,r)=>{if(!e)return t;const n=i(e.semver,t.semver,r);return n>0?e:n<0||">"===t.operator&&">="===e.operator?t:e},l=(e,t,r)=>{if(!e)return t;const n=i(e.semver,t.semver,r);return n<0?e:n>0||"<"===t.operator&&"<="===e.operator?t:e};return Us=(t,r,n={})=>{if(t===r)return!0;t=new e(t,n),r=new e(r,n);let i=!1;e:for(const e of t.set){for(const t of r.set){const r=o(e,t,n);if(i=i||null!==r,r)continue e}if(i)return!1}return!0}}();return Zs={parse:i,valid:a,clean:s,inc:o,diff:u,major:l,minor:c,patch:d,prerelease:h,compare:p,rcompare:f,compareLoose:m,compareBuild:g,sort:y,rsort:b,gt:v,lt:_,eq:w,neq:D,gte:E,lte:O,cmp:C,coerce:x,Comparator:k,Range:j,satisfies:A,toComparators:S,maxSatisfying:P,minSatisfying:I,minVersion:T,validRange:F,outside:N,gtr:$,ltr:R,intersects:M,simplifyRange:L,subset:B,SemVer:r,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers}}();function mo(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){const[r,i]=t.split("/",2);if(!r||!i)throw new Error(`Invalid identifier format: ${e}`);return[r,i,n]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}class go extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function yo(e,t,r){let n;if(e.ok)return void(r&&(n=await e.text()));n=await e.text();const i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;if(409===e.status)throw new go(i);throw new Error(i)}var bo="[...]",vo={result:"[Circular]"},_o=[],wo=[];function Do(e,t,r,n){var i;void 0===n&&(n={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),Oo(e,"",0,[],void 0,0,n);try{i=0===wo.length?JSON.stringify(e,t,r):JSON.stringify(e,function(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(wo.length>0)for(var n=0;ns.depthLimit)return void Eo(bo,e,t,i);if(void 0!==s.edgesLimit&&r+1>s.edgesLimit)return void Eo(bo,e,t,i);if(n.push(e),Array.isArray(e))for(o=0;o{const 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}))}function xo(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const ko=async e=>{if(429===e?.status){const 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 jo{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]})}get size(){return this.items.length}push(e){return new Promise((t=>{this.items.push([e,t])}))}pop(e){if(e<1)throw new Error("Number of items to pop off may not be less than 1.");const t=[];for(;t.lengthe[0])),()=>t.forEach((e=>e[1]()))]}}class Ao{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,"batchEndpointSupported",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new jo}),Object.defineProperty(this,"pendingAutoBatchedRunLimit",{enumerable:!0,configurable:!0,writable:!0,value:100}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchInitialDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"serverInfo",{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});const t=Ao.getDefaultClientConfig();this.tracingSampleRate=(()=>{const e=sa("TRACING_SAMPLING_RATE");if(void 0===e)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t})(),this.apiUrl=xo(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=xo(e.apiKey??t.apiKey),this.webUrl=xo(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??12e3,this.caller=new Ki(e.callerOptions??{}),this.batchIngestCaller=new Ki({...e.callerOptions??{},onFailedResponseHook:ko}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.pendingAutoBatchedRunLimit=e.pendingAutoBatchedRunLimit??this.pendingAutoBatchedRunLimit,this.fetchOptions=e.fetchOptions||{}}static getDefaultClientConfig(){const e=sa("API_KEY");return{apiUrl:sa("ENDPOINT")??"https://api.smith.langchain.com",apiKey:e,webUrl:void 0,hideInputs:"true"===sa("HIDE_INPUTS"),hideOutputs:"true"===sa("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${Fo}`};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){const 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){const r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`,i=await this.caller.call(qi(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yo(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;const i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(i));const a=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(qi(),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(s,`Failed to fetch ${e}`);const o=r?r(await s.json()):await s.json();if(0===o.length)break;if(yield o,o.length=0;){const[e,t]=this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);if(!e.length)return void t();try{await this.batchIngestRuns({runCreates:e.filter((e=>"create"===e.action)).map((e=>e.item)),runUpdates:e.filter((e=>"update"===e.action)).map((e=>e.item))})}finally{t()}}}async processRunOperation(e,t){const r=this.autoBatchTimeout;clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0;const n=this.autoBatchQueue.push(e);return(t||this.autoBatchQueue.size>this.pendingAutoBatchedRunLimit)&&await this.drainAutoBatchQueue().catch(console.error),this.autoBatchQueue.size>0&&(this.autoBatchTimeout=setTimeout((()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue().catch(console.error)}),r?this.autoBatchAggregationDelayMs:this.autoBatchInitialDelayMs)),n}async _getServerInfo(){const e=await qi()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yo(e,"get server info"),e.json()}async batchEndpointIsSupported(){try{this.serverInfo=await this._getServerInfo()}catch(e){return!1}return!0}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async createRun(e){if(!this._filterForSampling([e]).length)return;const t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const 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);const i=await Co([n]),a=await this.caller.call(qi(),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:Do(i[0]),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(a,"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){const e=r.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const 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}const i={post:this._filterForSampling(r),patch:this._filterForSampling(n,!0)};if(!i.post.length&&!i.patch.length)return;if(r=await Co(r),void 0===this.batchEndpointSupported&&(this.batchEndpointSupported=await this.batchEndpointIsSupported()),!this.batchEndpointSupported){this.autoBatchTracing=!1;for(const e of i.post)await this.createRun(e);for(const e of i.patch)void 0!==e.id&&await this.updateRun(e.id,e);return}const a=this.serverInfo?.batch_ingest_config?.size_limit_bytes??20971520,s={post:[],patch:[]};let o=0;for(const e of["post","patch"]){const t=e,r=i[t].reverse();let n=r.pop();for(;void 0!==n;){const e=Do(n);o>0&&o+e.length>a&&(await this._postBatchIngestRuns(Do(s)),o=0,s.post=[],s.patch=[]),o+=e.length,s[t].push(n),n=r.pop()}}(s.post.length>0||s.patch.length>0)&&await this._postBatchIngestRuns(Do(s))}async _postBatchIngestRuns(e){const t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call(qi(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(r,"batch create run",!0)}async updateRun(e,t){oa(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));const 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?void await this.processRunOperation({action:"update",item:r},!0):void this.processRunOperation({action:"update",item:r}).catch(console.error);const n={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(qi(),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,body:Do(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(i,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){oa(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;if(t.session_id)e=t.session_id;else if(r?.projectName)e=(await this.readProject({projectName:r?.projectName})).id;else if(r?.projectId)e=r?.projectId;else{e=(await this.readProject({projectName:sa("PROJECT")||"default"})).id}const n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const r of e)t.push(r);return t}(this.listRuns({id:e.child_run_ids})),r={},n={};t.sort(((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")));for(const e of t){if(null===e.parent_run_id||void 0===e.parent_run_id)throw new 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}e.child_runs=r[e.id]||[];for(const t in r)t!==e.id&&(n[t].child_runs=r[t]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:n,traceId:i,referenceExampleId:a,startTime:s,executionOrder:o,isRoot:u,runType:l,error:c,id:d,query:h,filter:p,traceFilter:f,treeFilter:m,limit:g,select:y}=e;let b=[];if(t&&(b=Array.isArray(t)?t:[t]),r){const e=Array.isArray(r)?r:[r],t=await Promise.all(e.map((e=>this.readProject({projectName:e}).then((e=>e.id)))));b.push(...t)}const v={session:b.length?b:null,run_type:l,reference_example:a,query:h,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:n,start_time:s?s.toISOString():null,error:c,id:d,limit:g,trace:i,select:y||["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"],is_root:u};let _=0;for await(const e of this._getCursorPaginatedList("/runs/query",v))if(g){if(_>=g)break;if(e.length+_>g){const t=e.slice(0,g-_);yield*t;break}_+=e.length,yield*e}else yield*e}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:o,endTime:u,error:l,query:c,filter:d,traceFilter:h,treeFilter:p,isRoot:f,dataSourceType:m}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map((e=>this.readProject({projectName:e}).then((e=>e.id)))))]);const y={id:e,trace:t,parent_run:r,run_type:n,session:g,reference_example:s,start_time:o,end_time:u,error:l,query:c,filter:d,trace_filter:h,tree_filter:p,is_root:f,data_source_type:m},b=Object.fromEntries(Object.entries(y).filter((([e,t])=>void 0!==t))),v=await this.caller.call(qi(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||ki()};oa(e);const n=await this.caller.call(qi(),`${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 new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){oa(e);const t=await this.caller.call(qi(),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(t,"unshare run",!0)}async readRunSharedLink(e){oa(e);const t=await this.caller.call(qi(),`${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}={}){const r=new URLSearchParams({share_token:e});if(void 0!==t)for(const e of t)r.append("id",e);oa(e);const n=await this.caller.call(qi(),`${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 new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}oa(e);const r=await this.caller.call(qi(),`${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 new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}const r={dataset_id:e};oa(e);const n=await this.caller.call(qi(),`${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){oa(e);const t=await this.caller.call(qi(),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(t,"unshare dataset",!0)}async readSharedDataset(e){oa(e);const t=await this.caller.call(qi(),`${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){const r={};t?.exampleIds&&(r.id=t.exampleIds);const n=new URLSearchParams;Object.entries(r).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>n.append(e,t))):n.append(e,t)}));const i=await this.caller.call(qi(),`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await i.json();if(!i.ok){if("detail"in a)throw new Error(`Failed to list shared examples.\nStatus: ${i.status}\nMessage: ${a.detail.join("\n")}`);throw new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`)}return a.map((e=>({...e,_hostUrl:this.getHostUrl()})))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:i=null,referenceDatasetId:a=null}){const s=n?"?upsert=true":"",o=`${this.apiUrl}/sessions${s}`,u=i||{};r&&(u.metadata=r);const l={name:e,extra:u,description:t};null!==a&&(l.reference_dataset_id=a);const c=await this.caller.call(qi(),o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(c,"create project");return await c.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:i=null,endTime:a=null}){const s=`${this.apiUrl}/sessions/${e}`;let o=i;n&&(o={...o||{},metadata:n});const u={name:t,extra:o,description:r,end_time:a?new Date(a).toISOString():null},l=await this.caller.call(qi(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(l,"update project");return await l.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)oa(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");n.append("name",t)}const i=await this.caller.call(qi(),`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const e=await i.json();return!!i.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n="/sessions";const i=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)oa(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");i.append("name",t)}void 0!==r&&i.append("include_stats",r.toString());const a=await this._get(n,i);let s;if(Array.isArray(a)){if(0===a.length)throw new Error(`Project[id=${e}, name=${t}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const 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 new Error("Must provide either datasetName or datasetId");const 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;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:n,referenceDatasetName:i,referenceFree:a,metadata:s}={}){const o=new URLSearchParams;if(void 0!==e)for(const t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==r&&o.append("name_contains",r),void 0!==n)o.append("reference_dataset",n);else if(void 0!==i){const e=await this.readDataset({datasetName:i});o.append("reference_dataset",e.id)}void 0!==a&&o.append("reference_free",a.toString()),void 0!==s&&o.append("metadata",JSON.stringify(s));for await(const e of this._getPaginated("/sessions",o))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");r=void 0===e?(await this.readProject({projectName:t})).id:e,oa(r);const n=await this.caller.call(qi(),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(n,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:i,dataType:a,name:s}){const o=`${this.apiUrl}/datasets/upload`,u=new FormData;u.append("file",e,t),r.forEach((e=>{u.append("input_keys",e)})),n.forEach((e=>{u.append("output_keys",e)})),i&&u.append("description",i),a&&u.append("data_type",a),s&&u.append("name",s);const l=await this.caller.call(qi(),o,{method:"POST",headers:this.headers,body:u,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(l,"upload CSV");return await l.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:i,metadata:a}={}){const s={name:e,description:t,extra:a?{metadata:a}:void 0};r&&(s.data_type=r),n&&(s.inputs_schema_definition=n),i&&(s.outputs_schema_definition=i);const o=await this.caller.call(qi(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(o,"create dataset");return await o.json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const n=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)oa(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide datasetName or datasetId");n.append("name",t)}const i=await this._get(r,n);let a;if(Array.isArray(i)){if(0===i.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);a=i[0]}else a=i;return a}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 new Error("Must provide either datasetName or datasetId");if(void 0!==i&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===i){i=(await this.readDataset({datasetName:t})).id}const a=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`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map((e=>JSON.parse(e)))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:i,metadata:a}={}){const s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(const e of r)s.append("id",e);void 0!==n&&s.append("name",n),void 0!==i&&s.append("name_contains",i),void 0!==a&&s.append("metadata",JSON.stringify(a));for await(const e of this._getPaginated("/datasets",s))yield*e}async updateDataset(e){const{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;oa(i);const a=await this.caller.call(qi(),`${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 yo(a,"update dataset"),await a.json()}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){n=(await this.readDataset({datasetName:t})).id}if(void 0===n)throw new Error("Must provide datasetName or datasetId");oa(n),r+=`/${n}`;const i=await this.caller.call(qi(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(i,`delete ${r}`),await i.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(!n&&!t)throw new Error("Must provide either datasetName or datasetId");if(n&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!n){n=(await this.readDataset({datasetName:t})).id}oa(n);const i={tag:r},a=await this.caller.call(qi(),`${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 yo(a,"index dataset"),await a.json()}async similarExamples(e,t,r,{filter:n}={}){const i={limit:r,inputs:e};void 0!==n&&(i.filter=n),oa(t);const a=await this.caller.call(qi(),`${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});await yo(a,"fetch similar examples");return(await a.json()).examples}async createExample(e,t,{datasetId:r,datasetName:n,createdAt:i,exampleId:a,metadata:s,split:o,sourceRunId:u}){let l=r;if(void 0===l&&void 0===n)throw new Error("Must provide either datasetName or datasetId");if(void 0!==l&&void 0!==n)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===l){l=(await this.readDataset({datasetName:n})).id}const c=i||new Date,d={dataset_id:l,inputs:e,outputs:t,created_at:c?.toISOString(),id:a,metadata:s,split:o,source_run_id:u},h=await this.caller.call(qi(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(h,"create example");return await h.json()}async createExamples(e){const{inputs:t,outputs:r,metadata:n,sourceRunIds:i,exampleIds:a,datasetId:s,datasetName:o}=e;let u=s;if(void 0===u&&void 0===o)throw new Error("Must provide either datasetName or datasetId");if(void 0!==u&&void 0!==o)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===u){const e=await this.readDataset({datasetName:o});u=e.id}const l=t.map(((t,s)=>({dataset_id:u,inputs:t,outputs:r?r[s]:void 0,metadata:n?n[s]:void 0,split:e.splits?e.splits[s]:void 0,id:a?a[s]:void 0,source_run_id:i?i[s]:void 0}))),c=await this.caller.call(qi(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(c,"create examples");return await c.json()}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const n=e.map((e=>Yi(e)?Xi(e):e)),i=Yi(t)?Xi(t):t;return this.createExample({input:n},{output:i},r)}async readExample(e){oa(e);const t=`/examples/${e}`;return await this._get(t)}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:i,inlineS3Urls:a,metadata:s,limit:o,offset:u,filter:l}={}){let c;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)c=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");c=(await this.readDataset({datasetName:t})).id}const d=new URLSearchParams({dataset:c}),h=n?"string"==typeof n?n:n?.toISOString():void 0;h&&d.append("as_of",h);const p=a??!0;if(d.append("inline_s3_urls",p.toString()),void 0!==r)for(const e of r)d.append("id",e);if(void 0!==i)for(const e of i)d.append("splits",e);if(void 0!==s){const e=JSON.stringify(s);d.append("metadata",e)}void 0!==o&&d.append("limit",o.toString()),void 0!==u&&d.append("offset",u.toString()),void 0!==l&&d.append("filter",l);let f=0;for await(const e of this._getPaginated("/examples",d)){for(const t of e)yield t,f++;if(void 0!==o&&f>=o)break}}async deleteExample(e){oa(e);const t=`/examples/${e}`,r=await this.caller.call(qi(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(r,`delete ${t}`),await r.json()}async updateExample(e,t){oa(e);const r=await this.caller.call(qi(),`${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});await yo(r,"update example");return await r.json()}async updateExamples(e){const t=await this.caller.call(qi(),`${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});await yo(t,"update examples");return await t.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){n=(await this.readDataset({datasetName:t})).id}else n=e;oa(n);const i=new URLSearchParams,a=r?"string"==typeof r?r:r?.toISOString():void 0;a&&i.append("as_of",a);return await this._get(`/datasets/${n}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:i=!1}){let a;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){a=(await this.readDataset({datasetName:t})).id}else a=e;oa(a);const s={split_name:r,examples:n.map((e=>(oa(e),e))),remove:i},o=await this.caller.call(qi(),`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(o,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:i}={loadChildRuns:!1}){let a;if(la("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)a=await this.readRun(e,{loadChildRuns:n});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);a=e}null!==a.reference_example_id&&void 0!==a.reference_example_id&&(i=await this.readExample(a.reference_example_id));const s=await t.evaluateRun(a,i),[o,u]=await this._logEvaluationFeedback(s,a,r);return u[0]}async createFeedback(e,t,{score:r,value:n,correction:i,comment:a,sourceInfo:s,feedbackSourceType:o="api",sourceRunId:u,feedbackId:l,feedbackConfig:c,projectId:d,comparativeExperimentId:h}){if(!e&&!d)throw new Error("One of runId or projectId must be provided");if(e&&d)throw new Error("Only one of runId or projectId can be provided");const p={type:o??"api",metadata:s??{}};void 0===u||void 0===p?.metadata||p.metadata.__run||(p.metadata.__run={run_id:u}),void 0!==p?.metadata&&void 0!==p.metadata.__run?.run_id&&oa(p.metadata.__run.run_id);const f={id:l??ki(),run_id:e,key:t,score:r,value:n,correction:i,comment:a,feedback_source:p,comparative_experiment_id:h,feedbackConfig:c,session_id:d},m=`${this.apiUrl}/feedback`,g=await this.caller.call(qi(),m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yo(g,"create feedback",!0),f}async updateFeedback(e,{score:t,value:r,correction:n,comment:i}){const a={};null!=t&&(a.score=t),null!=r&&(a.value=r),null!=n&&(a.correction=n),null!=i&&(a.comment=i),oa(e);const s=await this.caller.call(qi(),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(s,"update feedback",!0)}async readFeedback(e){oa(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){oa(e);const t=`/feedback/${e}`,r=await this.caller.call(qi(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(r,`delete ${t}`),await r.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const n=new URLSearchParams;if(e&&n.append("run",e.join(",")),t)for(const e of t)n.append("key",e);if(r)for(const e of r)n.append("source",e);for await(const e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){const 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};const a=await this.caller.call(qi(),`${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 a.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:i,metadata:a,id:s}){if(0===t.length)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw new Error("A reference dataset is required");const o={id:s,name:e,experiment_ids:t,reference_dataset_id:r,description:i,created_at:(n??new Date)?.toISOString(),extra:{}};a&&(o.extra.metadata=a);const u=await this.caller.call(qi(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u.json()}async*listPresignedFeedbackTokens(e){oa(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:[e],t}async _logEvaluationFeedback(e,t,r){const n=this._selectEvalResults(e),i=[];for(const e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),i.push(await this.createFeedback(a,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){const[n]=await this._logEvaluationFeedback(e,t,r);return n}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:n,limit:i}=e,a=new URLSearchParams;t&&t.forEach(((e,t)=>{oa(e,`queueIds[${t}]`),a.append("ids",e)})),r&&a.append("name",r),n&&a.append("name_contains",n),a.append("limit",(void 0!==i?Math.min(i,100):100).toString());let s=0;for await(const e of this._getPaginated("/annotation-queues",a))if(yield*e,s++,void 0!==i&&s>=i)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:n}=e,i={name:t,description:r,id:n||ki()},a=await this.caller.call(qi(),`${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});await yo(a,"create annotation queue");return await a.json()}async readAnnotationQueue(e){const t=await this.listAnnotationQueues({queueIds:[e]}).next();if(t.done)throw new Error(`Annotation queue with ID ${e} not found`);return t.value}async updateAnnotationQueue(e,t){const{name:r,description:n}=t,i=await this.caller.call(qi(),`${this.apiUrl}/annotation-queues/${oa(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 yo(i,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call(qi(),`${this.apiUrl}/annotation-queues/${oa(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const r=await this.caller.call(qi(),`${this.apiUrl}/annotation-queues/${oa(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map(((e,t)=>oa(e,`runIds[${t}]`).toString()))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${oa(e,"queueId")}/run`,n=await this.caller.call(qi(),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yo(n,"get run from annotation queue"),await n.json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(qi(),`${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){const e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),n=new Error(`Error ${t.status}: ${t.statusText}\n${e}`);throw n.statusCode=t.status,n}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,n,i]=mo(e),a=await this.caller.call(qi(),`${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 yo(a,(t?"like":"unlike")+" prompt"),await a.json()}async _getPromptUrl(e){const[t,r,n]=mo(e);if(await this._currentTenantIsOwner(t)){const 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(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,(e=>e.commits)))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,(e=>e.repos)))yield*e}async getPrompt(e){const[t,r,n]=mo(e),i=await this.caller.call(qi(),`${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 yo(i,"get prompt");const a=await i.json();return a.repo?a.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle. \n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[n,i,a]=mo(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);const s={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},o=await this.caller.call(qi(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(o,"create prompt");const{repo:u}=await o.json();return u}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,i,a]=mo(e),s="latest"!==r?.parentCommitHash&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${i}`),o={manifest:JSON.parse(JSON.stringify(t)),parent_commit:s},u=await this.caller.call(qi(),`${this.apiUrl}/commits/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(u,"create commit");const l=await u.json();return this._getPromptUrl(`${n}/${i}${l.commit_hash?`:${l.commit_hash}`:""}`)}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n]=mo(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const i={};if(void 0!==t?.description&&(i.description=t.description),void 0!==t?.readme&&(i.readme=t.readme),void 0!==t?.tags&&(i.tags=t.tags),void 0!==t?.isPublic&&(i.is_public=t.isPublic),void 0!==t?.isArchived&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw new Error("No valid update options provided");const a=await this.caller.call(qi(),`${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 yo(a,"update prompt"),a.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,n]=mo(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);const i=await this.caller.call(qi(),`${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){const[r,n,i]=mo(e);let a=i;if(!function(e,t){const r=fo.parse(e),n=fo.parse(t);if(!r||!n)throw new Error("Invalid version format.");return r.compare(n)>=0}((await this._getServerInfo()).version,"0.5.23")&&"latest"===i){const e=await this._getLatestCommitHash(`${r}/${n}`);if(!e)throw new Error("No commits found");a=e}const s=await this.caller.call(qi(),`${this.apiUrl}/commits/${r}/${n}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yo(s,"pull prompt commit");const o=await s.json();return{owner:r,repo:n,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){if(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)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[i,a]=this.parseTokenOrUrl(e,r),s=new Ao({apiUrl:i,apiKey:"placeholder"}),o=await s.readSharedDataset(a),u=n||o.name;try{if(await this.hasDataset({datasetId:u}))return}catch(e){}const l=await s.listSharedExamples(a),c=await this.createDataset(u,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map((e=>e.inputs)),outputs:l.flatMap((e=>e.outputs?[e.outputs]:[])),datasetId:c.id})}catch(e){throw e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return oa(e),[t,e]}catch(e){}try{const i=new URL(e).pathname.split("/").filter((e=>""!==e));if(i.length>=r){return[t,i[i.length-r]]}throw new Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${n} URL or token: ${e}`)}}}class So{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){const t=e.split(",");let r={},n=[];for(const e of t){const[t,i]=e.split("="),a=decodeURIComponent(i);"langsmith-metadata"===t?r=JSON.parse(a):"langsmith-tags"===t&&(n=a.split(","))}return new So(r,n)}toHeader(){const 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 Po{constructor(e){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});const t=Po.getDefaultConfig(),{metadata:r,...n}=e,i=n.client??Po.getSharedClient(),a={...r,...n?.extra?.metadata};if(n.extra={...n.extra,metadata:a},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){const e=function(e,t,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(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:ki(),run_type:"chain",project_name:aa("LANGCHAIN_PROJECT")??aa("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:aa("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:aa("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Po.sharedClient||(Po.sharedClient=new Ao),Po.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new Po({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t}),n=Symbol.for("lc:child_config"),i=e.extra?.[n]??this.extra[n];if(void 0!==(a=i)&&"object"==typeof a.callbacks&&(To(a.callbacks?.handlers)||To(a.callbacks))){const e={...i},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(Io)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}var a;const s=new Set;let o=this;for(;null!=o&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now()){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r}_convertToCreate(e,t,r=!0){const n=e.extra??{};if(n.runtime||(n.runtime={}),t)for(const[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);let i,a;r?(a=e.parent_run?.id,i=[]):(i=e.child_runs.map((e=>this._convertToCreate(e,t,r))),a=void 0);return{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:n,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags}}async postRun(e=!0){try{const t=await na(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e){la("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){}}async patchRun(){try{const 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};await this.client.updateRun(this.id,e)}catch(e){}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(e,t){const r=e?.callbacks;let n,i,a,s=!!["TRACING_V2","TRACING"].find((e=>"true"===sa(e)));if(r){const e=r?.getParentRunId?.()??"",t=r?.handlers?.find((e=>"langchain_tracer"==e?.name));n=t?.getRun?.(e),i=t?.projectName,a=t?.client,s=s||!!t}if(!n)return new Po({...t,client:a,tracingEnabled:s,project_name:i});return new Po({name:n.name,id:n.id,trace_id:n.trace_id,dotted_order:n.dotted_order,client:a,tracingEnabled:s,project_name:i,tags:[...new Set((n?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...n?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const 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;const i=n.trim(),a=i.split(".").map((e=>{const[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}})),s=a[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:s,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){const e=So.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags}return new Po(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new So(this.extra?.metadata,this.tags).toHeader()};if(e)for(const[r,n]of Object.entries(t))e.set(r,n);return t}}function Io(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function To(e){return Array.isArray(e)&&e.some((e=>Io(e)))}Object.defineProperty(Po,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});const Fo="0.1.61";var No,$o={exports:{}};var Ro=(No||(No=1,function(e){const t=(e=0)=>t=>`[${38+e};5;${t}m`,r=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,n={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]}};n.color.gray=n.color.blackBright,n.bgColor.bgGray=n.bgColor.bgBlackBright,n.color.grey=n.color.blackBright,n.bgColor.bgGrey=n.bgColor.bgBlackBright;for(const[t,r]of Object.entries(n)){for(const[t,i]of Object.entries(r))n[t]={open:`[${i[0]}m`,close:`[${i[1]}m`},r[t]=n[t],e.set(i[0],i[1]);Object.defineProperty(n,t,{value:r,enumerable:!1})}return Object.defineProperty(n,"codes",{value:e,enumerable:!1}),n.color.close="",n.bgColor.close="",n.color.ansi256=t(),n.color.ansi16m=r(),n.bgColor.ansi256=t(10),n.bgColor.ansi16m=r(10),Object.defineProperties(n,{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=>{const t=/(?[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(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>n.rgbToAnsi256(...n.hexToRgb(e)),enumerable:!1}}),n}})}($o)),$o.exports),Mo=B(Ro);function Lo(e,t){return`${e.open}${t}${e.close}`}const{color:Bo}=Mo;class Uo extends vi{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const e=this.runMap.get(r.parent_run_id);if(!e)break;t.push(e),r=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map(((e,t,r)=>{const n=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?Lo(Mo.bold,n):n})).join(" > ");return Lo(Bo.grey,t)}onChainStart(e){this.getBreadcrumbs(e)}onChainEnd(e){this.getBreadcrumbs(e)}onChainError(e){this.getBreadcrumbs(e)}onLLMStart(e){this.getBreadcrumbs(e),"prompts"in e.inputs?e.inputs.prompts.map((e=>e.trim())):e.inputs}onLLMEnd(e){this.getBreadcrumbs(e)}onLLMError(e){this.getBreadcrumbs(e)}onToolStart(e){this.getBreadcrumbs(e)}onToolEnd(e){this.getBreadcrumbs(e)}onToolError(e){this.getBreadcrumbs(e)}onRetrieverStart(e){this.getBreadcrumbs(e)}onRetrieverEnd(e){this.getBreadcrumbs(e)}onRetrieverError(e){this.getBreadcrumbs(e)}onAgentAction(e){this.getBreadcrumbs(e)}}function zo(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}class Zo extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function Ho(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="";const r=[];let n=!1,i=!1;for(let a of e){if(n)'"'!==a||i?"\n"!==a||i?i="\\"===a&&!i:a="\\n":n=!1;else if('"'===a)n=!0,i=!1;else if("{"===a)r.push("}");else if("["===a)r.push("]");else if("}"===a||"]"===a){if(!r||r[r.length-1]!==a)return null;r.pop()}t+=a}n&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}class Vo extends li{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:""}constructor(e,t){"string"==typeof e&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(null===e)return this;const t=(r=this._printableFields,n=Math.max(4,e),JSON.stringify(function e(t,r){if("object"!=typeof t||null==t)return t;if(r>=n)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map((t=>e(t,r+1)));const i={};for(const n of Object.keys(t))i[n]=e(t[n],r+1);return i}(r,0),null,2));var r,n;return`${this.constructor.lc_name()} ${t}`}}function qo(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(null==r[e])r[e]=n;else{if(null==n)continue;if(typeof r[e]!=typeof n||Array.isArray(r[e])!==Array.isArray(n))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof r[e]){if("type"===e)continue;r[e]+=n}else if("object"!=typeof r[e]||Array.isArray(r[e])){if(Array.isArray(r[e]))r[e]=Wo(r[e],n);else if(r[e]===n)continue}else r[e]=qo(r[e],n)}return r}function Wo(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const r=[...e];for(const e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){const t=r.findIndex((t=>t.index===e.index));-1!==t?r[t]=qo(r[t],e):r.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}class Go extends Vo{}function Jo(e){return"function"==typeof e?._getType}class Ko extends Vo{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,"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 Yo extends Vo{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if("string"==typeof e)r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const t=r.additional_kwargs?.tool_calls,n=r.tool_calls;null!=t&&t.length>0&&(void 0===n||n.length);try{if(null!=t&&void 0===n){const[e,n]=function(e){const t=[],r=[];for(const n of e)if(n.function){const e=n.function.name;try{const r={name:e||"",args:JSON.parse(n.function.arguments)||{},id:n.id};t.push(r)}catch(t){r.push({name:e,args:n.function.arguments,id:n.id,error:"Malformed args."})}}return[t,r]}(t);r.tool_calls=e??[],r.invalid_tool_calls=n??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch(e){r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"string"!=typeof r&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}class Xo extends Go{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[]};else{const r=[],n=[];for(const t of e.tool_call_chunks){let e={};try{if(e=Ho(t.args||"{}"),null===e||"object"!=typeof e||Array.isArray(e))throw new Error("Malformed tool call chunk args.");r.push({name:t.name??"",args:e,id:t.id,type:"tool_call"})}catch(e){n.push({name:t.name,args:t.args,id:t.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:n}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:(r=this.content,n=e.content,"string"==typeof r?"string"==typeof n?r+n:[{type:"text",text:r},...n]:Array.isArray(n)?Wo(r,n)??[...r,...n]:[...r,{type:"text",text:n}]),additional_kwargs:qo(this.additional_kwargs,e.additional_kwargs),response_metadata:qo(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};var r,n;if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const r=Wo(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){const r=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},n=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i={input_tokens:r.input_tokens+n.input_tokens,output_tokens:r.output_tokens+n.output_tokens,total_tokens:r.total_tokens+n.total_tokens};t.usage_metadata=i}return new Xo(t)}}class Qo extends Vo{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return Qo}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 eu extends Vo{static lc_name(){return"HumanMessage"}_getType(){return"human"}}class tu extends Vo{static lc_name(){return"SystemMessage"}_getType(){return"system"}}function ru(e){return zo(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 nu(e){const{type:t,...r}=e;if("human"===t||"user"===t)return new eu(r);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=r;if(!Array.isArray(e))return new Yo(r);const n=e.map(ru);return new Yo({...t,tool_calls:n})}if("system"===t)return new tu(r);if("tool"===t&&"tool_call_id"in r)return new Ko({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});throw new Error("Unable to coerce message from array: only human, AI, or system message coercion is currently supported.")}function iu(e){if("string"==typeof e)return new eu(e);if(Jo(e))return e;if(Array.isArray(e)){const[t,r]=e;return nu({type:t,content:r})}if("string"==typeof e.role){const{role:t,...r}=e;return nu({...r,type:t})}return nu(e)}function au(e,t="Human",r="AI"){const n=[];for(const 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())throw new Error(`Got unsupported message type: ${i._getType()}`);e=i.role}const a=i.name?`${i.name}, `:"",s="string"==typeof i.content?i.content:JSON.stringify(i.content,null,2);n.push(`${e}: ${a}${s}`)}return n.join("\n")}class su extends vi{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});const{exampleId:t,projectName:r,client:n}=e;this.projectName=r??fi("LANGCHAIN_PROJECT")??fi("LANGCHAIN_SESSION"),this.exampleId=t,this.client=n??new Ao({});const i=su.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,t=void 0){return{...e,extra:{...e.extra,runtime:await pi()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){const t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){const 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;const r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);)t=t.parent_run;r.clear();const n=[t];for(;n.length>0;){const 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){const t={},r=[];for(const[e,n]of this.runMap){const i=new Po({...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])}r.sort(((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0));for(const[e]of r){const r=this.runMap.get(e),n=t[e];if(r&&n&&r.parent_run_id){const e=t[r.parent_run_id];e&&(e.child_runs.push(n),n.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return(()=>{const e=Nn.getInstance().getStore();if(void 0===e)throw new Error(["Could not get the current run tree.","","Please make sure you are calling this method within a traceable function or the tracing is enabled."].join("\n"));return e})()}catch{return}}}let ou;async function uu(e,t){!0===t?await e():(void 0===ou&&(ou=new("default"in Zi?Zi.default:Zi)({autoStart:!0,concurrency:1})),ou.add(e))}class lu{setHandler(e){return this.setHandlers([e])}}class cu{constructor(e,t,r,n,i,a,s,o){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:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map((t=>uu((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=>uu((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 du extends cu{getChild(e){const t=new mu(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=>uu((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=>uu((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 hu extends cu{async handleLLMNewToken(e,t,r,n,i,a){await Promise.all(this.handlers.map((r=>uu((async()=>{if(!r.ignoreLLM)try{await(r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a))}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=>uu((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=>uu((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 pu extends cu{getChild(e){const t=new mu(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=>uu((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=>uu((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=>uu((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=>uu((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 fu extends cu{getChild(e){const t=new mu(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=>uu((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=>uu((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 mu extends lu{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=void 0,n=void 0,i=void 0,a=void 0,s=void 0,o=void 0){return Promise.all(t.map((async(t,n)=>{const a=0===n&&r?r:In();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return bi(r)&&r._createRunForLLMStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,o),uu((async()=>{try{await(r.handleLLMStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,o))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new hu(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChatModelStart(e,t,r=void 0,n=void 0,i=void 0,a=void 0,s=void 0,o=void 0){return Promise.all(t.map((async(t,n)=>{const a=0===n&&r?r:In();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return bi(r)&&r._createRunForChatModelStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,o),uu((async()=>{try{if(r.handleChatModelStart)await(r.handleChatModelStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,o));else if(r.handleLLMStart){const n=au(t);await(r.handleLLMStart?.(e,[n],a,this._parentRunId,i,this.tags,this.metadata,o))}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new hu(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChainStart(e,t,r=In(),n=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map((i=>{if(!i.ignoreChain)return bi(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,n,s),uu((async()=>{try{await(i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,n,s))}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}}),i.awaitHandlers)}))),new pu(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=In(),n=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreAgent)return bi(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),uu((async()=>{try{await(n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new fu(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=In(),n=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreRetriever)return bi(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),uu((async()=>{try{await(n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new du(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=>uu((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){this.handlers=[],this.inheritableHandlers=[];for(const r of 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(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new mu(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);r.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(const 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){const t=new this;return t.addHandler(new class extends gi{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:In()}),Object.assign(this,e)}}),t}static configure(e,t,r,n,i,a,s){return this._configureSync(e,t,r,n,i,a,s)}static _configureSync(e,t,r,n,i,a,s){let o;(e||t)&&(Array.isArray(e)||!e?(o=new mu,o.setHandlers(e?.map(gu)??[],!0)):o=e,o=o.copy(Array.isArray(t)?t.map(gu):t?.handlers,!1));const u="true"===fi("LANGCHAIN_VERBOSE")||s?.verbose,l=su.getTraceableRunTree()?.tracingEnabled||!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((e=>"true"===fi(e))),c=l||(fi("LANGCHAIN_TRACING")??!1);if(u||c){if(o||(o=new mu),u&&!o.handlers.some((e=>e.name===Uo.prototype.name))){const e=new Uo;o.addHandler(e,!0)}if(c&&!o.handlers.some((e=>"langchain_tracer"===e.name))&&l){const e=new su;o.addHandler(e,!0),o._parentRunId=su.getTraceableRunTree()?.id??o._parentRunId}}return(r||n)&&o&&(o.addTags(r??[]),o.addTags(n??[],!1)),(i||a)&&o&&(o.addMetadata(i??{}),o.addMetadata(a??{},!1)),o}}function gu(e){return"name"in e?e:gi.fromMethods(e)}const yu=new class{getStore(){}run(e,t){return t()}},bu=Symbol.for("ls:tracing_async_local_storage"),vu=Symbol.for("lc:child_config");const _u=new class{getInstance(){return globalThis[bu]??yu}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[vu]}runWithConfig(e,t,r){const n=mu._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=n?.getParentRunId(),s=n?.handlers?.find((e=>"langchain_tracer"===e?.name));let o;return s&&a?o=s.convertToRunTree(a):r||(o=new Po({name:"",tracingEnabled:!1})),o&&(o.extra={...o.extra,[vu]:e}),i.run(o,t)}initializeGlobalInstance(e){void 0===globalThis[bu]&&(globalThis[bu]=e)}};async function wu(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,n)=>{r=()=>{n(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}class Du 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{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new Du({start:e=>function r(){return t.read().then((({done:t,value:n})=>{if(!t)return e.enqueue(n),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new Du({async pull(t){const{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function Eu(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function Ou(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){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=Ou(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class Cu{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)=>{_u.runWithConfig(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?_u.runWithConfig(this.config,this.signal?async()=>wu(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()}}class xu{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=Xn({},t);return new ku({ops:t,state:r[r.length-1].newDocument})}}class ku extends xu{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=Xn(this.state,e.ops);return new ku({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=Xn({},e.ops);return new ku({ops:e.ops,state:t[t.length-1].newDocument})}}const ju=e=>"log_stream_tracer"===e.name;async function Au(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{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 Su(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}class Pu extends vi{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"}),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=Du.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let 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(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new xu({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 xu({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;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const 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 Au(e,this._schemaFormat)),await this.writer.write(new xu({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await Au(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Su(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new xu({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new xu({ops:[{op:"replace",path:"/final_output",value:await Su(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let i;var a;void 0!==e.inputs.messages?(a=r?.chunk,i=void 0!==a&&void 0!==a.message?r?.chunk:new Xo({id:`run-${e.id}`,content:t})):i=t;const s=new xu({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:i}]});await this.writer.write(s)}}class Iu{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 Iu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function Tu({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const Fu=e=>"event_stream_tracer"===e.name;class Nu extends vi{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"}),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=Du.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let 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){const r=await t.next();if(r.done)return;const 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 Iu({text:t}):t}let a=this.tappedPromises.get(e);if(void 0===a){let s;a=new Promise((e=>{s=e})),this.tappedPromises.set(e,a);try{const a={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...a,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...a,data:{chunk:i(n.runType,e)}},n),yield e}finally{s()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=Tu(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);const 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){const n=this.runInfoMap.get(e.id);let i,a;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)a="on_chat_model_stream",i=void 0===r?.chunk?new Xo({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);a="on_llm_stream",i=void 0===r?.chunk?new Iu({text:t}):r.chunk}await this.send({event:a,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let i;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==i)break;i=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);i={generations:n?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=Tu(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let 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){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const 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){const t=Tu(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){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?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){const t=Tu(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const n=this.runInfoMap.get(r);if(void 0===n)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}async function $u(e){return mu._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Ru(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const 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){const e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{const r=e.copy();for(const e of n)r.addHandler(gu(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){const r=n.copy();for(const t of e)r.addHandler(gu(t),!0);t.callbacks=r}else t.callbacks=new mu(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{const n=e;t[n]=r[n]??t[n]}return t}const Mu=new Set(["string","number","boolean"]);function Lu(e){const t=_u.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{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(const e of Object.keys(r.configurable))Mu.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 new Error("Timeout must be a positive number");const 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 Bu(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:a,runId:s}={}){const o=Lu(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==n&&(o.recursionLimit=n),void 0!==r&&(o.maxConcurrency=r),void 0!==i&&(o.runName=i),void 0!==a&&(o.configurable={...o.configurable,...a}),void 0!==s&&delete o.runId,o}const Uu=[400,401,402,403,404,405,406,407,409],zu=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&Uu.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};class Zu{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??zu;const t="default"in Zi?Zi.default:Zi;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add((()=>En((()=>e(...t).catch((e=>{throw e instanceof Error?e:new 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(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>fetch(...e).then((e=>e.ok?e:Promise.reject(e)))))}}class Hu extends vi{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 Vu(e){return!!e&&e.lc_runnable}class qu{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;const 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}}const Wu=Symbol("Let zodToJsonSchema decide on which parser to use"),Gu={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"},Ju=e=>{const t=(e=>"string"==typeof e?{...Gu,name:e}:{...Gu,...e})(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 Ku(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Yu(e,t,r,n,i){e[t]=r,Ku(e,t,n,i)}function Xu(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>Xu(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 Qu(e,t)}}const Qu=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":Yu(r,"minimum",n.value,n.message,t);break;case"max":Yu(r,"maximum",n.value,n.message,t)}return r};let el;const tl=/^[cC][^\s-]{8,}$/,rl=/^[0-9a-z]+$/,nl=/^[0-9A-HJKMNP-TV-Z]{26}$/,il=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,al=()=>(void 0===el&&(el=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),el),sl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ol=/^[a-zA-Z0-9_-]{21}$/;function ul(e,t){const r={type:"string"};function n(e){return"escape"===t.patternStrategy?ll(e):e}if(e.checks)for(const i of e.checks)switch(i.kind){case"min":Yu(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t);break;case"max":Yu(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":cl(r,"email",i.message,t);break;case"format:idn-email":cl(r,"idn-email",i.message,t);break;case"pattern:zod":dl(r,il,i.message,t)}break;case"url":cl(r,"uri",i.message,t);break;case"uuid":cl(r,"uuid",i.message,t);break;case"regex":dl(r,i.regex,i.message,t);break;case"cuid":dl(r,tl,i.message,t);break;case"cuid2":dl(r,rl,i.message,t);break;case"startsWith":dl(r,RegExp(`^${n(i.value)}`),i.message,t);break;case"endsWith":dl(r,RegExp(`${n(i.value)}$`),i.message,t);break;case"datetime":cl(r,"date-time",i.message,t);break;case"date":cl(r,"date",i.message,t);break;case"time":cl(r,"time",i.message,t);break;case"duration":cl(r,"duration",i.message,t);break;case"length":Yu(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t),Yu(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"includes":dl(r,RegExp(n(i.value)),i.message,t);break;case"ip":"v6"!==i.version&&cl(r,"ipv4",i.message,t),"v4"!==i.version&&cl(r,"ipv6",i.message,t);break;case"emoji":dl(r,al,i.message,t);break;case"ulid":dl(r,nl,i.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":cl(r,"binary",i.message,t);break;case"contentEncoding:base64":Yu(r,"contentEncoding","base64",i.message,t);break;case"pattern:zod":dl(r,sl,i.message,t)}break;case"nanoid":dl(r,ol,i.message,t)}return r}const ll=e=>Array.from(e).map((e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`)).join(""),cl=(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}}})):Yu(e,"format",t,r,n)},dl=(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:hl(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Yu(e,"pattern",hl(t,n),r,n)},hl=(e,t)=>{const r="function"==typeof e?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;const n=r.flags.includes("i"),i=r.flags.includes("m"),a=r.flags.includes("s"),s=n?r.source.toLowerCase():r.source;let o="",u=!1,l=!1,c=!1;for(let e=0;e({...r,[n]:yl(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:!1};const r={type:"object",additionalProperties:yl(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===kr.ZodString&&e.keyType._def.checks?.length){const n=Object.entries(ul(e.keyType._def,t)).reduce(((e,[t,r])=>"type"===t?e:{...e,[t]:r}),{});return{...r,propertyNames:n}}return e.keyType?._def.typeName===kr.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}const fl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const ml=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>yl(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 gl(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:yl(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:yl(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function yl(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==Wu)return i}if(n&&!r){const e=bl(n,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=_l(e,e.typeName,t);return a&&wl(e,t,a),i.jsonSchema=a,a}const bl=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:vl(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[r]===e))||"seen"===t.$refStrategy?{}:void 0}},vl=(e,t)=>{let r=0;for(;r{switch(t){case kr.ZodString:return ul(e,r);case kr.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",Ku(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?Yu(r,"minimum",n.value,n.message,t):Yu(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Yu(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?Yu(r,"maximum",n.value,n.message,t):Yu(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Yu(r,"maximum",n.value,n.message,t));break;case"multipleOf":Yu(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case kr.ZodObject:return function(e,t){const r={type:"object",...Object.entries(e.shape()).reduce(((e,[r,n])=>{if(void 0===n||void 0===n._def)return e;const i=yl(n._def,{...t,currentPath:[...t.currentPath,"properties",r],propertyPath:[...t.currentPath,"properties",r]});return void 0===i?e:{properties:{...e.properties,[r]:i},required:n.isOptional()?e.required:[...e.required,r]}}),{properties:{},required:[]}),additionalProperties:gl(e,t)};return r.required.length||delete r.required,r}(e,r);case kr.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?Yu(r,"minimum",n.value,n.message,t):Yu(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Yu(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?Yu(r,"maximum",n.value,n.message,t):Yu(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Yu(r,"maximum",n.value,n.message,t));break;case"multipleOf":Yu(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case kr.ZodBoolean:return{type:"boolean"};case kr.ZodDate:return Xu(e,r);case kr.ZodUndefined:return{not:{}};case kr.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case kr.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def?.typeName!==kr.ZodAny&&(r.items=yl(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Yu(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Yu(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Yu(r,"minItems",e.exactLength.value,e.exactLength.message,t),Yu(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case kr.ZodUnion:case kr.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return ml(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in fl&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=fl[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))){const e=r.reduce(((e,t)=>{const 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){const 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 ml(e,t)}(e,r);case kr.ZodIntersection:return function(e,t){const r=[yl(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),yl(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}else i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),i.length?{allOf:i,...n}:void 0}(e,r);case kr.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>yl(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:yl(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>yl(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case kr.ZodRecord:return pl(e,r);case kr.ZodLiteral:return function(e,t){const 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}}(e,r);case kr.ZodEnum:return function(e){return{type:"string",enum:e.values}}(e);case kr.ZodNativeEnum:return function(e){const 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}}(e);case kr.ZodNullable:return function(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:fl[e.innerType._def.typeName],nullable:!0}:{type:[fl[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=yl(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=yl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case kr.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return yl(e.innerType._def,t);const r=yl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case kr.ZodMap:return function(e,t){return"record"===t.mapStrategy?pl(e,t):{type:"array",maxItems:125,items:{type:"array",items:[yl(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},yl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case kr.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:yl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Yu(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Yu(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case kr.ZodLazy:return yl(e.getter()._def,r);case kr.ZodPromise:return function(e,t){return yl(e.type._def,t)}(e,r);case kr.ZodNaN:case kr.ZodNever:return{not:{}};case kr.ZodEffects:return function(e,t){return"input"===t.effectStrategy?yl(e.schema._def,t):{}}(e,r);case kr.ZodAny:case kr.ZodUnknown:return{};case kr.ZodDefault:return function(e,t){return{...yl(e.innerType._def,t),default:e.defaultValue()}}(e,r);case kr.ZodBranded:return function(e,t){return yl(e.type._def,t)}(e,r);case kr.ZodReadonly:case kr.ZodCatch:return((e,t)=>yl(e.innerType._def,t))(e,r);case kr.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return yl(e.in._def,t);if("output"===t.pipeStrategy)return yl(e.out._def,t);const r=yl(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,yl(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case kr.ZodFunction:case kr.ZodVoid:case kr.ZodSymbol:default:return}},wl=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Dl=(e,t)=>{const r=Ju(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,n])=>({...e,[t]:yl(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}})),{}):void 0,i="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,a=yl(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(a.title=s);const o=void 0===i?n?{...a,[r.definitionPath]:n}:a:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:a}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function El(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const Ol=["*","_","`"];function Cl(e,t,r){const{firstNode:n,lastNode:i,nodeColors:a,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=r??{};let l=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(s){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last");for(const[n,i]of Object.entries(e)){const e=i.name.split(":").pop()??"";let a=Ol.some((t=>e.startsWith(t)&&e.endsWith(t)))?`

${e}

`:e;Object.keys(i.metadata??{}).length&&(a+=`
${Object.entries(i.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}`);const s=(r[n]??r[t]).replace("{0}",El(n)).replace("{1}",a);l+=`\t${s}\n`}}const c={};for(const e of t){const 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)}const d=new Set;function h(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(d.has(e))throw new 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.`);d.add(e),l+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:r,data:n,conditional:i}=t;let a="";if(void 0!==n){let e=n;const t=e.split(" ");t.length>u&&(e=Array.from({length:Math.ceil(t.length/u)},((e,r)=>t.slice(r*u,(r+1)*u).join(" "))).join(" 
 ")),a=i?` -.  ${e}  .-> `:` --  ${e}  --\x3e `}else a=i?" -.-> ":" --\x3e ";l+=`\t${El(e)}${a}${El(r)};\n`}for(const e in c)e.startsWith(`${t}:`)&&e!==t&&h(c[e],e);t&&!r&&(l+="\tend\n")}h(c[""]??[],"");for(const e in c)e.includes(":")||""===e||h(c[e],e);return s&&(l+=function(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}(a??{})),l}function xl(e,t){if(void 0!==e&&!Cn(e))return e;if(!Vu(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}}function kl(e){return Vu(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Dl(e.data.schema),title:e.data.name}}}class jl{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(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=Cn(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...kl(t)}))),edges:this.edges.map((t=>{const 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 new Error(`Node with id ${t} already exists`);const n=t??In(),i={id:n,data:e,name:xl(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 new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const i={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(i),i}firstNode(){return Al(this)}lastNode(){return Sl(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(Cn)&&(r="");const n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}}));const i=e.edges.map((e=>({...e,source:n(e.source),target:n(e.target)})));this.edges=[...this.edges,...i];const a=e.firstNode(),s=e.lastNode();return[a?{id:n(a.id),data:a.data}:void 0,s?{id:n(s.id),data:s.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Al(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Sl(this,[e.id])&&this.removeNode(e)}reid(){const 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)}));const r=r=>{const n=e[r];return Cn(r)&&1===t.get(n)?n:r};return new jl({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){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),s=a.firstNode(),o=a.lastNode();return Cl(a.nodes,a.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:i})}async drawMermaidPng(e){return async function(e,t){let{backgroundColor:r="white"}=t??{};const n=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const i=`https://mermaid.ink/img/${n}?bgColor=${r}`,a=await fetch(i);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join("\n"));return await a.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function Al(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),n=[];for(const 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 Sl(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),n=[];for(const 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 Pl(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function Il(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*Tl(e,t){for(;;){const{value:r,done:n}=_u.runWithConfig(e,t.next.bind(t),!0);if(n)break;yield r}}async function*Fl(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:i}=await _u.runWithConfig(e,r.next.bind(t),!0);if(i)break;yield n}}function Nl(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class $l extends li{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){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new Rl({bound:this,kwargs:e,config:{}})}map(){return new Ml({bound:this})}withRetry(e){return new Ll({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Rl({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Hl({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Lu);if(t>1&&!Array.isArray(e)&&e.runId){const r=Object.fromEntries(Object.entries(e).filter((([e])=>"runId"!==e)));return Array.from({length:t},((t,n)=>Lu(0===n?e:r)))}return Array.from({length:t},(()=>Lu(e)))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,a=new Zu({maxConcurrency:i,onFailedAttempt:e=>{throw e}}),s=e.map(((e,t)=>a.call((async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}}))));return Promise.all(s)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=Lu(t),n=new Cu({generator:this._streamIterator(e,r),config:r});return await n.setup,Du.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=Lu(void 0===e?e:{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});const 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){const n=Lu(r),i=await $u(n),a=await(i?.handleChainStart(this.toJSON(),Nl(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let s;delete n.runId;try{const i=e.call(this,t,n,a);s=await wu(i,r?.signal)}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(Nl(s,"output"))),s}async _batchWithConfig(e,t,r,n){const i=this._getOptionsList(r??{},t.length),a=await Promise.all(i.map($u)),s=await Promise.all(a.map((async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),Nl(t[r],"input"),i[r].runId,i[r].runType,void 0,void 0,i[r].runName??this.getName()));return delete i[r].runId,n})));let o;try{const r=e.call(this,t,i,s,n);o=await wu(r,i?.[0]?.signal)}catch(e){throw await Promise.all(s.map((t=>t?.handleChainError(e)))),e}return await Promise.all(s.map((e=>e?.handleChainEnd(Nl(o,"output"))))),o}async*_transformStreamWithConfig(e,t,r){let n,i,a=!0,s=!0;const o=Lu(r),u=await $u(o);let l;try{const c=await async function(e,t,r,n,...i){const a=new Cu({generator:t,startSetup:r,signal:n}),s=await a.setup;return{output:e(a,s,...i),setup:s}}(t.bind(this),async function*(){for await(const t of e){if(a)if(void 0===n)n=t;else try{n=Ou(n,t)}catch{n=void 0,a=!1}yield t}}(),(async()=>u?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName())),r?.signal,o);delete o.runId,l=c.setup;const d=l?.handlers.find(Fu);let h=c.output;void 0!==d&&void 0!==l&&(h=d.tapOutputIterable(l.runId,h));const p=l?.handlers.find(ju);void 0!==p&&void 0!==l&&(h=p.tapOutputIterable(l.runId,h));for await(const e of h)if(yield e,s)if(void 0===i)i=e;else try{i=Ou(i,e)}catch{i=void 0,s=!1}}catch(e){throw await(l?.handleChainError(e,void 0,void 0,void 0,{inputs:Nl(n,"input")})),e}await(l?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:Nl(n,"input")}))}getGraph(e){const t=new jl,r=t.addNode({name:`${this.getName()}Input`,schema:yn.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:yn.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new Bl({first:this,last:Vl(e)})}pick(e){return this.pipe(new Wl(e))}assign(e){return this.pipe(new ql(new Ul({steps:e})))}async*transform(e,t){let r;for await(const t of e)r=void 0===r?t:Ou(r,t);yield*this._streamIterator(r,Lu(t))}async*streamLog(e,t,r){const n=new Pu({...r,autoClose:!1,_schemaFormat:"original"}),i=Lu(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const i=this.stream(e,r);const a=async function(){try{const e=await i;for await(const r of e){const e=new xu({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await a}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return Du.fromReadableStream(r)}(n):Du.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new Nu({...r,autoClose:!1}),i=Lu(t),a=i.runId??In();i.runId=a;const s=i.callbacks;if(void 0===s)i.callbacks=[n];else if(Array.isArray(s))i.callbacks=s.concat(n);else{const e=s.copy();e.addHandler(n,!0),i.callbacks=e}const o=this;const u=async function(){try{const t=await o.stream(e,i),r=n.tapOutputIterable(a,t);for await(const e of r);}finally{await n.finish()}}();let l,c=!1;try{for await(const t of n)c?(t.run_id===l&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,c=!0,l=t.run_id,yield t)}finally{await u}}async*_streamEventsV1(e,t,r){let n,i=!1;const a=Lu(t),s=a.tags??[],o=a.metadata??{},u=a.runName??this.getName(),l=new Pu({...r,autoClose:!1,_schemaFormat:"streaming_events"}),c=new qu({...r}),d=this._streamLog(e,l,a);for await(const t of d){if(n=n?n.concat(t):ku.fromRunLogPatch(t),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:u,tags:s,metadata:o,data:{input:e}};c.includeEvent(r,t.type)&&(yield r)}const r=t.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),a=[...new Set(r)];for(const e of a){let t,r={};const i=n.state.logs[e];if(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end","start"===t)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){const e=i.streamed_output.length;if(1!==e)throw new 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}}const{state:l}=n;if(l.streamed_output.length>0){const e=l.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);const t={chunk:l.streamed_output[0]};l.streamed_output=[];const r={event:`on_${l.type}_stream`,run_id:l.id,tags:s,metadata:o,name:u,data:t};c.includeEvent(r,l.type)&&(yield r)}}const h=n?.state;if(void 0!==h){const e={event:`on_${h.type}_end`,name:u,run_id:h.id,tags:s,metadata:o,data:{output:h.final_output}};c.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return Vu(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new Rl({bound:this,config:{},configFactories:[n=>({callbacks:[new Hu({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),n=t.description??t.schema?.description;if(t.schema.constructor===yn.ZodString)return new Gl({name:r,description:n,schema:yn.object({input:yn.string()}).transform((e=>e.input)),bound:e});return new Gl({name:r,description:n,schema:t.schema,bound:e})}(this,e)}}class Rl extends $l{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){const t=Ru(this.config,...e);return Ru(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(Lu(t),this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig(Lu(e),this.kwargs)))):await this._mergeConfig(Lu(t),this.kwargs);return this.bound.batch(e,n,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Lu(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Lu(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Lu(t),this.kwargs))}streamEvents(e,t,r){const n=this;return Du.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(Lu(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&$l.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new Rl({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new Hu({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class Ml extends $l{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 Ml({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,Bu(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new Ml({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class Ll extends Rl{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){const n=e>1?`retry:attempt:${e}`:void 0;return Bu(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return En((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){const i={};try{await En((async a=>{const s=e.map(((e,t)=>t)).filter((e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error)),o=s.map((t=>e[t])),u=s.map((e=>this._patchConfigForRetry(a,t?.[e],r?.[e]))),l=await super.batch(o,u,{...n,returnExceptions:!0});let c;for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==n?.returnExceptions)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 Bl extends $l{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,"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}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=Lu(t),n=await $u(r),i=await(n?.handleChainStart(this.toJSON(),Nl(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let a,s=e;try{const e=[this.first,...this.middle];for(let n=0;n{const i=await(t?.handleChainStart(this.toJSON(),Nl(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let s=e;try{for(let e=0;e{const i=t?.getChild(`seq:step:${e+1}`);return Bu(n[r],{callbacks:i})})),r);s=await wu(t,n[0]?.signal)}}catch(e){throw await Promise.all(a.map((t=>t?.handleChainError(e)))),e}return await Promise.all(a.map((e=>e?.handleChainEnd(Nl(s,"output"))))),s}async*_streamIterator(e,t){const r=await $u(t),{runId:n,...i}=t??{},a=await(r?.handleChainStart(this.toJSON(),Nl(e,"input"),n,void 0,void 0,void 0,i?.runName)),s=[this.first,...this.middle,this.last];let o,u=!0;try{let r=s[0].transform(async function*(){yield e}(),Bu(i,{callbacks:a?.getChild("seq:step:1")}));for(let e=1;e{const a=n.getGraph(e);0!==i&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);const s=a.firstNode();if(!s)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,s),r=a.lastNode()})),t}pipe(e){return Bl.isRunnableSequence(e)?new Bl({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new Bl({first:this.first,middle:[...this.middle,this.last],last:Vl(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&$l.isRunnable(e)}static from([e,...t],r){return new Bl({first:Vl(e),middle:t.slice(0,-1).map(Vl),last:Vl(t[t.length-1]),name:r})}}class Ul extends $l{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}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,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=Vl(r)}static from(e){return new Ul({steps:e})}async invoke(e,t){const r=Lu(t),n=await $u(r),i=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const a={};try{const n=Object.entries(this.steps).map((async([t,n])=>{a[t]=await n.invoke(e,Bu(r,{callbacks:i?.getChild(`map:key:${t}`)}))}));await wu(Promise.all(n),t?.signal)}catch(e){throw await(i?.handleChainError(e)),e}return await(i?.handleChainEnd(a)),a}async*_transform(e,t,r){const n={...this.steps},i=Eu(e,Object.keys(n).length),a=new Map(Object.entries(n).map((([e,n],a)=>{const s=n.transform(i[a],Bu(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then((t=>({key:e,gen:s,result:t})))]})));for(;a.size;){const e=Promise.race(a.values()),{key:t,result:n,gen:i}=await wu(e,r?.signal);a.delete(t),n.done||(yield{[t]:n.value},a.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){const r=Lu(t),n=new Cu({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,Du.fromAsyncGenerator(n)}}class zl extends $l{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}),!$n(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),n=await $u(r);return wu(this.func(Bu(r,{callbacks:n}),e),r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);var i;if(Il(n))for await(const e of n)r?.signal?.throwIfAborted(),yield e;else if(null!=(i=n)&&"object"==typeof i&&"next"in i&&"function"==typeof i.next)for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(e){return new zl({func:e})}}class Zl extends $l{static lc_name(){return"RunnableLambda"}constructor(e){if($n(e.func))return zl.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}),function(e){if($n(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(e){return new Zl({func:e})}async _invoke(e,t,r){return new Promise(((n,i)=>{const a=Bu(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});_u.runWithConfig(a,(async()=>{try{let r=await this.func(e,{...a});if(r&&$l.isRunnable(r)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");r=await r.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(Il(r)){let e;for await(const n of Fl(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=Ou(e,n)}catch(t){e=n}r=e}else if(Pl(r)){let e;for(const n of Tl(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=Ou(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(const t of e)if(void 0===n)n=t;else try{n=Ou(n,t)}catch(e){n=t}const i=Bu(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),a=await new Promise(((e,t)=>{_u.runWithConfig(i,(async()=>{try{const t=await this.func(n,{...i,config:i});e(t)}catch(e){t(e)}}))}));if(a&&$l.isRunnable(a)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await a.stream(n,i);for await(const t of e)yield t}else if(Il(a))for await(const e of Fl(i,a))r?.signal?.throwIfAborted(),yield e;else if(Pl(a))for(const e of Tl(i,a))r?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Lu(t),n=new Cu({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,Du.fromAsyncGenerator(n)}}class Hl extends $l{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(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=Lu(t),n=await $u(t),{runId:i,...a}=r,s=await(n?.handleChainStart(this.toJSON(),Nl(e,"input"),i,void 0,void 0,void 0,a?.runName));let o;for(const t of this.runnables()){r?.signal?.throwIfAborted();try{const r=await t.invoke(e,Bu(a,{callbacks:s?.getChild()}));return await(s?.handleChainEnd(Nl(r,"output"))),r}catch(e){void 0===o&&(o=e)}}if(void 0===o)throw new Error("No error stored at end of fallback.");throw await(s?.handleChainError(o)),o}async*_streamIterator(e,t){const r=Lu(t),n=await $u(t),{runId:i,...a}=r,s=await(n?.handleChainStart(this.toJSON(),Nl(e,"input"),i,void 0,void 0,void 0,a?.runName));let o,u,l;for(const t of this.runnables()){r?.signal?.throwIfAborted();const n=Bu(a,{callbacks:s?.getChild()});try{u=await t.stream(e,n);break}catch(e){void 0===o&&(o=e)}}if(void 0===u){const e=o??new Error("No error stored at end of fallback.");throw await(s?.handleChainError(e)),e}try{for await(const e of u){yield e;try{l=void 0===l?l:Ou(l,e)}catch(e){l=void 0}}}catch(e){throw await(s?.handleChainError(e)),e}await(s?.handleChainEnd(Nl(l,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map((e=>$u(e)))),a=await Promise.all(i.map((async(t,r)=>{const i=await(t?.handleChainStart(this.toJSON(),Nl(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let s;for(const t of this.runnables()){n[0].signal?.throwIfAborted();try{const i=await t.batch(e,a.map(((e,t)=>Bu(n[t],{callbacks:e?.getChild()}))),r);return await Promise.all(a.map(((e,t)=>e?.handleChainEnd(Nl(i[t],"output"))))),i}catch(e){void 0===s&&(s=e)}}if(!s)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(a.map((e=>e?.handleChainError(s)))),s}}function Vl(e){if("function"==typeof e)return new Zl({func:e});if($l.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=Vl(n);return new Ul({steps:t})}}class ql extends $l{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Ul&&(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){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const n=this.mapper.getStepsKeys(),[i,a]=Eu(e),s=this.mapper.transform(a,Bu(r,{callbacks:t?.getChild()})),o=s.next();for await(const e of i){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter((([e])=>!n.includes(e))));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of s)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Lu(t),n=new Cu({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,Du.fromAsyncGenerator(n)}}class Wl extends $l{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];{const 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(const t of e){const 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){const r=Lu(t),n=new Cu({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,Du.fromAsyncGenerator(n)}}class Gl extends Rl{constructor(e){super({bound:Bl.from([Zl.from((async e=>{let t;if(zo(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new Zo("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"}}class Jl extends $l{static lc_name(){return"RunnablePassthrough"}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,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){const r=Lu(t);return this.func&&await this.func(e,r),this._callWithConfig((e=>Promise.resolve(e)),e,r)}async*transform(e,t){const r=Lu(t);let n,i=!0;for await(const t of this._transformStreamWithConfig(e,(e=>e),r))if(yield t,i)if(void 0===n)n=t;else try{n=Ou(n,t)}catch{n=void 0,i=!1}this.func&&void 0!==n&&await this.func(n,r)}static assign(e){return new ql(new Ul({steps:e}))}}class Kl extends $l{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig((async(e,t)=>this.parseResult([{text:e}],t?.callbacks)),e,{...t,runType:"parser"}):this._callWithConfig((async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks)),e,{...t,runType:"parser"})}}class Yl extends Kl{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}}class Xl extends Yl{async*_transform(e){for await(const t of e)"string"==typeof t?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class Ql extends Xl{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentComplexToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce(((e,t)=>e+this._messageContentComplexToString(t)),"")}}class ec extends $l{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});const{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){const t=this.partialVariables??{},r={};for(const[e,n]of Object.entries(t))r[e]="string"==typeof n?n:await n();return{...r,...e}}async invoke(e,t){return this._callWithConfig((e=>this.formatPromptValue(e)),e,{...t,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{const{PromptTemplate:t}=await Promise.resolve().then((function(){return Tc}));return t.deserialize(e)}case void 0:{const{PromptTemplate:t}=await Promise.resolve().then((function(){return Tc}));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{const{FewShotPromptTemplate:t}=await Promise.resolve().then((function(){return Wc}));return t.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}class tc extends li{}class rc extends tc{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 eu(this.value)]}}class nc extends tc{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 au(this.messages)}toChatMessages(){return this.messages}}class ic extends tc{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 eu({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}class ac extends ec{async formatPromptValue(e){const t=await this.format(e);return new rc(t)}} /*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js */var sc=Object.prototype.toString,oc=Array.isArray||function(e){return"[object Array]"===sc.call(e)};function uc(e){return"function"==typeof e}function lc(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function cc(e,t){return null!=e&&"object"==typeof e&&t in e}var dc=RegExp.prototype.test;var hc=/\S/;function pc(e){return!function(e,t){return dc.call(e,t)}(hc,e)}var fc={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};var mc=/\s*/,gc=/\s+/,yc=/\s*=/,bc=/\s*\}/,vc=/#|\^|\/|>|\{|&|=|!/;function _c(e){this.string=e,this.tail=e,this.pos=0}function wc(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function Dc(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}_c.prototype.eos=function(){return""===this.tail},_c.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},_c.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},wc.prototype.push=function(e){return new wc(e,this)},wc.prototype.lookup=function(e){var t,r,n,i=this.cache;if(i.hasOwnProperty(e))t=i[e];else{for(var a,s,o,u=this,l=!1;u;){if(e.indexOf(".")>0)for(a=u.view,s=e.split("."),o=0;null!=a&&o0?i[i.length-1][4]:r;break;default:n.push(t)}return r}(function(e){for(var t,r,n=[],i=0,a=e.length;i"===s?o=this.renderPartial(a,t,r,i):"&"===s?o=this.unescapedValue(a,t):"name"===s?o=this.escapedValue(a,t,i):"text"===s&&(o=this.rawValue(a)),void 0!==o&&(u+=o);return u},Dc.prototype.renderSection=function(e,t,r,n,i){var a=this,s="",o=t.lookup(e[1]);if(o){if(oc(o))for(var u=0,l=o.length;u0||!r)&&(i[a]=n+i[a]);return i.join("\n")},Dc.prototype.renderPartial=function(e,t,r,n){if(r){var i=this.getConfigTags(n),a=uc(r)?r(e[1]):r[e[1]];if(null!=a){var s=e[6],o=e[5],u=e[4],l=a;0==o&&u&&(l=this.indentPartial(a,u,s));var c=this.parse(l,i);return this.renderTokens(c,t,r,l,n)}}},Dc.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},Dc.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||Ec.escape,i=t.lookup(e[1]);if(null!=i)return"number"==typeof i&&n===Ec.escape?String(i):n(i)},Dc.prototype.rawValue=function(e){return e[1]},Dc.prototype.getConfigTags=function(e){return oc(e)?e:e&&"object"==typeof e?e.tags:void 0},Dc.prototype.getConfigEscape=function(e){return e&&"object"==typeof e&&!oc(e)?e.escape:void 0};var Ec={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(e){Oc.templateCache=e},get templateCache(){return Oc.templateCache}},Oc=new Dc;function Cc(){Ec.escape=e=>e}Ec.clearCache=function(){return Oc.clearCache()},Ec.parse=function(e,t){return Oc.parse(e,t)},Ec.render=function(e,t,r,n){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+((oc(i=e)?"array":typeof i)+'" was given as the first argument for mustache#render(template, view, partials)'));var i;return Oc.render(e,t,r,n)},Ec.escape=function(e){return String(e).replace(/[&<>"'`=\/]/g,(function(e){return fc[e]}))},Ec.Scanner=_c,Ec.Context=wc,Ec.Writer=Dc;const xc=e=>{const t=e.split(""),r=[],n=(e,r)=>{for(let n=r;n{Cc();return(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]})))(Ec.parse(e))},jc={"f-string":(e,t)=>xc(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 new Error(`(f-string) Missing value for input ${r.name}`)}return e+r.text}),""),mustache:(e,t)=>(Cc(),Ec.render(e,t))},Ac={"f-string":xc,mustache:kc},Sc=(e,t,r)=>jc[t](e,r),Pc=(e,t,r)=>{if(!(t in jc)){const e=Object.keys(jc);throw new Error(`Invalid template format. Got \`${t}\`;\n should be one of ${e}`)}try{const n=r.reduce(((e,t)=>(e[t]="foo",e)),{});Array.isArray(e)?e.forEach((e=>{if("text"===e.type)Sc(e.text,t,n);else{if("image_url"!==e.type)throw new Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`);if("string"==typeof e.image_url)Sc(e.image_url,t,n);else{const r=e.image_url.url;Sc(r,t,n)}}})):Sc(e,t,n)}catch(e){throw new Error(`Invalid prompt schema: ${e.message}`)}};class Ic extends ac{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 new Error("Mustache templates cannot be validated.");let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Pc(this.template,this.templateFormat,e)}}_getPromptType(){return"prompt"}async format(e){const t=await this.mergePartialAndUserVariables(e);return Sc(this.template,this.templateFormat,t)}static fromExamples(e,t,r,n="\n\n",i=""){const a=[i,...e,t].join(n);return new Ic({inputVariables:r,template:a})}static fromTemplate(e,t){const{templateFormat:r="f-string",...n}=t??{},i=new Set;return((e,t)=>Ac[t](e))(e,r).forEach((e=>{"variable"===e.type&&i.add(e.name)})),new Ic({inputVariables:[...i],templateFormat:r,template:e,...n})}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new Ic(n)}serialize(){if(void 0!==this.outputParser)throw new 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 new Error("Prompt template must have a template");return new Ic({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}var Tc=Object.freeze({__proto__:null,PromptTemplate:Ic});class Fc extends ec{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))),Pc([{type:"image_url",image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return"prompt"}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new Fc(n)}async format(e){const t={};for(const[r,n]of Object.entries(this.template))t[r]="string"==typeof n?Sc(n,this.templateFormat,e):n;const r=e.url||t.url,n=e.detail||t.detail;if(!r)throw new Error("Must provide either an image URL.");if("string"!=typeof r)throw new Error("url must be a string.");const i={url:r};return n&&(i.detail=n),i}async formatPromptValue(e){const t=await this.format(e);return new ic(t)}}class Nc extends $l{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 $c extends Nc{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){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){const e=new 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}let r;try{r=Array.isArray(t)?t.map(iu):[iu(t)]}catch(e){const r="string"==typeof t?t:JSON.stringify(t,null,2),n=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${r}`,`Additional message: ${e.message}`].join("\n\n"));throw n.name="InputFormatError",n}return r}}class Rc extends Nc{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 Mc extends ec{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new nc(t)}}class Lc extends Rc{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 Qo(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(Ic.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}}class Bc extends Nc{static _messageClass(){throw new 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){const t=this.constructor;if(t._messageClass()){return new(t._messageClass())({content:e})}if(t.chatMessageClass){const r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}throw new 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 new Error("Invalid message class name")}}static fromTemplate(e,t){if("string"==typeof e)return new this(Ic.fromTemplate(e,t));const r=[];for(const 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??"");const i={...t,..."string"!=typeof n?{additionalContentFields:n}:{}};r.push(Ic.fromTemplate(e,i))}else if("object"==typeof n&&"image_url"in n){let e,i=n.image_url??"",a=[];if("string"==typeof i){let r;r="mustache"===t?.templateFormat?kc(i):xc(i);const s=r.flatMap((e=>"variable"===e.type?[e.name]:[]));if((s?.length??0)>0){if(s.length>1)throw new Error(`Only one format variable allowed per image template.\nGot: ${s}\nFrom: ${i}`);a=[s[0]]}else a=[];i={url:i},e=new Fc({template:i,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:n})}else{if("object"!=typeof i)throw new Error("Invalid image template");if("url"in i){let e;e="mustache"===t?.templateFormat?kc(i.url):xc(i.url),a=e.flatMap((e=>"variable"===e.type?[e.name]:[]))}else a=[];e=new Fc({template:i,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:n})}r.push(e)}return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof ac){const t=await this.prompt.format(e);return this.createMessage(t)}{const t=[];for(const r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const t of r.inputVariables)n||(n={[t]:e[t]}),n={...n,[t]:e[t]};if(r instanceof ac){const e=await r.format(n);let i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,type:"text",text:e})}else if(r instanceof Fc){const e=await r.format(n);let i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,type:"image_url",image_url:e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}}class Uc extends Bc{static _messageClass(){return eu}static lc_name(){return"HumanMessagePromptTemplate"}}class zc extends Bc{static _messageClass(){return Yo}static lc_name(){return"AIMessagePromptTemplate"}}class Zc extends Bc{static _messageClass(){return tu}static lc_name(){return"SystemMessagePromptTemplate"}}function Hc(e,t){if("function"==typeof e.formatMessages||Jo(e))return e;if(Array.isArray(e)&&"placeholder"===e[0]){const t=e[1];if("string"!=typeof t||"{"!==t[0]||"}"!==t[t.length-1])throw new Error(`Invalid placeholder template: "${e[1]}". Expected a variable name surrounded by curly braces.`);const r=t.slice(1,-1);return new $c({variableName:r,optional:!0})}const r=iu(e);let n;if(n="string"==typeof r.content?r.content:r.content.map((e=>"text"in e?{...e,text:e.text}:"image_url"in e?{...e,image_url:e.image_url}:e)),"human"===r._getType())return Uc.fromTemplate(n,t);if("ai"===r._getType())return zc.fromTemplate(n,t);if("system"===r._getType())return Zc.fromTemplate(n,t);if(Qo.isInstance(r))return Lc.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}class Vc extends Mc{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){const e=new Set;for(const t of this.promptMessages)if(!(t instanceof Vo))for(const r of t.inputVariables)e.add(r);const 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 new Error(`Input variables \`${[...n]}\` are not used in any of the prompt messages.`);const i=new Set([...e].filter((e=>!r.has(e))));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` 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;const 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;const n=Ic.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){const t=await this.mergePartialAndUserVariables(e);let r=[];for(const e of this.promptMessages)if(e instanceof Vo)r.push(await this._parseImagePrompts(e,t));else{const n=e.inputVariables.reduce(((r,n)=>{if(!(n in t)&&("MessagesPlaceholder"!==e.constructor.lc_name()||!e.optional))throw new Error(`Missing value for input variable \`${n.toString()}\``);return r[n]=t[n],r}),{}),i=await e.formatMessages(n);r=r.concat(i)}return r}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new Vc(n)}static fromTemplate(e,t){const r=Ic.fromTemplate(e,t),n=new Uc({prompt:r});return this.fromMessages([n])}static fromMessages(e,t){const r=e.reduce(((e,r)=>e.concat(r instanceof Vc?r.promptMessages:[Hc(r,t)])),[]),n=e.reduce(((e,t)=>t instanceof Vc?Object.assign(e,t.partialVariables):e),Object.create(null)),i=new Set;for(const e of r)if(!(e instanceof Vo))for(const t of e.inputVariables)t in n||i.add(t);return new this({...t,inputVariables:[...i],promptMessages:r,partialVariables:n,templateFormat:t?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}class qc extends ac{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 new Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw new 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))),Pc(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 new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new qc(n)}async format(e){const t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=await Promise.all(r.map((e=>this.examplePrompt.format(e)))),i=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return Sc(i,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(void 0!==this.outputParser)throw new 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){const{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");const r=await Ic.deserialize(t);let n;if(!Array.isArray(e.examples))throw new Error("Invalid examples format. Only list or string are supported.");return n=e.examples,new qc({inputVariables:e.input_variables,examplePrompt:r,examples:n,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}}var Wc=Object.freeze({__proto__:null,FewShotPromptTemplate:qc});const Gc="context",Jc=Ic.fromTemplate("{page_content}");async function Kc({llm:e,prompt:t,outputParser:r=new Ql,documentPrompt:n=Jc,documentSeparator:i="\n\n"}){if(!t.inputVariables.includes(Gc))throw new Error(`Prompt must include a "${Gc}" variable`);return Bl.from([Jl.assign({[Gc]:new Wl(Gc).pipe(((e,t)=>async function({documentPrompt:e,documentSeparator:t,documents:r,config:n}){return(await Promise.all(r.map((t=>e.withConfig({runName:"document_formatter"}).invoke({...t.metadata,page_content:t.pageContent},n))))).join(t)}({documents:e,documentPrompt:n,documentSeparator:i,config:t})))}),t,e,r],"stuff_documents_chain")}class Yc{constructor(e){Object.defineProperty(this,"pageContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=void 0!==e.pageContent?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}}class Xc extends $l{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(e,t){return this.transformDocuments(e)}}class Qc{async loadAndSplit(e){if(void 0===e)throw new Error("You must pass a text splitter to use this method.");const t=await this.load();return e.invoke(t)}}class ed extends Qc{constructor(e){super(),Object.defineProperty(this,"filePathOrBlob",{enumerable:!0,configurable:!0,writable:!0,value:e})}async parse(e){return[e]}async load(){let e,t;if("string"==typeof this.filePathOrBlob){const{readFile:r}=await ed.imports();e=await r(this.filePathOrBlob,"utf8"),t={source:this.filePathOrBlob}}else e=await this.filePathOrBlob.text(),t={source:"blob",blobType:this.filePathOrBlob.type};const r=await this.parse(e);return r.forEach(((e,t)=>{if("string"!=typeof e)throw new Error(`Expected string, at position ${t} got ${typeof e}`)})),r.map(((e,n)=>new Yc({pageContent:e,metadata:1===r.length?t:{...t,line:n+1}})))}static async imports(){try{const{readFile:e}=await import("node:fs/promises");return{readFile:e}}catch(e){throw new Error(`Failed to load fs/promises. TextLoader available only on environment 'node'. It appears you are running environment '${di()}'. See https:// for alternatives.`)}}}class td extends $l{constructor(e){super(e),Object.defineProperty(this,"callbacks",{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,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){return this.getRelevantDocuments(e,Lu(t))}async getRelevantDocuments(e,t){const r=Lu((n=t)?Array.isArray(n)||"name"in n?{callbacks:n}:n:{});var n;const i=await mu.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),a=await(i?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const t=await this._getRelevantDocuments(e,a);return await(a?.handleRetrieverEnd(t)),t}catch(e){throw await(a?.handleRetrieverError(e)),e}}}class rd extends td{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,"mmr"===e.searchType&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if("mmr"===this.searchType){if("function"!=typeof this.vectorStore.maxMarginalRelevanceSearch)throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}}class nd extends li{constructor(e,t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","vectorstores",this._vectorstoreType()]}),Object.defineProperty(this,"embeddings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map((e=>e[0]))}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,i,a){if("number"==typeof e)return new rd({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:r});{const t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return new rd("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}}function id(e,t){let r=0,n=0,i=0;for(let a=0;at.map((t=>r(e,t))).map((e=>Number.isNaN(e)?0:e))))}(e,t,ad)}function od(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const i=sd(Array.isArray(e[0])?e:[e],t)[0],a=function(e){if(0===e.length)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;nt&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}(i).maxIndex,s=[t[a]],o=[a];for(;o.length{if(o.includes(i))return;const s=Math.max(...a[i]),u=r*t-(1-r)*s;u>e&&(e=u,n=i)})),s.push(t[n]),o.push(n)}return o}class ud extends nd{_vectorstoreType(){return"memory"}constructor(e,{similarity:t,...r}={}){super(e,r),Object.defineProperty(this,"memoryVectors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"similarity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.similarity=t??id}async addDocuments(e){const t=e.map((({pageContent:e})=>e));return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){const r=e.map(((e,r)=>({content:t[r].pageContent,embedding:e,metadata:t[r].metadata,id:t[r].id})));this.memoryVectors=this.memoryVectors.concat(r)}async _queryVectors(e,t,r){return this.memoryVectors.filter((e=>{if(!r)return!0;const t=new Yc({metadata:e.metadata,pageContent:e.content,id:e.id});return r(t)})).map(((t,r)=>({similarity:this.similarity(e,t.embedding),index:r,metadata:t.metadata,content:t.content,embedding:t.embedding,id:t.id}))).sort(((e,t)=>e.similarity>t.similarity?-1:0)).slice(0,t)}async similaritySearchVectorWithScore(e,t,r){return(await this._queryVectors(e,t,r)).map((e=>[new Yc({metadata:e.metadata,pageContent:e.content,id:e.id}),e.similarity]))}async maxMarginalRelevanceSearch(e,t){const r=await this.embeddings.embedQuery(e),n=await this._queryVectors(r,t.fetchK??20,t.filter);return od(r,n.map((e=>e.embedding)),t.lambda,t.k).map((e=>new Yc({metadata:n[e].metadata,pageContent:n[e].content,id:n[e].id})))}static async fromTexts(e,t,r,n){const i=[];for(let r=0;r0?o-4:o;for(i=0;i>16&255,l[c++]=n>>8&255,l[c++]=255&n;2===u&&(n=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,l[c++]=255&n);1===u&&(n=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,l[c++]=n>>8&255,l[c++]=255&n);return l},cd.fromByteArray=function(t){for(var r,n=t.length,i=n%3,a=[],o=16383,u=0,l=n-i;ul?l:u+o));1===i?(r=t[n-1],a.push(e[r>>2]+e[r<<4&63]+"==")):2===i&&(r=(t[n-2]<<8)+t[n-1],a.push(e[r>>10]+e[r>>4&63]+e[r<<2&63]+"="));return a.join("")};for(var e=[],t=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)e[i]=n[i],t[n.charCodeAt(i)]=i;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function s(t,r,n){for(var i,a,s=[],o=r;o>18&63]+e[a>>12&63]+e[a>>6&63]+e[63&a]);return s.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,cd}(),hd=B(dd),pd=Object.defineProperty;function fd(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let r=Array.from({length:e.length},((e,t)=>({start:t,end:t+1})));for(;r.length>1;){let n=null;for(let i=0;it.get(e.slice(r.start,r.end).join(",")))).filter((e=>null!=e))}var md,gd=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split("\n").filter(Boolean).reduce(((e,t)=>{const[r,n,...i]=t.split(" "),a=Number.parseInt(n,10);return i.forEach(((t,r)=>e[t]=a+r)),e}),{});for(const[e,t]of Object.entries(r)){const r=hd.toByteArray(e);this.rankMap.set(r.join(","),t),this.textMap.set(t,r)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce(((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e)),{})}encode(e,t=[],r="all"){const n=new RegExp(this.patStr,"ug"),i=gd.specialTokenRegex(Object.keys(this.specialTokens)),a=[],s=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter((e=>!s.has(e))):r);if(o.size>0){const t=gd.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw new Error(`The text contains a special token that is not allowed: ${r[0]}`)}let u=0;for(;;){let t=null,r=u;for(;i.lastIndex=r,t=i.exec(e),null!=t&&!s.has(t[0]);)r=t.index+1;const o=t?.index??e.length;for(const t of e.substring(u,o).matchAll(n)){const e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));null==r?a.push(...fd(e,this.rankMap)):a.push(r)}if(null==t)break;let l=this.specialTokens[t[0]];a.push(l),u=t.index+t[0].length}return a}decode(e){const t=[];let r=0;for(let n=0;nnew RegExp(e.map((e=>e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&"))).join("|"),"g"),((e,t,r)=>{t in e?pd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(gd,"specialTokenRegex"+"",md);class yd extends Xc{constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","document_transformers","text_splitters"]}),Object.defineProperty(this,"chunkSize",{enumerable:!0,configurable:!0,writable:!0,value:1e3}),Object.defineProperty(this,"chunkOverlap",{enumerable:!0,configurable:!0,writable:!0,value:200}),Object.defineProperty(this,"keepSeparator",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lengthFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chunkSize=e?.chunkSize??this.chunkSize,this.chunkOverlap=e?.chunkOverlap??this.chunkOverlap,this.keepSeparator=e?.keepSeparator??this.keepSeparator,this.lengthFunction=e?.lengthFunction??(e=>e.length),this.chunkOverlap>=this.chunkSize)throw new Error("Cannot have chunkOverlap >= chunkSize")}async transformDocuments(e,t={}){return this.splitDocuments(e,t)}splitOnSeparator(e,t){let r;if(t)if(this.keepSeparator){const n=t.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");r=e.split(new RegExp(`(?=${n})`))}else r=e.split(t);else r=e.split("");return r.filter((e=>""!==e))}async createDocuments(e,t=[],r={}){const n=t.length>0?t:[...Array(e.length)].map((()=>({}))),{chunkHeader:i="",chunkOverlapHeader:a="(cont'd) ",appendChunkOverlapHeader:s=!1}=r,o=new Array;for(let t=0;th){u-=this.numberOfNewLines(r,h,e)}s&&(d+=a)}const p=this.numberOfNewLines(e),f=n[t].loc&&"object"==typeof n[t].loc?{...n[t].loc}:{};f.lines={from:u,to:u+p};const m={...n[t],loc:f};d+=e,o.push(new Yc({pageContent:d,metadata:m})),u+=p,l=e,c=h}}return o}numberOfNewLines(e,t,r){return(e.slice(t,r).match(/\n/g)||[]).length}async splitDocuments(e,t={}){const r=e.filter((e=>void 0!==e.pageContent)),n=r.map((e=>e.pageContent)),i=r.map((e=>e.metadata));return this.createDocuments(n,i,t)}joinDocs(e,t){const r=e.join(t).trim();return""===r?null:r}async mergeSplits(e,t){const r=[],n=[];let i=0;for(const a of e){const e=await this.lengthFunction(a);if(i+e+n.length*t.length>this.chunkSize&&(this.chunkSize,n.length>0)){const a=this.joinDocs(n,t);for(null!==a&&r.push(a);i>this.chunkOverlap||i+e+n.length*t.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(n[0]),n.shift()}n.push(a),i+=e}const a=this.joinDocs(n,t);return null!==a&&r.push(a),r}}class bd extends yd{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:["\n\n","\n"," ",""]}),this.separators=e?.separators??this.separators,this.keepSeparator=e?.keepSeparator??!0}async _splitText(e,t){const r=[];let n,i=t[t.length-1];for(let r=0;r","
","

","
","

  • ","

    ","

    ","

    ","

    ","

    ","
    ","","","","
    ","","
      ","
        ","
        ","