@checksum-ai/runtime 4.13.1 → 4.14.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,97 @@
1
- "use strict";var wr=Object.create;var ce=Object.defineProperty;var Nr=Object.getOwnPropertyDescriptor;var xr=Object.getOwnPropertyNames;var Dr=Object.getPrototypeOf,Lr=Object.prototype.hasOwnProperty;var a=(t,e)=>ce(t,"name",{value:e,configurable:!0});var W=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Or=(t,e)=>{for(var r in e)ce(t,r,{get:e[r],enumerable:!0})},st=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xr(e))!Lr.call(t,o)&&o!==r&&ce(t,o,{get:()=>e[o],enumerable:!(n=Nr(e,o))||n.enumerable});return t};var le=(t,e,r)=>(r=t!=null?wr(Dr(t)):{},st(e||!t||!t.__esModule?ce(r,"default",{value:t,enumerable:!0}):r,t)),Mr=t=>st(ce({},"__esModule",{value:!0}),t);var Le=W((yo,dt)=>{dt.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var he=W(ut=>{var pt={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Ur(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}a(Ur,"E");for(let t of Object.keys(pt))ut[t]=Ur(pt[t])});var yt=W((Io,ht)=>{var Pr=require("fs"),U=require("path"),ft=Le(),Fr=he(),Br=typeof process=="object"&&process.platform==="win32",gt=a(t=>typeof t=="object"&&t!==null,"is_Obj"),mt=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function L(t){this.sep=U.sep,this.fs=Pr,gt(t)&&gt(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}a(L,"Utils");ht.exports=L;L.prototype.makeDir=function(t){let e=this;function r(n){let o=n.split(e.sep)[0];n.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var s;try{s=e.fs.statSync(o)}catch(l){if(l.message&&l.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw l}if(s&&s.isFile())throw Fr.FILE_IN_THE_WAY(`"${o}"`)}})}a(r,"mkdirSync"),r(t)};L.prototype.writeFileTo=function(t,e,r,n){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var s=U.dirname(t);o.fs.existsSync(s)||o.makeDir(s);var l;try{l=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),l=o.fs.openSync(t,"w",438)}if(l)try{o.fs.writeSync(l,e,0,e.length,0)}finally{o.fs.closeSync(l)}return o.fs.chmodSync(t,n||438),!0};L.prototype.writeFileToAsync=function(t,e,r,n,o){typeof n=="function"&&(o=n,n=void 0);let c=this;c.fs.exists(t,function(s){if(s&&!r)return o(!1);c.fs.stat(t,function(l,u){if(s&&u&&u.isDirectory())return o(!1);var g=U.dirname(t);c.fs.exists(g,function(y){if(!y)try{c.makeDir(g)}catch{return o(!1)}let T=a(function(v){c.fs.write(v,e,0,e.length,0,function(A){c.fs.close(v,function(){if(A)return o(!1);c.fs.chmod(t,n||438,function(){o(!0)})})})},"writeToFd");c.fs.open(t,"w",438,function(v,A){v?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(d,f){if(d||!f)return o(!1);T(f)})}):A?T(A):o(!1)})})})})};L.prototype.findFiles=function(t){let e=this;function r(n,o,c,s){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(n).forEach(function(u){let g=U.join(n,u),y=e.fs.statSync(g);if((!o||o.test(g))&&l.push(U.normalize(g)+(y.isDirectory()?e.sep:"")),y.isDirectory()&&c){let T=e.fs.realpathSync(g);s.has(T)||(s.add(T),l=l.concat(r(g,o,c,s)))}}),l}return a(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};L.prototype.findFilesAsync=function(t,e){let r=this,n=[],o=!1,c=a(function(l){o||(o=!0,e(l,l?void 0:n))},"finish"),s=a(function(l,u,g){r.fs.readdir(l,function(y,T){if(y)return g(y);let v=T.length;if(!v)return g();T.forEach(function(A){let d=U.join(l,A);r.fs.stat(d,function(f,p){if(f)return g(f);if(!p){--v||g();return}if(n.push(U.normalize(d)+(p.isDirectory()?r.sep:"")),!p.isDirectory()){--v||g();return}r.fs.realpath(d,function(h,E){if(h)return g(h);if(u.has(E)){--v||g();return}u.add(E),s(d,u,function(i){if(i)return g(i);--v||g()})})})})})},"walk");r.fs.realpath(t,function(l,u){if(l)return c(l);s(t,new Set([u]),c)})};L.prototype.getAttributes=function(){};L.prototype.setAttributes=function(){};L.crc32update=function(t,e){return mt[(t^e)&255]^t>>>8};L.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=L.crc32update(r,t[n++]);return~r>>>0};L.methodToString=function(t){switch(t){case ft.STORED:return"STORED ("+t+")";case ft.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};L.canonical=function(t){if(!t)return"";let e=U.posix.normalize("/"+t.split("\\").join("/"));return U.join(".",e)};L.zipnamefix=function(t){if(!t)return"";let e=U.posix.normalize("/"+t.split("\\").join("/"));return U.posix.join(".",e)};L.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};L.sanitize=function(t,e){t=U.resolve(U.normalize(t));for(var r=e.split("/"),n=0,o=r.length;n<o;n++){var c=U.normalize(U.join(t,r.slice(n,o).join(U.sep)));if(c===t||c.startsWith(t+U.sep))return c}return U.normalize(U.join(t,U.basename(e)))};L.toBuffer=a(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");L.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};L.writeBigUInt64LE=function(t,e,r){let n=e>>>0,o=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(o,r+4)};L.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};L.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};L.isWin=Br;L.crcTable=mt});var Tt=W((Ro,Et)=>{var Hr=require("path");Et.exports=function(t,{fs:e}){var r=t||"",n=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return a(c,"newAttr"),r&&e.existsSync(r)?(o=e.statSync(r),n.directory=o.isDirectory(),n.mtime=o.mtime,n.atime=o.atime,n.executable=(73&o.mode)!==0,n.readonly=(128&o.mode)===0,n.hidden=Hr.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:a(function(){},"decodeAttributes"),encodeAttributes:a(function(){},"encodeAttributes"),toJSON:a(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var _t=W((Co,It)=>{It.exports={efs:!0,encode:a(t=>Buffer.from(t,"utf8"),"encode"),decode:a(t=>t.toString("utf8"),"decode")}});var ne=W((vo,re)=>{re.exports=yt();re.exports.Constants=Le();re.exports.Errors=he();re.exports.FileAttr=Tt();re.exports.decoder=_t()});var St=W((bo,Rt)=>{var q=ne(),I=q.Constants;Rt.exports=function(){var t=20,e=10,r=0,n=0,o=0,c=0,s=0,l=0,u=0,g=0,y=0,T=0,v=0,A=0,d=0;t|=q.isWin?2560:768,r|=I.FLG_EFS;let f={extraLen:0},p=a(i=>Math.max(0,i)>>>0,"uint32"),h=a(i=>Math.max(0,i)&65535,"uint16"),E=a(i=>Math.max(0,i)&255,"uint8");return o=q.fromDate2DOS(new Date),{get made(){return t},set made(i){t=i},get version(){return e},set version(i){e=i},get flags(){return r},set flags(i){r=i},get flags_efs(){return(r&I.FLG_EFS)>0},set flags_efs(i){i?r|=I.FLG_EFS:r&=~I.FLG_EFS},get flags_desc(){return(r&I.FLG_DESC)>0},set flags_desc(i){i?r|=I.FLG_DESC:r&=~I.FLG_DESC},get method(){return n},set method(i){switch(i){case I.STORED:this.version=10;break;case I.DEFLATED:default:this.version=20}n=i},get time(){return q.fromDOS2Date(this.timeval)},set time(i){i=new Date(i),this.timeval=q.fromDate2DOS(i)},get timeval(){return o},set timeval(i){o=p(i)},get timeHighByte(){return E(o>>>8)},get crc(){return c},set crc(i){c=p(i)},get compressedSize(){return s},set compressedSize(i){s=p(i)},get size(){return l},set size(i){l=p(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return g},set extraLength(i){g=i},get extraLocalLength(){return f.extraLen},set extraLocalLength(i){f.extraLen=i},get commentLength(){return y},set commentLength(i){y=i},get diskNumStart(){return T},set diskNumStart(i){T=p(i)},get inAttr(){return v},set inAttr(i){v=p(i)},get attr(){return A},set attr(i){A=p(i)},get fileAttr(){return(A||0)>>16&4095},get offset(){return d},set offset(i){d=p(i)},get encrypted(){return(r&I.FLG_ENC)===I.FLG_ENC},get centralHeaderSize(){return I.CENHDR+u+g+y},get realDataOffset(){return d+I.LOCHDR+f.fnameLen+f.extraLen},get localHeader(){return f},loadLocalHeaderFromBinary:a(function(i){var m=i.slice(d,d+I.LOCHDR);if(m.readUInt32LE(0)!==I.LOCSIG)throw q.Errors.INVALID_LOC();f.version=m.readUInt16LE(I.LOCVER),f.flags=m.readUInt16LE(I.LOCFLG),f.flags_desc=(f.flags&I.FLG_DESC)>0,f.method=m.readUInt16LE(I.LOCHOW),f.time=m.readUInt32LE(I.LOCTIM),f.crc=m.readUInt32LE(I.LOCCRC),f.compressedSize=m.readUInt32LE(I.LOCSIZ),f.size=m.readUInt32LE(I.LOCLEN),f.fnameLen=m.readUInt16LE(I.LOCNAM),f.extraLen=m.readUInt16LE(I.LOCEXT);let R=d+I.LOCHDR+f.fnameLen,S=R+f.extraLen;return i.slice(R,S)},"loadLocalHeaderFromBinary"),loadFromBinary:a(function(i){if(i.length!==I.CENHDR||i.readUInt32LE(0)!==I.CENSIG)throw q.Errors.INVALID_CEN();t=i.readUInt16LE(I.CENVEM),e=i.readUInt16LE(I.CENVER),r=i.readUInt16LE(I.CENFLG),n=i.readUInt16LE(I.CENHOW),o=i.readUInt32LE(I.CENTIM),c=i.readUInt32LE(I.CENCRC),s=i.readUInt32LE(I.CENSIZ),l=i.readUInt32LE(I.CENLEN),u=i.readUInt16LE(I.CENNAM),g=i.readUInt16LE(I.CENEXT),y=i.readUInt16LE(I.CENCOM),T=i.readUInt16LE(I.CENDSK),v=i.readUInt16LE(I.CENATT),A=i.readUInt32LE(I.CENATX),d=i.readUInt32LE(I.CENOFF)},"loadFromBinary"),localHeaderToBinary:a(function(){var i=Buffer.alloc(I.LOCHDR);return i.writeUInt32LE(I.LOCSIG,0),i.writeUInt16LE(e,I.LOCVER),i.writeUInt16LE(r&~I.FLG_DESC,I.LOCFLG),i.writeUInt16LE(n,I.LOCHOW),i.writeUInt32LE(o,I.LOCTIM),i.writeUInt32LE(c,I.LOCCRC),i.writeUInt32LE(s,I.LOCSIZ),i.writeUInt32LE(l,I.LOCLEN),i.writeUInt16LE(u,I.LOCNAM),i.writeUInt16LE(f.extraLen,I.LOCEXT),i},"localHeaderToBinary"),centralHeaderToBinary:a(function(){var i=Buffer.alloc(I.CENHDR+u+g+y);return i.writeUInt32LE(I.CENSIG,0),i.writeUInt16LE(t,I.CENVEM),i.writeUInt16LE(e,I.CENVER),i.writeUInt16LE(r&~I.FLG_DESC,I.CENFLG),i.writeUInt16LE(n,I.CENHOW),i.writeUInt32LE(o,I.CENTIM),i.writeUInt32LE(c,I.CENCRC),i.writeUInt32LE(s,I.CENSIZ),i.writeUInt32LE(l,I.CENLEN),i.writeUInt16LE(u,I.CENNAM),i.writeUInt16LE(g,I.CENEXT),i.writeUInt16LE(y,I.CENCOM),i.writeUInt16LE(T,I.CENDSK),i.writeUInt16LE(v,I.CENATT),i.writeUInt32LE(A,I.CENATX),i.writeUInt32LE(d,I.CENOFF),i},"centralHeaderToBinary"),toJSON:a(function(){let i=a(function(m){return m+" bytes"},"bytes");return{made:t,version:e,flags:r,method:q.methodToString(n),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:i(s),size:i(l),fileNameLength:i(u),extraLength:i(g),commentLength:i(y),diskNumStart:T,inAttr:v,attr:A,offset:d,centralHeaderSize:i(I.CENHDR+u+g+y)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var At=W((No,Ct)=>{var K=ne(),C=K.Constants;Ct.exports=function(){var t=0,e=0,r=0,n=0,o=0;let c=a(()=>t>C.EF_ZIP64_OR_16||e>C.EF_ZIP64_OR_16||r>C.EF_ZIP64_OR_32||n>C.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(s){t=e=s},get totalEntries(){return e},set totalEntries(s){e=t=s},get size(){return r},set size(s){r=s},get offset(){return n},set offset(s){n=s},get commentLength(){return o},set commentLength(s){o=s},get mainHeaderSize(){return(c()?C.ZIP64HDR+C.END64HDR:0)+C.ENDHDR+o},loadFromBinary:a(function(s){if((s.length!==C.ENDHDR||s.readUInt32LE(0)!==C.ENDSIG)&&(s.length<C.ZIP64HDR||s.readUInt32LE(0)!==C.ZIP64SIG))throw K.Errors.INVALID_END();s.readUInt32LE(0)===C.ENDSIG?(t=s.readUInt16LE(C.ENDSUB),e=s.readUInt16LE(C.ENDTOT),r=s.readUInt32LE(C.ENDSIZ),n=s.readUInt32LE(C.ENDOFF),o=s.readUInt16LE(C.ENDCOM)):(t=K.readBigUInt64LE(s,C.ZIP64SUB),e=K.readBigUInt64LE(s,C.ZIP64TOT),r=K.readBigUInt64LE(s,C.ZIP64SIZB),n=K.readBigUInt64LE(s,C.ZIP64OFF),o=0)},"loadFromBinary"),toBinary:a(function(){if(!c()){var s=Buffer.alloc(C.ENDHDR+o);return s.writeUInt32LE(C.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,C.ENDSUB),s.writeUInt16LE(e,C.ENDTOT),s.writeUInt32LE(r,C.ENDSIZ),s.writeUInt32LE(n,C.ENDOFF),s.writeUInt16LE(o,C.ENDCOM),s.fill(" ",C.ENDHDR),s}var s=Buffer.alloc(this.mainHeaderSize);let l=0;s.writeUInt32LE(C.ZIP64SIG,l),K.writeBigUInt64LE(s,C.ZIP64HDR-C.ZIP64LEAD,l+C.ZIP64SIZE),s.writeUInt16LE(45,l+C.ZIP64VEM),s.writeUInt16LE(45,l+C.ZIP64VER),s.writeUInt32LE(0,l+C.ZIP64DSK),s.writeUInt32LE(0,l+C.ZIP64DSKDIR),K.writeBigUInt64LE(s,t,l+C.ZIP64SUB),K.writeBigUInt64LE(s,e,l+C.ZIP64TOT),K.writeBigUInt64LE(s,r,l+C.ZIP64SIZB),K.writeBigUInt64LE(s,n,l+C.ZIP64OFF);let u=n+r;return l+=C.ZIP64HDR,s.writeUInt32LE(C.END64SIG,l),s.writeUInt32LE(0,l+C.END64START),K.writeBigUInt64LE(s,u,l+C.END64OFF),s.writeUInt32LE(1,l+C.END64NUMDISKS),l+=C.END64HDR,s.writeUInt32LE(C.ENDSIG,l),s.writeUInt32LE(0,l+4),s.writeUInt16LE(Math.min(t,C.EF_ZIP64_OR_16),l+C.ENDSUB),s.writeUInt16LE(Math.min(e,C.EF_ZIP64_OR_16),l+C.ENDTOT),s.writeUInt32LE(Math.min(r,C.EF_ZIP64_OR_32),l+C.ENDSIZ),s.writeUInt32LE(Math.min(n,C.EF_ZIP64_OR_32),l+C.ENDOFF),s.writeUInt16LE(o,l+C.ENDCOM),s.fill(" ",l+C.ENDHDR),s},"toBinary"),toJSON:a(function(){let s=a(function(l,u){let g=l.toString(16).toUpperCase();for(;g.length<u;)g="0"+g;return"0x"+g},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:s(n,4),commentLength:o}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Me=W(Oe=>{Oe.EntryHeader=St();Oe.MainHeader=At()});var bt=W((Lo,vt)=>{vt.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:a(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:a(function(n){var o=e.createDeflateRaw(r),c=[],s=0;o.on("data",function(l){c.push(l),s+=l.length}),o.on("end",function(){var l=Buffer.alloc(s),u=0;l.fill(0);for(var g=0;g<c.length;g++){var y=c[g];y.copy(l,u),u+=y.length}n&&n(l)}),o.end(t)},"deflateAsync")}}});var xt=W((Mo,Nt)=>{var wt,Wr=+(((wt=process==null?void 0:process.versions)==null?void 0:wt.node)??"").split(".")[0]||0;Nt.exports=function(t,e){var r=require("zlib");let n=Wr>=15&&e>0?{maxOutputLength:e}:{};return{inflate:a(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:a(function(o){var c=r.createInflateRaw(n),s=[],l=0;c.on("data",function(u){s.push(u),l+=u.length}),c.on("end",function(){var u=Buffer.alloc(l),g=0;u.fill(0);for(var y=0;y<s.length;y++){var T=s[y];T.copy(u,g),g+=T.length}o&&o(u)}),c.end(t)},"inflateAsync")}}});var kt=W((Uo,Mt)=>{"use strict";var{randomFillSync:Dt}=require("crypto"),$r=he(),Gr=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Ot=a((t,e)=>Math.imul(t,e)>>>0,"uMul"),Lt=a((t,e)=>Gr[(t^e)&255]^t>>>8,"crc32update"),de=a(()=>typeof Dt=="function"?Dt(Buffer.alloc(12)):de.node(),"genSalt");de.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ye={genSalt:de};function Ee(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}a(Ee,"Initkeys");Ee.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Lt(e[0],t),e[1]+=e[0]&255,e[1]=Ot(e[1],134775813)+1,e[2]=Lt(e[2],e[1]>>>24),t};Ee.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Ot(t,t^1)>>8&255};function Zr(t){let e=new Ee(t);return function(r){let n=Buffer.alloc(r.length),o=0;for(let c of r)n[o++]=e.updateKeys(c^e.next());return n}}a(Zr,"make_decrypter");function Vr(t){let e=new Ee(t);return function(r,n,o=0){n||(n=Buffer.alloc(r.length));for(let c of r){let s=e.next();n[o++]=c^s,e.updateKeys(c)}return n}}a(Vr,"make_encrypter");function jr(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Zr(r),o=n(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw $r.WRONG_PASSWORD();return n(t.slice(12))}a(jr,"decrypt");function Kr(t){Buffer.isBuffer(t)&&t.length>=12?ye.genSalt=function(){return t.slice(0,12)}:t==="node"?ye.genSalt=de.node:ye.genSalt=de}a(Kr,"_salter");function zr(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Vr(r),c=ye.genSalt();c[11]=e.crc>>>24&255,n&&(c[10]=e.crc>>>16&255);let s=Buffer.alloc(t.length+12);return o(c,s),o(t,s,12)}a(zr,"encrypt");Mt.exports={decrypt:jr,encrypt:zr,_salter:Kr}});var Ut=W(Te=>{Te.Deflater=bt();Te.Inflater=xt();Te.ZipCrypto=kt()});var Ue=W((Bo,Pt)=>{var D=ne(),Jr=Me(),j=D.Constants,ke=Ut();Pt.exports=function(t,e){var r=new Jr.EntryHeader,n=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,s=null,l=Buffer.alloc(0),u=Buffer.alloc(0),g=!0;let y=t,T=typeof y.decoder=="object"?y.decoder:D.decoder;g=T.hasOwnProperty("efs")?T.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}a(v,"getCompressedDataFromZip");function A(i){let m=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return D.crc32(i)===m}a(A,"crc32OK");function d(i,m,R){if(typeof m>"u"&&typeof i=="string"&&(R=i,i=void 0),c)return i&&m&&m(Buffer.alloc(0),D.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var S=v();if(S.length===0)return i&&m&&m(S),S;if(r.encrypted){if(typeof R!="string"&&!Buffer.isBuffer(R))throw D.Errors.INVALID_PASS_PARAM();S=ke.ZipCrypto.decrypt(S,r,R)}var _;switch(r.method){case D.Constants.STORED:if(_=Buffer.alloc(S.length),S.copy(_),A(_))return i&&m&&m(_),_;throw i&&m&&m(_,D.Errors.BAD_CRC()),D.Errors.BAD_CRC();case D.Constants.DEFLATED:var b=new ke.Inflater(S,r.size);if(i)b.inflateAsync(function(w){m&&(A(w)?m(w):m(w,D.Errors.BAD_CRC()))});else{if(_=b.inflate(),!A(_))throw D.Errors.BAD_CRC(`"${T.decode(n)}"`);return _}break;default:throw i&&m&&m(Buffer.alloc(0),D.Errors.UNKNOWN_METHOD()),D.Errors.UNKNOWN_METHOD()}}a(d,"decompress");function f(i,m){if((!s||!s.length)&&Buffer.isBuffer(e))return i&&m&&m(v()),v();if(s.length&&!c){var R;switch(r.method){case D.Constants.STORED:return r.compressedSize=r.size,R=Buffer.alloc(s.length),s.copy(R),i&&m&&m(R),R;default:case D.Constants.DEFLATED:var S=new ke.Deflater(s);if(i)S.deflateAsync(function(b){R=Buffer.alloc(b.length),r.compressedSize=b.length,b.copy(R),m&&m(R)});else{var _=S.deflate();return r.compressedSize=_.length,_}S=null;break}}else if(i&&m)m(Buffer.alloc(0));else return Buffer.alloc(0)}a(f,"compress");function p(i,m){return D.readBigUInt64LE(i,m)}a(p,"readUInt64LE");function h(i){try{for(var m=0,R,S,_;m+4<i.length;)R=i.readUInt16LE(m),m+=2,S=i.readUInt16LE(m),m+=2,_=i.slice(m,m+S),m+=S,j.ID_ZIP64===R&&E(_)}catch{throw D.Errors.EXTRA_FIELD_PARSE_ERROR()}}a(h,"parseExtra");function E(i){var m,R,S,_;i.length>=j.EF_ZIP64_SCOMP&&(m=p(i,j.EF_ZIP64_SUNCOMP),r.size===j.EF_ZIP64_OR_32&&(r.size=m)),i.length>=j.EF_ZIP64_RHO&&(R=p(i,j.EF_ZIP64_SCOMP),r.compressedSize===j.EF_ZIP64_OR_32&&(r.compressedSize=R)),i.length>=j.EF_ZIP64_DSN&&(S=p(i,j.EF_ZIP64_RHO),r.offset===j.EF_ZIP64_OR_32&&(r.offset=S)),i.length>=j.EF_ZIP64_DSN+4&&(_=i.readUInt32LE(j.EF_ZIP64_DSN),r.diskNumStart===j.EF_ZIP64_OR_16&&(r.diskNumStart=_))}return a(E,"parseZip64ExtendedInformation"),{get entryName(){return T.decode(n)},get rawEntryName(){return n},set entryName(i){n=D.toBuffer(i,T.encode);var m=n[n.length-1];c=m===47||m===92,r.fileNameLength=n.length},get efs(){return typeof g=="function"?g(this.entryName):g},get extra(){return l},set extra(i){l=i,r.extraLength=i.length,h(i)},get comment(){return T.decode(o)},set comment(i){if(o=D.toBuffer(i,T.encode),r.commentLength=o.length,o.length>65535)throw D.Errors.COMMENT_TOO_LONG()},get name(){let i=T.decode(n);return c?i.replace(/[/\\]$/,"").split("/").pop():i.split("/").pop()},get isDirectory(){return c},getCompressedData:a(function(){return f(!1,null)},"getCompressedData"),getCompressedDataAsync:a(function(i){f(!0,i)},"getCompressedDataAsync"),setData:a(function(i){s=D.toBuffer(i,D.decoder.encode),!c&&s.length?(r.size=s.length,r.method=D.Constants.DEFLATED,r.crc=D.crc32(i),r.changed=!0):r.method=D.Constants.STORED},"setData"),getData:a(function(i){return r.changed?s:d(!1,null,i)},"getData"),getDataAsync:a(function(i,m){r.changed?i(s):d(!0,i,m)},"getDataAsync"),set attr(i){r.attr=i},get attr(){return r.attr},set header(i){r.loadFromBinary(i)},get header(){return r},packCentralHeader:a(function(){r.flags_efs=this.efs,r.extraLength=l.length;var i=r.centralHeaderToBinary(),m=D.Constants.CENHDR;return n.copy(i,m),m+=n.length,l.copy(i,m),m+=r.extraLength,o.copy(i,m),i},"packCentralHeader"),packLocalHeader:a(function(){let i=0;r.flags_efs=this.efs,r.extraLocalLength=u.length;let m=r.localHeaderToBinary(),R=Buffer.alloc(m.length+n.length+r.extraLocalLength);return m.copy(R,i),i+=m.length,n.copy(R,i),i+=n.length,u.copy(R,i),i+=u.length,R},"packLocalHeader"),toJSON:a(function(){let i=a(function(m){return"<"+(m&&m.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:i(e),data:i(s)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Ht=W((Wo,Bt)=>{var Ft=Ue(),Yr=Me(),G=ne();Bt.exports=function(t,e){var r=[],n=Object.create(null),o=Buffer.alloc(0),c=new Yr.MainHeader,s=!1,l=null;let u=new Set,g=e,{noSort:y,decoder:T}=g;t?d(g.readEntries):s=!0;function v(){let p=new Set;for(let h of Object.keys(n)){let E=h.split("/");if(E.pop(),!!E.length)for(let i=0;i<E.length;i++){let m=E.slice(0,i+1).join("/")+"/";p.add(m)}}for(let h of p)if(!(h in n)){let E=new Ft(g);E.entryName=h,E.attr=16,E.temporary=!0,r.push(E),n[E.entryName]=E,u.add(E)}}a(v,"makeTemporaryFolders");function A(){if(s=!0,n=Object.create(null),c.diskEntries>(t.length-c.offset)/G.Constants.CENHDR)throw G.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var p=c.offset,h=0;h<r.length;h++){var E=p,i=new Ft(g,t);i.header=t.slice(E,E+=G.Constants.CENHDR),i.entryName=t.slice(E,E+=i.header.fileNameLength),i.header.extraLength&&(i.extra=t.slice(E,E+=i.header.extraLength)),i.header.commentLength&&(i.comment=t.slice(E,E+i.header.commentLength)),p+=i.header.centralHeaderSize,r[h]=i,n[i.entryName]=i}u.clear(),v()}a(A,"readEntries");function d(p){var h=t.length-G.Constants.ENDHDR,E=Math.max(0,h-65535),i=E,m=t.length,R=-1,S=0;for(typeof g.trailingSpace=="boolean"&&g.trailingSpace&&(E=0),h;h>=i;h--)if(t[h]===80){if(t.readUInt32LE(h)===G.Constants.ENDSIG){R=h,S=h,m=h+G.Constants.ENDHDR,i=h-G.Constants.END64HDR;continue}if(t.readUInt32LE(h)===G.Constants.END64SIG){i=E;continue}if(t.readUInt32LE(h)===G.Constants.ZIP64SIG){R=h,m=h+G.readBigUInt64LE(t,h+G.Constants.ZIP64SIZE)+G.Constants.ZIP64LEAD;break}}if(R==-1)throw G.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(R,m)),c.commentLength&&(o=t.slice(S+G.Constants.ENDHDR)),p&&A()}a(d,"readMainHeader");function f(){r.length>1&&!y&&(r=r.map(p=>({entry:p,key:p.entryName.toLowerCase()})).sort((p,h)=>p.key.localeCompare(h.key)).map(p=>p.entry))}return a(f,"sortEntries"),{get entries(){return s||A(),r.filter(p=>!u.has(p))},get comment(){return T.decode(o)},set comment(p){o=G.toBuffer(p,T.encode),c.commentLength=o.length},getEntryCount:a(function(){return s?r.length:c.diskEntries},"getEntryCount"),forEach:a(function(p){this.entries.forEach(p)},"forEach"),getEntry:a(function(p){return s||A(),n[p]||null},"getEntry"),setEntry:a(function(p){s||A(),r.push(p),n[p.entryName]=p,c.totalEntries=r.length},"setEntry"),deleteFile:a(function(p,h=!0){s||A();let E=n[p];this.getEntryChildren(E,h).map(m=>m.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:a(function(p){s||A();let h=n[p],E=r.indexOf(h);E>=0&&(r.splice(E,1),delete n[p],c.totalEntries=r.length)},"deleteEntry"),getEntryChildren:a(function(p,h=!0){if(s||A(),typeof p=="object")if(p.isDirectory&&h){let E=[],i=p.entryName;for(let m of r)m.entryName.startsWith(i)&&E.push(m);return E}else return[p];return[]},"getEntryChildren"),getChildCount:a(function(p){if(p&&p.isDirectory){let h=this.getEntryChildren(p);return h.includes(p)?h.length-1:h.length}return 0},"getChildCount"),compressToBuffer:a(function(){s||A(),f();let p=[],h=[],E=0,i=0;c.size=0,c.offset=0;let m=0;for(let _ of this.entries){let b=_.getCompressedData();_.header.offset=i;let w=_.packLocalHeader(),N=w.length+b.length;i+=N,p.push(w),p.push(b);let x=_.packCentralHeader();h.push(x),c.size+=x.length,E+=N+x.length,m++}E+=c.mainHeaderSize,c.offset=i,c.totalEntries=m,i=0;let R=Buffer.alloc(E);for(let _ of p)_.copy(R,i),i+=_.length;for(let _ of h)_.copy(R,i),i+=_.length;let S=c.toBinary();return o&&o.copy(S,S.length-o.length),S.copy(R,i),t=R,s=!1,R},"compressToBuffer"),toAsyncBuffer:a(function(p,h,E,i){try{s||A(),f();let m=[],R=[],S=0,_=0,b=0;c.size=0,c.offset=0;let w=a(function(N){if(N.length>0){let x=N.shift(),H=x.entryName+x.extra.toString();E&&E(H),x.getCompressedDataAsync(function($){i&&i(H),x.header.offset=_;let X=x.packLocalHeader(),me=X.length+$.length;_+=me,m.push(X),m.push($);let ae=x.packCentralHeader();R.push(ae),c.size+=ae.length,S+=me+ae.length,b++,w(N)})}else{S+=c.mainHeaderSize,c.offset=_,c.totalEntries=b,_=0;let x=Buffer.alloc(S);m.forEach(function($){$.copy(x,_),_+=$.length}),R.forEach(function($){$.copy(x,_),_+=$.length});let H=c.toBinary();o&&o.copy(H,H.length-o.length),H.copy(x,_),t=x,s=!1,p(x)}},"compress2Buffer");w(Array.from(this.entries))}catch(m){h(m)}},"toAsyncBuffer")}}});var Gt=W((Go,$t)=>{var M=ne(),O=require("path"),qr=Ue(),Xr=Ht(),Q=a((...t)=>M.findLast(t,e=>typeof e=="boolean"),"get_Bool"),Wt=a((...t)=>M.findLast(t,e=>typeof e=="string"),"get_Str"),Qr=a((...t)=>M.findLast(t,e=>typeof e=="function"),"get_Fun"),en={noSort:!1,readEntries:!1,method:M.Constants.NONE,fs:null};$t.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),en);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=M.Constants.BUFFER,t=void 0)),Object.assign(n,e);let o=new M(n),c=a(d=>{d.filter(f=>f.attr).sort((f,p)=>p.path.length-f.path.length).forEach(f=>o.fs.chmodSync(f.path,f.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=M.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))n.method=M.Constants.FILE,n.filename=t,r=o.fs.readFileSync(t);else throw M.Errors.INVALID_FILENAME();let s=new Xr(r,n),{canonical:l,sanitize:u,zipnamefix:g}=M;function y(d){if(d&&s){var f;if(typeof d=="string"&&(f=s.getEntry(O.posix.normalize(d))),typeof d=="object"&&typeof d.entryName<"u"&&typeof d.header<"u"&&(f=s.getEntry(d.entryName)),f)return f}return null}a(y,"getEntry");function T(d){let{join:f,normalize:p,sep:h}=O.posix;return f(O.isAbsolute(d)?"/":".",p(h+d.split("\\").join(h)+h))}a(T,"fixPath");function v(d){return d instanceof RegExp?(function(f){return function(p){return f.test(p)}})(d):typeof d!="function"?()=>!0:d}a(v,"filenameFilter");let A=a((d,f)=>{let p=f.slice(-1);return p=p===o.sep?o.sep:"",O.relative(d,f)+p},"relativePath");return{readFile:a(function(d,f){var p=y(d);return p&&p.getData(f)||null},"readFile"),childCount:a(function(d){let f=y(d);if(f)return s.getChildCount(f)},"childCount"),readFileAsync:a(function(d,f){var p=y(d);p?p.getDataAsync(f):f(null,"getEntry failed for:"+d)},"readFileAsync"),readAsText:a(function(d,f){var p=y(d);if(p){var h=p.getData();if(h&&h.length)return h.toString(f||"utf8")}return""},"readAsText"),readAsTextAsync:a(function(d,f,p){var h=y(d);h?h.getDataAsync(function(E,i){if(i){f(E,i);return}E&&E.length?f(E.toString(p||"utf8")):f("")}):f("")},"readAsTextAsync"),deleteFile:a(function(d,f=!0){var p=y(d);p&&s.deleteFile(p.entryName,f)},"deleteFile"),deleteEntry:a(function(d){var f=y(d);f&&s.deleteEntry(f.entryName)},"deleteEntry"),addZipComment:a(function(d){s.comment=d},"addZipComment"),getZipComment:a(function(){return s.comment||""},"getZipComment"),addZipEntryComment:a(function(d,f){var p=y(d);p&&(p.comment=f)},"addZipEntryComment"),getZipEntryComment:a(function(d){var f=y(d);return f&&f.comment||""},"getZipEntryComment"),updateFile:a(function(d,f){var p=y(d);p&&p.setData(f)},"updateFile"),addLocalFile:a(function(d,f,p,h){if(o.fs.existsSync(d)){f=f?T(f):"";let E=O.win32.basename(O.win32.normalize(d));f+=p||E;let i=o.fs.statSync(d),m=i.isFile()?o.fs.readFileSync(d):Buffer.alloc(0);i.isDirectory()&&(f+=o.sep),this.addFile(f,m,h,i)}else throw M.Errors.FILE_NOT_FOUND(d)},"addLocalFile"),addLocalFileAsync:a(function(d,f){d=typeof d=="object"?d:{localPath:d};let p=O.resolve(d.localPath),{comment:h}=d,{zipPath:E,zipName:i}=d,m=this;o.fs.stat(p,function(R,S){if(R)return f(R,!1);E=E?T(E):"";let _=O.win32.basename(O.win32.normalize(p));if(E+=i||_,S.isFile())o.fs.readFile(p,function(b,w){return b?f(b,!1):(m.addFile(E,w,h,S),setImmediate(f,void 0,!0))});else if(S.isDirectory())return E+=o.sep,m.addFile(E,Buffer.alloc(0),h,S),setImmediate(f,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:a(function(d,f,p){if(p=v(p),f=f?T(f):"",d=O.normalize(d),o.fs.existsSync(d)){let h=o.findFiles(d),E=this;if(h.length)for(let i of h){let m=O.join(f,A(d,i));p(m)&&E.addLocalFile(i,O.dirname(m))}}else throw M.Errors.FILE_NOT_FOUND(d)},"addLocalFolder"),addLocalFolderAsync:a(function(d,f,p,h){h=v(h),p=p?T(p):"",d=O.normalize(d);var E=this;o.fs.open(d,"r",function(i){if(i&&i.code==="ENOENT")f(void 0,M.Errors.FILE_NOT_FOUND(d));else if(i)f(void 0,i);else{var m=o.findFiles(d),R=-1,S=a(function(){if(R+=1,R<m.length){var _=m[R],b=A(d,_).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),h(b)?o.fs.stat(_,function(w,N){w&&f(void 0,w),N.isFile()?o.fs.readFile(_,function(x,H){x?f(void 0,x):(E.addFile(p+b,H,"",N),S())}):(E.addFile(p+b+"/",Buffer.alloc(0),"",N),S())}):process.nextTick(()=>{S()})}else f(!0,void 0)},"next");S()}})},"addLocalFolderAsync"),addLocalFolderAsync2:a(function(d,f){let p=this;d=typeof d=="object"?d:{localPath:d};let h=O.resolve(T(d.localPath)),{zipPath:E,filter:i,namefix:m}=d;i instanceof RegExp?i=(function(_){return function(b){return _.test(b)}})(i):typeof i!="function"&&(i=a(function(){return!0},"filter")),E=E?T(E):"",m==="latin1"&&(m=a(_=>_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof m!="function"&&(m=a(_=>_,"namefix"));let R=a(_=>O.join(E,m(A(h,_))),"relPathFix"),S=a(_=>O.win32.basename(O.win32.normalize(m(_))),"fileNameFix");o.fs.open(h,"r",function(_){_&&_.code==="ENOENT"?f(void 0,M.Errors.FILE_NOT_FOUND(h)):_?f(void 0,_):o.findFilesAsync(h,function(b,w){if(b)return f(b);w=w.filter(N=>i(R(N))),w.length||f(void 0,!1),setImmediate(w.reverse().reduce(function(N,x){return function(H,$){if(H||$===!1)return setImmediate(N,H,!1);p.addLocalFileAsync({localPath:x,zipPath:O.dirname(R(x)),zipName:S(x)},N)}},f))})})},"addLocalFolderAsync2"),addLocalFolderPromise:a(function(d,f){return new Promise((p,h)=>{this.addLocalFolderAsync2(Object.assign({localPath:d},f),(E,i)=>{E&&h(E),i&&p(this)})})},"addLocalFolderPromise"),addFile:a(function(d,f,p,h){d=g(d);let E=y(d),i=E!=null;i||(E=new qr(n),E.entryName=d),E.comment=p||"";let m=typeof h=="object"&&h instanceof o.fs.Stats;m&&(E.header.time=h.mtime);var R=E.isDirectory?16:0;let S=E.isDirectory?16384:32768;return m?S|=4095&h.mode:typeof h=="number"?S|=4095&h:S|=E.isDirectory?493:420,R=(R|S<<16)>>>0,E.attr=R,E.setData(f),i||s.setEntry(E),E},"addFile"),getEntries:a(function(d){return s.password=d,s?s.entries:[]},"getEntries"),getEntry:a(function(d){return y(d)},"getEntry"),getEntryCount:a(function(){return s.getEntryCount()},"getEntryCount"),forEach:a(function(d){return s.forEach(d)},"forEach"),extractEntryTo:a(function(d,f,p,h,E,i){h=Q(!1,h),E=Q(!1,E),p=Q(!0,p),i=Wt(E,i);var m=y(d);if(!m)throw M.Errors.NO_ENTRY();var R=l(m.entryName),S=u(f,i&&!m.isDirectory?l(i):p?R:O.basename(R));if(m.isDirectory){var _=s.getEntryChildren(m);return _.forEach(function(N){if(N.isDirectory)return;var x=N.getData();if(!x)throw M.Errors.CANT_EXTRACT_FILE();var H=l(p?N.entryName:N.entryName.substring(m.entryName.length)),$=u(f,H);let X=E?N.header.fileAttr:void 0;o.writeFileTo($,x,h,X)}),!0}var b=m.getData(s.password);if(!b)throw M.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(S)&&!h)throw M.Errors.CANT_OVERRIDE();let w=E?d.header.fileAttr:void 0;return o.writeFileTo(S,b,h,w),!0},"extractEntryTo"),test:a(function(d){if(!s)return!1;for(var f of s.entries)try{if(f.isDirectory)continue;var p=f.getData(d);if(!p)return!1}catch{return!1}return!0},"test"),extractAllTo:a(function(d,f,p,h){if(p=Q(!1,p),h=Wt(p,h),f=Q(!1,f),!s)throw M.Errors.NO_ZIP();let E=[];s.entries.forEach(function(i){var m=u(d,l(i.entryName));if(i.isDirectory){o.makeDir(m),p&&E.push({path:m,attr:i.header.fileAttr});return}var R=i.getData(h);if(!R)throw M.Errors.CANT_EXTRACT_FILE();let S=p?i.header.fileAttr:void 0;o.writeFileTo(m,R,f,S);try{o.fs.utimesSync(m,i.header.time,i.header.time)}catch{}}),c(E)},"extractAllTo"),extractAllToAsync:a(function(d,f,p,h){if(h=Qr(f,p,h),p=Q(!1,p),f=Q(!1,f),!h)return new Promise((b,w)=>{this.extractAllToAsync(d,f,p,function(N){N?w(N):b(this)})});if(!s){h(M.Errors.NO_ZIP());return}d=O.resolve(d);let E=a(b=>u(d,O.normalize(l(b.entryName))),"getPath"),i=a((b,w)=>new Error(b+': "'+w+'"'),"getError"),m=[],R=[];s.entries.forEach(b=>{b.isDirectory?m.push(b):R.push(b)});let S=[];for(let b of m){let w=E(b),N=p?b.header.fileAttr:void 0;try{o.makeDir(w)}catch{h(i("Unable to create folder",w));continue}N&&S.push({path:w,attr:N});try{o.fs.utimesSync(w,b.header.time,b.header.time)}catch{}}let _=a(b=>{if(!b)try{c(S)}catch(w){return h(i("Unable to set folder permissions",w.path||""))}h(b)},"done");R.reverse().reduce(function(b,w){return function(N){if(N)b(N);else{let x=O.normalize(l(w.entryName)),H=u(d,x);w.getDataAsync(function($,X){if(X)b(X);else if(!$)b(M.Errors.CANT_EXTRACT_FILE());else{let me=p?w.header.fileAttr:void 0;o.writeFileToAsync(H,$,f,me,function(ae){if(!ae)return b(i("Unable to write file",H));o.fs.utimes(H,w.header.time,w.header.time,function(){b()})})}})}}},_)()},"extractAllToAsync"),writeZip:a(function(d,f){if(arguments.length===1&&typeof d=="function"&&(f=d,d=""),!d&&n.filename&&(d=n.filename),!!d){var p=s.compressToBuffer();if(p){var h=o.writeFileTo(d,p,!0);typeof f=="function"&&f(h?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:a(function(d,f){let{overwrite:p,perm:h}=Object.assign({overwrite:!0},f);return new Promise((E,i)=>{!d&&n.filename&&(d=n.filename),d||i("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(m=>{let R=a(S=>S?E(S):i("ADM-ZIP: Wasn't able to write zip file"),"ret");o.writeFileToAsync(d,m,p,h,R)},i)})},"writeZipPromise"),toBufferPromise:a(function(){return new Promise((d,f)=>{s.toAsyncBuffer(d,f)})},"toBufferPromise"),toBuffer:a(function(d,f,p,h){return typeof d=="function"?(s.toAsyncBuffer(d,f,p,h),null):s.compressToBuffer()},"toBuffer")}}});var Yt=W((Ko,z)=>{var Fe=require("fs"),_e=require("path"),rn=require("os"),nn=require("crypto"),Vt=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function on(){return Vt[Math.floor(Math.random()*Vt.length)]}a(on,"_getRandomTip");function oe(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}a(oe,"parseBoolean");function sn(){return process.stdout.isTTY}a(sn,"supportsAnsi");function an(t){return sn()?`\x1B[2m${t}\x1B[0m`:t}a(an,"dim");var cn=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ln(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
- `);let n;for(;(n=cn.exec(r))!=null;){let o=n[1],c=n[2]||"";c=c.trim();let s=c[0];c=c.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),s==='"'&&(c=c.replace(/\\n/g,`
3
- `),c=c.replace(/\\r/g,"\r")),e[o]=c}return e}a(ln,"parse");function dn(t){t=t||{};let e=Jt(t);t.path=e;let r=P.configDotenv(t);if(!r.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=zt(t).split(","),o=n.length,c;for(let s=0;s<o;s++)try{let l=n[s].trim(),u=un(r,l);c=P.decrypt(u.ciphertext,u.key);break}catch(l){if(s+1>=o)throw l}return P.parse(c)}a(dn,"_parseVault");function pn(t){console.error(`\u26A0 ${t}`)}a(pn,"_warn");function pe(t){console.log(`\u2506 ${t}`)}a(pe,"_debug");function Kt(t){console.log(`\u25C7 ${t}`)}a(Kt,"_log");function zt(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}a(zt,"_dotenvKey");function un(t,e){let r;try{r=new URL(e)}catch(l){if(l.code==="ERR_INVALID_URL"){let u=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw u.code="INVALID_DOTENV_KEY",u}throw l}let n=r.password;if(!n){let l=new Error("INVALID_DOTENV_KEY: Missing key part");throw l.code="INVALID_DOTENV_KEY",l}let o=r.searchParams.get("environment");if(!o){let l=new Error("INVALID_DOTENV_KEY: Missing environment part");throw l.code="INVALID_DOTENV_KEY",l}let c=`DOTENV_VAULT_${o.toUpperCase()}`,s=t.parsed[c];if(!s){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${c} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:s,key:n}}a(un,"_instructions");function Jt(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)Fe.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=_e.resolve(process.cwd(),".env.vault");return Fe.existsSync(e)?e:null}a(Jt,"_vaultPath");function jt(t){return t[0]==="~"?_e.join(rn.homedir(),t.slice(1)):t}a(jt,"_resolveHome");function fn(t){let e=oe(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=oe(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Kt("loading env from encrypted .env.vault");let n=P._parseVault(t),o=process.env;return t&&t.processEnv!=null&&(o=t.processEnv),P.populate(o,n,t),{parsed:n}}a(fn,"_configVault");function gn(t){let e=_e.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let o=oe(n.DOTENV_CONFIG_DEBUG||t&&t.debug),c=oe(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:o&&pe("no encoding is specified (UTF-8 is used by default)");let s=[e];if(t&&t.path)if(!Array.isArray(t.path))s=[jt(t.path)];else{s=[];for(let y of t.path)s.push(jt(y))}let l,u={};for(let y of s)try{let T=P.parse(Fe.readFileSync(y,{encoding:r}));P.populate(u,T,t)}catch(T){o&&pe(`failed to load ${y} ${T.message}`),l=T}let g=P.populate(n,u,t);if(o=oe(n.DOTENV_CONFIG_DEBUG||o),c=oe(n.DOTENV_CONFIG_QUIET||c),o||!c){let y=Object.keys(g).length,T=[];for(let v of s)try{let A=_e.relative(process.cwd(),v);T.push(A)}catch(A){o&&pe(`failed to load ${v} ${A.message}`),l=A}Kt(`injected env (${y}) from ${T.join(",")} ${an(`// tip: ${on()}`)}`)}return l?{parsed:u,error:l}:{parsed:u}}a(gn,"configDotenv");function mn(t){if(zt(t).length===0)return P.configDotenv(t);let e=Jt(t);return e?P._configVault(t):(pn(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),P.configDotenv(t))}a(mn,"config");function hn(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),o=n.subarray(0,12),c=n.subarray(-16);n=n.subarray(12,-16);try{let s=nn.createDecipheriv("aes-256-gcm",r,o);return s.setAuthTag(c),`${s.update(n)}${s.final()}`}catch(s){let l=s instanceof RangeError,u=s.message==="Invalid key length",g=s.message==="Unsupported state or unable to authenticate data";if(l||u){let y=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw y.code="INVALID_DOTENV_KEY",y}else if(g){let y=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw y.code="DECRYPTION_FAILED",y}else throw s}}a(hn,"decrypt");function yn(t,e,r={}){let n=!!(r&&r.debug),o=!!(r&&r.override),c={};if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(t,s)?(o===!0&&(t[s]=e[s],c[s]=e[s]),n&&pe(o===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):(t[s]=e[s],c[s]=e[s]);return c}a(yn,"populate");var P={configDotenv:gn,_configVault:fn,_parseVault:dn,config:mn,decrypt:hn,parse:ln,populate:yn};z.exports.configDotenv=P.configDotenv;z.exports._configVault=P._configVault;z.exports._parseVault=P._parseVault;z.exports.config=P.config;z.exports.decrypt=P.decrypt;z.exports.parse=P.parse;z.exports.populate=P.populate;z.exports=P});var Qn={};Or(Qn,{TestRunMonitor:()=>xe});module.exports=Mr(Qn);var De=a(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var _r=require("child_process"),ge=require("crypto"),k=require("fs"),Rr=require("fs/promises"),Sr=require("stream/promises"),Cr=require("http"),Ar=le(require("net")),vr=require("os"),V=require("path");var at=["script","template"],ct='<script id="playwrightReportBase64" type="application/zip">',lt="</script>";var sr=require("htmlparser2"),ir=le(Gt()),B=require("fs"),te=require("path"),ar=require("os"),cr=require("crypto");var J=le(require("path")),He=require("fs");var Pe=require("path"),Ie=require("fs");function tn(t,e,r=10){let n=t;for(let o=0;o<r;o++){let c=(0,Pe.join)(n,"package.json");if((0,Ie.existsSync)(c))try{if(JSON.parse((0,Ie.readFileSync)(c,"utf8")).name===e)return n}catch{}n=(0,Pe.join)(n,"..")}}a(tn,"findRepositoryRoot");function Zt(t,e=10){return tn(t,"checksum-customer-engineering-workspace",e)}a(Zt,"findCustomerEngineeringRoot");var We=le(Yt());var Z=a((t,e)=>{if(t==null||t==="")return(e==null?void 0:e.default)??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(e==null?void 0:e.default)??!1},"parseBoolean");function qt(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}a(qt,"resolveMaxRRwebBytes");var En=__dirname,Xt=J.join(__dirname,".."),er=(0,He.existsSync)(Xt)?Xt:En;(0,We.config)({path:J.resolve(er,".env")});var Qt=Z(process.env.CHECKSUM_RUNTIME_DEV_MODE);function Tn(){let t=__dirname;for(;!(0,He.existsSync)(J.join(t,"package.json"));)t=J.join(t,"..");return t}a(Tn,"findRoot");var ue=Tn(),In=Zt(ue,10);(0,We.config)({path:[er,In].filter(t=>!!t).map(t=>J.resolve(t,".env")),override:!1});var Be=Z(process.env.CHECKSUM_RUNTIME_REPO_MODE),_n=Be?J.join(ue,"package","pw-report-template.html"):J.join(ue,"pw-report-template.html"),Rn=Z(process.env.CHECKSUM_DEBUG_ANALYTICS),Sn=Z(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),Cn=qt(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),Re={isDevMode:Qt,isRepoMode:Be,CI:!!process.env.CI,checksumRootFolderBypass:Be&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(Qt?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:ue+"/checksumlib.js"},runtimeRoot:ue,playwrightReporter:{htmlReportTemplatePath:_n},bypassProxyForLocalhost:Z(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Z(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Z(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Z(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Z(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:Cn},monitoring:{debugAnalytics:Rn,logToConsole:Sn,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Z(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Z(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Z(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Z(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Z(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var Rs=require("@playwright/test/reporter");var se=require("path");var $e=a((t,e,r)=>`v2:${An(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),An=a(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var Se=require("fs"),F=le(require("typescript"));var vn=/^[0-9a-zA-Z]+$/,bn=5;function tr(t){return t?t.length===bn&&vn.test(t):!1}a(tr,"isValidChecksumTestId");var je=class je{extract(e,r){if(!e)return;let n=e.split("/"),o=n[n.length-1];if(!o||!o.endsWith(".checksum.spec.ts"))return;let s=o.replace(".checksum.spec.ts","").split(" - ").pop();return tr(s)?s:void 0}};a(je,"FileNameExtractionStrategy");var Ge=je,Ke=class Ke{extract(e,r){if(!(!e||!(0,Se.existsSync)(e)))try{let n=(0,Se.readFileSync)(e,"utf-8"),o=F.createSourceFile(e,n,F.ScriptTarget.Latest,!0),c=new Map,s=a(l=>{if(F.isCallExpression(l)){let u=l;if(this.isTestCall(u.expression)){let g=u.arguments[0];if(g&&F.isCallExpression(g)&&F.isIdentifier(g.expression)&&g.expression.text==="defineChecksumTest"){let y=this.extractDefineChecksumTestArgs(g);y&&tr(y.checksumTestId)&&c.set(y.testTitle,y.checksumTestId)}}}F.forEachChild(l,s)},"visit");return s(o),r&&c.has(r)?c.get(r):c.size>0?Array.from(c.values())[0]:void 0}catch{return}}isTestCall(e){return F.isIdentifier(e)&&e.text==="test"?!0:F.isPropertyAccessExpression(e)?F.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],o=r[1];if(!n||!o)return;let c=this.extractStringLiteral(n),s=this.extractStringLiteral(o);if(c&&s)return{testTitle:c,checksumTestId:s}}extractStringLiteral(e){if(F.isStringLiteral(e)||F.isNoSubstitutionTemplateLiteral(e))return e.text}};a(Ke,"FileContentExtractionStrategy");var Ze=Ke,ze=class ze{constructor(e){this.strategies=e??[new Ze,new Ge]}extract(e,r){for(let n of this.strategies){let o=n.extract(e,r);if(o)return o}}};a(ze,"ChecksumTestIdExtractor");var Ve=ze;var rr=new Ve;function Ce(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?rr.extract(t.filePath,t.title):void 0)}a(Ce,"resolveChecksumTestId");var Ye=a((t,e)=>Object.values(e[t]??{}).some(r=>{var n,o;return(o=(n=r.autoRecoveryMetadata)==null?void 0:n.data)==null?void 0:o.autoRecovered}),"isAutoRecovered"),Je=a(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function qe(t,e,r){let n=[],o=0,c=0,s=Je(e.expected)+Je(e.flaky),l=Je(e.unexpected);for(let u of t){let g=wn(u,r);n.push(g),g.recovered&&c++,g.bug&&(o++,g.outcome==="expected"||g.outcome==="flaky"?s--:g.outcome==="unexpected"&&l--)}return{passed:s,failed:l,bug:o,recovered:c,tests:n}}a(qe,"computeReportStats");function wn(t,e){let r=Ce({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=Nn(t),o=xn(t.annotations),c=Ye(t.playwrightTestId,e.playwrightIdToMetadata),s=Dn(r,t,e),l=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:c,bug:n,annotations:o,tags:t.tags,outcome:t.outcome,variantKey:$e(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...l!==void 0?{relativeFilePath:l}:{},...t.projectName?{project:t.projectName}:{},...s!==void 0?{usingChecksumTestIdPlaceholder:s}:{}}}a(wn,"rowToTestWithMetadata");function nr(t,e){let r=t.files,n=a(l=>{let g=Ce({playwrightTestId:l.testId,filePath:l.location.file,title:l.title},e)??`${l.location.file}::${l.title}`,y=$e(l.location.file,l.path??[],l.title);return`${g}::${l.projectName}::${y}`},"keyFor"),o=new Map;for(let l of r)for(let u of l.tests)o.set(n(u),u);let c=new Set(o.values()),s={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let l of r){l.tests=l.tests.filter(u=>c.has(u));for(let u of l.tests)s.total++,u.outcome==="expected"?s.expected++:u.outcome==="unexpected"?s.unexpected++:u.outcome==="flaky"?s.flaky++:s.skipped++}t.files=r.filter(l=>l.tests.length>0),t.stats={...t.stats,...s}}a(nr,"dedupeReportByChecksumTestId");var Nn=a(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),xn=a(t=>t.filter(e=>!!(e!=null&&e.type)).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),Dn=a((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var or=a((t,e,r)=>{if(!t)return;let n=r||e,o;if((0,se.isAbsolute)(t))o=t;else{let c=(0,se.dirname)(e);o=(0,se.resolve)(c,t)}return o.replace(n+"/","")},"toRelativeFilePath");var Ln=a(t=>t.files.flatMap(e=>e.tests.map(r=>{var n;return{playwrightTestId:r.testId,ok:!!r.ok,outcome:r.outcome,title:r.title,titlePath:r.path??[],filePath:(n=r.location)==null?void 0:n.file,...r.projectName?{projectName:r.projectName}:{},tags:r.tags??[],annotations:r.annotations??[]}})),"htmlReportToRows"),ee=class ee{constructor(e,r,n,o={},c={},s,l,u,g={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=o;this.channel=s;this.checksumTestIdToUsingPlaceholder=g;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...c},this.checksumRoot=l||(0,te.dirname)((0,te.dirname)(e)),this.projectRoot=u||this.checksumRoot}async process(){var c;let e=0;try{e=((c=(0,B.statSync)(this.reportHTMLFilePath))==null?void 0:c.size)||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(s){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,s)}let r=(0,te.join)((0,ar.tmpdir)(),`pw-report-${(0,cr.randomUUID)()}.zip`),n=a(()=>{try{(0,B.existsSync)(r)&&(0,B.unlinkSync)(r)}catch{}},"cleanupFile"),o={sigterm:a(()=>{n(),process.exit(143)},"sigterm"),sigint:a(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",o.sigterm),process.once("SIGINT",o.sigint),process.once("exit",o.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let s=Date.now();await this.extractBase64ToFile(r);let l=Date.now()-s;this.channel.debug("Modifying ZIP file...");let u=Date.now(),g=this.modifyZipFile(r),y=Date.now()-u;this.channel.debug("Writing output HTML...");let T=Date.now();await this.writeOutputWithStreamedZip(r);let v=Date.now()-T;return{report_html_bytes:e,extract_ms:l,modify_ms:y,write_ms:v,entry_count:g.entryCount,json_entry_count:g.jsonEntryCount,largest_entry_bytes:g.largestEntryBytes,largest_entry_name:g.largestEntryName}}finally{process.removeListener("SIGTERM",o.sigterm),process.removeListener("SIGINT",o.sigint),process.removeListener("exit",o.exit);try{(0,B.existsSync)(r)&&(0,B.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let o=!1,c=!1,s=!1,l=[],u=0,g=(0,B.createWriteStream)(e);g.on("error",d=>{if(!c){c=!0;try{A.destroyed||A.destroy(),v.end()}catch{}n(d)}});let y=a(()=>{if(u<4)return;let d=l.join("");l.length=0,s||(d=d.replace("data:application/zip;base64,",""),s=!0);let f=Math.floor(d.length/4)*4,p=d.slice(0,f),h=d.slice(f);if(h.length>0?(l.push(h),u=h.length):u=0,p.length>0){let E=Buffer.from(p,"base64");g.write(E)}},"flushBuffer"),T=a(d=>at.includes(d),"isPayloadTag"),v=new sr.Parser({onopentag:a((d,f)=>{T(d)&&f.id==="playwrightReportBase64"&&(o=!0)},"onopentag"),ontext:a(d=>{o&&(l.push(d),u+=d.length,u>1024*1024&&y())},"ontext"),onclosetag:a(d=>{if(T(d)&&o&&!c){if(c=!0,u>0){let f=l.join("");if(s||(f=f.replace("data:application/zip;base64,","")),f.length>0){let p=Buffer.from(f,"base64");g.write(p)}}try{A.destroyed||A.destroy()}catch{}g.end(()=>r())}},"onclosetag"),onerror:a(d=>{if(!c){c=!0;try{v.end(),A.destroyed||A.destroy(),g.destroyed||g.destroy()}catch{}n(d)}},"onerror")}),A=(0,B.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});A.on("data",d=>v.write(d.toString())),A.on("end",()=>{if(v.end(),!c){c=!0;try{g.destroyed||g.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),A.on("error",d=>{if(!c){c=!0;try{v.end(),g.destroyed||g.destroy()}catch{}n(d)}})})}modifyZipFile(e){let r=new ir.default(e),n=r.getEntries(),o=!1,c=0,s=0,l="";for(let u of n){if(u.isDirectory||!u.entryName.endsWith(".json"))continue;let g=u.getData().toString("utf8");if(c+=1,g.length>s&&(s=g.length,l=u.entryName),u.entryName==="report.json"){let y=JSON.parse(g);this.config.dedupeByChecksumTestId&&nr(y,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(y),this.report=y,this.extractStats(y),u.setData(Buffer.from(JSON.stringify(y),"utf8")),o=!0}else u.setData(Buffer.from(this.replaceAttachmentPaths(g),"utf8"))}if(!o)throw new Error("report.json not found in ZIP file");return r.writeZip(e),{entryCount:n.length,jsonEntryCount:c,largestEntryBytes:s,largestEntryName:l}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),o=n.replace(".html",".backup.html");(0,B.copyFileSync)(n,o);let c=(0,B.createWriteStream)(n);await new Promise((s,l)=>{c.on("error",l),c.write(r),c.write(ct+"data:application/zip;base64,");let u=(0,B.createReadStream)(e,{highWaterMark:3*1024*1024});u.on("data",g=>{let T=(typeof g=="string"?Buffer.from(g):g).toString("base64");c.write(T)||u.pause()}),c.on("drain",()=>{u.resume()}),u.on("end",()=>{c.write(lt),c.end(()=>s())}),u.on("error",g=>{try{c.destroyed||c.destroy()}catch{}l(g)}),c.on("error",g=>{try{u.destroyed||u.destroy()}catch{}l(g)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(c=>this.pwTestIdToChecksumTestId[c]===e);if(!n)return!0;let o=a(c=>c.some(s=>{var l;return(l=s.attachments)==null?void 0:l.some(u=>u.name==="trace")}),"hasTrace");for(let c of this.report.files)for(let s of c.tests)if(s.testId===n&&s.projectName===r&&o(s.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return ee.templateCache||(ee.templateCache=(0,B.readFileSync)(Re.playwrightReporter.htmlReportTemplatePath,"utf-8")),ee.templateCache}getReportsStats(){return this.stats}extractStats(e){e.stats&&(this.stats=qe(Ln(e),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:a(r=>or(r,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}))}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,te.basename)(e)}`:e}handleReportJSON(e){let r={},n=a(o=>{var u;let c=o.testId,s=this.playwrightIdToMetadata[c];s&&(r[c]=s);let l=Ce({playwrightTestId:o.testId,filePath:(u=o.location)==null?void 0:u.file,title:o.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});l!==void 0&&(o.checksumTestId=l),o.results.forEach(g=>{this.processAttachments(g.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(o=>{o.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};a(ee,"PlaywrightReportProcessor"),ee.templateCache=null;var Ae=ee;var lr={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},On={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},Ps=Object.fromEntries(Object.entries(On).map(t=>t.reverse())),Mn={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},Fs=Object.fromEntries(Object.entries(Mn).map(t=>t.reverse()));var Bs={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},Hs={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var Ne=require("fs"),yr=require("path"),Er=require("stream");var dr=a(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var Xe=require("fs");var pr="\x1B[31m",kn="\x1B[33m",Un="\x1B[32m",Pn="\x1B[36m",Fn="\x1B[2m",Bn="\x1B[1m",fe="\x1B[0m",Hn=a(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),Wn=new Set(["severity","message","kind","timestamp","_startedAtMs"]),$n=a(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),Gn=a(t=>t==="ERROR"||t==="CRITICAL"?pr:t==="WARNING"?kn:Un,"colorForSeverity"),Zn=a(t=>{let e=String(t.severity??"INFO"),r=`${Gn(e)}${e.padEnd(5)}${fe}`,n=t.kind?`${Pn}${t.kind}${fe}`:"",o=String(t.message??""),c=t.error&&typeof t.error=="object"?(()=>{let y=t.error;return` ${pr}${y.type??"Error"}: ${y.message??""}${fe}`})():"",s=["outcome","test_suite_run_id","status"],l=Object.entries(t).filter(([y,T])=>!Wn.has(y)&&T!=null&&y!=="error"&&typeof T!="object"),u=a(y=>{let T=s.indexOf(y);return T===-1?s.length:T},"rank"),g=l.sort(([y],[T])=>u(y)-u(T)).slice(0,8).map(([y,T])=>`${Fn}${y}=${fe}${T}`).join(" ");return[r,Bn+n+fe,o,g,c].filter(y=>y&&y.trim()!=="").join(" ")},"formatPretty"),Vn=a(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),ur=a(t=>{let e=Hn()?Zn(t):$n(Vn(t));(0,Xe.writeSync)(1,e+`
4
- `)},"emitEvent");var fr=a(t=>{(0,Xe.writeSync)(2,t.endsWith(`
1
+ "use strict";var gm=Object.create;var lr=Object.defineProperty;var ym=Object.getOwnPropertyDescriptor;var _m=Object.getOwnPropertyNames;var bm=Object.getPrototypeOf,Em=Object.prototype.hasOwnProperty;var o=(t,e)=>lr(t,"name",{value:e,configurable:!0});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},wm=(t,e)=>{for(var r in e)lr(t,r,{get:e[r],enumerable:!0})},qa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _m(e))!Em.call(t,s)&&s!==r&&lr(t,s,{get:()=>e[s],enumerable:!(n=ym(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?gm(bm(t)):{},qa(e||!t||!t.__esModule?lr(r,"default",{value:t,enumerable:!0}):r,t)),Tm=t=>qa(lr({},"__esModule",{value:!0}),t);var zo=P((hx,Ms)=>{"use strict";var oh=Object.prototype.hasOwnProperty,Ae="~";function dr(){}o(dr,"Events");Object.create&&(dr.prototype=Object.create(null),new dr().__proto__||(Ae=!1));function ch(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(ch,"EE");function Go(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new ch(r,n||t,s),a=Ae?Ae+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],i]:t._events[a].push(i):(t._events[a]=i,t._eventsCount++),t}o(Go,"addListener");function nn(t,e){--t._eventsCount===0?t._events=new dr:delete t._events[e]}o(nn,"clearEvent");function ve(){this._events=new dr,this._eventsCount=0}o(ve,"EventEmitter");ve.prototype.eventNames=o(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)oh.call(r,n)&&e.push(Ae?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");ve.prototype.listeners=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},"listeners");ve.prototype.listenerCount=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");ve.prototype.emit=o(function(e,r,n,s,i,a){var c=Ae?Ae+e:e;if(!this._events[c])return!1;var l=this._events[c],u=arguments.length,d,f;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,n),!0;case 4:return l.fn.call(l.context,r,n,s),!0;case 5:return l.fn.call(l.context,r,n,s,i),!0;case 6:return l.fn.call(l.context,r,n,s,i,a),!0}for(f=1,d=new Array(u-1);f<u;f++)d[f-1]=arguments[f];l.fn.apply(l.context,d)}else{var _=l.length,g;for(f=0;f<_;f++)switch(l[f].once&&this.removeListener(e,l[f].fn,void 0,!0),u){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,r);break;case 3:l[f].fn.call(l[f].context,r,n);break;case 4:l[f].fn.call(l[f].context,r,n,s);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];l[f].fn.apply(l[f].context,d)}}return!0},"emit");ve.prototype.on=o(function(e,r,n){return Go(this,e,r,n,!1)},"on");ve.prototype.once=o(function(e,r,n){return Go(this,e,r,n,!0)},"once");ve.prototype.removeListener=o(function(e,r,n,s){var i=Ae?Ae+e:e;if(!this._events[i])return this;if(!r)return nn(this,i),this;var a=this._events[i];if(a.fn)a.fn===r&&(!s||a.once)&&(!n||a.context===n)&&nn(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==r||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=l.length===1?l[0]:l:nn(this,i)}return this},"removeListener");ve.prototype.removeAllListeners=o(function(e){var r;return e?(r=Ae?Ae+e:e,this._events[r]&&nn(this,r)):(this._events=new dr,this._eventsCount=0),this},"removeAllListeners");ve.prototype.off=ve.prototype.removeListener;ve.prototype.addListener=ve.prototype.on;ve.prefixed=Ae;ve.EventEmitter=ve;typeof Ms<"u"&&(Ms.exports=ve)});var qo=P((yx,Vo)=>{"use strict";Vo.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var Ko=P((_x,an)=>{"use strict";var lh=qo(),sn=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},Wo=o((t,e,r)=>new Promise((n,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){s(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new sn(a);typeof t.cancel=="function"&&t.cancel(),s(c)},e);lh(t.then(n,s),()=>{clearTimeout(i)})}),"pTimeout");an.exports=Wo;an.exports.default=Wo;an.exports.TimeoutError=sn});var Zo=P(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});function uh(t,e,r){let n=0,s=t.length;for(;s>0;){let i=s/2|0,a=n+i;r(t[a],e)<=0?(n=++a,s-=i+1):s=i}return n}o(uh,"lowerBound");ks.default=uh});var Jo=P(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var dh=Zo(),Ps=class{static{o(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let s=dh.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(s,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Ls.default=Ps});var cn=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var fh=zo(),Yo=Ko(),ph=Jo(),on=o(()=>{},"empty"),mh=new Yo.TimeoutError,Ds=class extends fh{static{o(this,"PQueue")}constructor(e){var r,n,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=on,this._resolveIdle=on,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:ph.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,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=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=on,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=on,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&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(!(typeof e=="number"&&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,s)=>{let i=o(async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?e():Yo.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&s(mh)});n(await a)}catch(a){s(a)}this._next()},"run");this._queue.enqueue(i,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),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}};$s.default=Ds});var wr=P((UR,vl)=>{"use strict";var Mg="2.0.0",kg=Number.MAX_SAFE_INTEGER||9007199254740991,Pg=16,Lg=250,Dg=["major","premajor","minor","preminor","patch","prepatch","prerelease"];vl.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Pg,MAX_SAFE_BUILD_LENGTH:Lg,MAX_SAFE_INTEGER:kg,RELEASE_TYPES:Dg,SEMVER_SPEC_VERSION:Mg,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Tr=P((FR,Sl)=>{"use strict";var $g=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Sl.exports=$g});var Yt=P((it,Il)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:yi,MAX_SAFE_BUILD_LENGTH:Ug,MAX_LENGTH:Fg}=wr(),Bg=Tr();it=Il.exports={};var jg=it.re=[],Hg=it.safeRe=[],L=it.src=[],Gg=it.safeSrc=[],D=it.t={},zg=0,_i="[a-zA-Z0-9-]",Vg=[["\\s",1],["\\d",Fg],[_i,Ug]],qg=o(t=>{for(let[e,r]of Vg)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),V=o((t,e,r)=>{let n=qg(e),s=zg++;Bg(t,s,e),D[t]=s,L[s]=e,Gg[s]=n,jg[s]=new RegExp(e,r?"g":void 0),Hg[s]=new RegExp(n,r?"g":void 0)},"createToken");V("NUMERICIDENTIFIER","0|[1-9]\\d*");V("NUMERICIDENTIFIERLOOSE","\\d+");V("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${_i}*`);V("MAINVERSION",`(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})`);V("MAINVERSIONLOOSE",`(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASEIDENTIFIER",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIER]})`);V("PRERELEASEIDENTIFIERLOOSE",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASE",`(?:-(${L[D.PRERELEASEIDENTIFIER]}(?:\\.${L[D.PRERELEASEIDENTIFIER]})*))`);V("PRERELEASELOOSE",`(?:-?(${L[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${L[D.PRERELEASEIDENTIFIERLOOSE]})*))`);V("BUILDIDENTIFIER",`${_i}+`);V("BUILD",`(?:\\+(${L[D.BUILDIDENTIFIER]}(?:\\.${L[D.BUILDIDENTIFIER]})*))`);V("FULLPLAIN",`v?${L[D.MAINVERSION]}${L[D.PRERELEASE]}?${L[D.BUILD]}?`);V("FULL",`^${L[D.FULLPLAIN]}$`);V("LOOSEPLAIN",`[v=\\s]*${L[D.MAINVERSIONLOOSE]}${L[D.PRERELEASELOOSE]}?${L[D.BUILD]}?`);V("LOOSE",`^${L[D.LOOSEPLAIN]}$`);V("GTLT","((?:<|>)?=?)");V("XRANGEIDENTIFIERLOOSE",`${L[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);V("XRANGEIDENTIFIER",`${L[D.NUMERICIDENTIFIER]}|x|X|\\*`);V("XRANGEPLAIN",`[v=\\s]*(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:${L[D.PRERELEASE]})?${L[D.BUILD]}?)?)?`);V("XRANGEPLAINLOOSE",`[v=\\s]*(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:${L[D.PRERELEASELOOSE]})?${L[D.BUILD]}?)?)?`);V("XRANGE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAIN]}$`);V("XRANGELOOSE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAINLOOSE]}$`);V("COERCEPLAIN",`(^|[^\\d])(\\d{1,${yi}})(?:\\.(\\d{1,${yi}}))?(?:\\.(\\d{1,${yi}}))?`);V("COERCE",`${L[D.COERCEPLAIN]}(?:$|[^\\d])`);V("COERCEFULL",L[D.COERCEPLAIN]+`(?:${L[D.PRERELEASE]})?(?:${L[D.BUILD]})?(?:$|[^\\d])`);V("COERCERTL",L[D.COERCE],!0);V("COERCERTLFULL",L[D.COERCEFULL],!0);V("LONETILDE","(?:~>?)");V("TILDETRIM",`(\\s*)${L[D.LONETILDE]}\\s+`,!0);it.tildeTrimReplace="$1~";V("TILDE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAIN]}$`);V("TILDELOOSE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAINLOOSE]}$`);V("LONECARET","(?:\\^)");V("CARETTRIM",`(\\s*)${L[D.LONECARET]}\\s+`,!0);it.caretTrimReplace="$1^";V("CARET",`^${L[D.LONECARET]}${L[D.XRANGEPLAIN]}$`);V("CARETLOOSE",`^${L[D.LONECARET]}${L[D.XRANGEPLAINLOOSE]}$`);V("COMPARATORLOOSE",`^${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]})$|^$`);V("COMPARATOR",`^${L[D.GTLT]}\\s*(${L[D.FULLPLAIN]})$|^$`);V("COMPARATORTRIM",`(\\s*)${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]}|${L[D.XRANGEPLAIN]})`,!0);it.comparatorTrimReplace="$1$2$3";V("HYPHENRANGE",`^\\s*(${L[D.XRANGEPLAIN]})\\s+-\\s+(${L[D.XRANGEPLAIN]})\\s*$`);V("HYPHENRANGELOOSE",`^\\s*(${L[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${L[D.XRANGEPLAINLOOSE]})\\s*$`);V("STAR","(<|>)?=?\\s*\\*");V("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");V("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var An=P((jR,xl)=>{"use strict";var Wg=Object.freeze({loose:!0}),Kg=Object.freeze({}),Zg=o(t=>t?typeof t!="object"?Wg:t:Kg,"parseOptions");xl.exports=Zg});var bi=P((GR,Rl)=>{"use strict";var Al=/^[0-9]+$/,Cl=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=Al.test(t),n=Al.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),Jg=o((t,e)=>Cl(e,t),"rcompareIdentifiers");Rl.exports={compareIdentifiers:Cl,rcompareIdentifiers:Jg}});var Se=P((VR,Nl)=>{"use strict";var Cn=Tr(),{MAX_LENGTH:Ol,MAX_SAFE_INTEGER:Rn}=wr(),{safeRe:On,t:Nn}=Yt(),Yg=An(),{compareIdentifiers:Ei}=bi(),wi=class t{static{o(this,"SemVer")}constructor(e,r){if(r=Yg(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Ol)throw new TypeError(`version is longer than ${Ol} characters`);Cn("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=e.trim().match(r.loose?On[Nn.LOOSE]:On[Nn.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Rn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rn||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&i<Rn)return i}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Cn("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=e.prerelease[r];if(Cn("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ei(n,s)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let n=this.build[r],s=e.build[r];if(Cn("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ei(n,s)}while(++r)}inc(e,r,n){if(e.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?On[Nn.PRERELEASELOOSE]:On[Nn.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Ei(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Nl.exports=wi});var Dt=P((WR,kl)=>{"use strict";var Ml=Se(),Xg=o((t,e,r=!1)=>{if(t instanceof Ml)return t;try{return new Ml(t,e)}catch(n){if(!r)return null;throw n}},"parse");kl.exports=Xg});var Ll=P((ZR,Pl)=>{"use strict";var Qg=Dt(),ey=o((t,e)=>{let r=Qg(t,e);return r?r.version:null},"valid");Pl.exports=ey});var $l=P((YR,Dl)=>{"use strict";var ty=Dt(),ry=o((t,e)=>{let r=ty(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");Dl.exports=ry});var Bl=P((QR,Fl)=>{"use strict";var Ul=Se(),ny=o((t,e,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ul(t instanceof Ul?t.version:t,r).inc(e,n,s).version}catch{return null}},"inc");Fl.exports=ny});var Gl=P((tO,Hl)=>{"use strict";var jl=Dt(),sy=o((t,e)=>{let r=jl(t,null,!0),n=jl(e,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,a=i?r:n,c=i?n:r,l=!!a.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(a)===0)return c.minor&&!c.patch?"minor":"patch"}let d=l?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"},"diff");Hl.exports=sy});var Vl=P((nO,zl)=>{"use strict";var iy=Se(),ay=o((t,e)=>new iy(t,e).major,"major");zl.exports=ay});var Wl=P((iO,ql)=>{"use strict";var oy=Se(),cy=o((t,e)=>new oy(t,e).minor,"minor");ql.exports=cy});var Zl=P((oO,Kl)=>{"use strict";var ly=Se(),uy=o((t,e)=>new ly(t,e).patch,"patch");Kl.exports=uy});var Yl=P((lO,Jl)=>{"use strict";var dy=Dt(),fy=o((t,e)=>{let r=dy(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");Jl.exports=fy});var Ge=P((dO,Ql)=>{"use strict";var Xl=Se(),py=o((t,e,r)=>new Xl(t,r).compare(new Xl(e,r)),"compare");Ql.exports=py});var tu=P((pO,eu)=>{"use strict";var my=Ge(),hy=o((t,e,r)=>my(e,t,r),"rcompare");eu.exports=hy});var nu=P((hO,ru)=>{"use strict";var gy=Ge(),yy=o((t,e)=>gy(t,e,!0),"compareLoose");ru.exports=yy});var Mn=P((yO,iu)=>{"use strict";var su=Se(),_y=o((t,e,r)=>{let n=new su(t,r),s=new su(e,r);return n.compare(s)||n.compareBuild(s)},"compareBuild");iu.exports=_y});var ou=P((bO,au)=>{"use strict";var by=Mn(),Ey=o((t,e)=>t.sort((r,n)=>by(r,n,e)),"sort");au.exports=Ey});var lu=P((wO,cu)=>{"use strict";var wy=Mn(),Ty=o((t,e)=>t.sort((r,n)=>wy(n,r,e)),"rsort");cu.exports=Ty});var vr=P((vO,uu)=>{"use strict";var vy=Ge(),Sy=o((t,e,r)=>vy(t,e,r)>0,"gt");uu.exports=Sy});var kn=P((IO,du)=>{"use strict";var Iy=Ge(),xy=o((t,e,r)=>Iy(t,e,r)<0,"lt");du.exports=xy});var Ti=P((AO,fu)=>{"use strict";var Ay=Ge(),Cy=o((t,e,r)=>Ay(t,e,r)===0,"eq");fu.exports=Cy});var vi=P((RO,pu)=>{"use strict";var Ry=Ge(),Oy=o((t,e,r)=>Ry(t,e,r)!==0,"neq");pu.exports=Oy});var Pn=P((NO,mu)=>{"use strict";var Ny=Ge(),My=o((t,e,r)=>Ny(t,e,r)>=0,"gte");mu.exports=My});var Ln=P((kO,hu)=>{"use strict";var ky=Ge(),Py=o((t,e,r)=>ky(t,e,r)<=0,"lte");hu.exports=Py});var Si=P((LO,gu)=>{"use strict";var Ly=Ti(),Dy=vi(),$y=vr(),Uy=Pn(),Fy=kn(),By=Ln(),jy=o((t,e,r,n)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Ly(t,r,n);case"!=":return Dy(t,r,n);case">":return $y(t,r,n);case">=":return Uy(t,r,n);case"<":return Fy(t,r,n);case"<=":return By(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");gu.exports=jy});var _u=P(($O,yu)=>{"use strict";var Hy=Se(),Gy=Dt(),{safeRe:Dn,t:$n}=Yt(),zy=o((t,e)=>{if(t instanceof Hy)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Dn[$n.COERCEFULL]:Dn[$n.COERCE]);else{let l=e.includePrerelease?Dn[$n.COERCERTLFULL]:Dn[$n.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",a=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Gy(`${n}.${s}.${i}${a}${c}`,e)},"coerce");yu.exports=zy});var Eu=P((FO,bu)=>{"use strict";var Ii=class{static{o(this,"LRUCache")}constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,r)}return this}};bu.exports=Ii});var ze=P((jO,Su)=>{"use strict";var Vy=/\s+/g,xi=class t{static{o(this,"Range")}constructor(e,r){if(r=Wy(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Ai)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(Vy," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Tu(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&e_(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&Xy)|(this.options.loose&&Qy))+":"+e,s=wu.get(n);if(s)return s;let i=this.options.loose,a=i?Ce[Ie.HYPHENRANGELOOSE]:Ce[Ie.HYPHENRANGE];e=e.replace(a,u_(this.options.includePrerelease)),ee("hyphen replace",e),e=e.replace(Ce[Ie.COMPARATORTRIM],Zy),ee("comparator trim",e),e=e.replace(Ce[Ie.TILDETRIM],Jy),ee("tilde trim",e),e=e.replace(Ce[Ie.CARETTRIM],Yy),ee("caret trim",e);let c=e.split(" ").map(f=>t_(f,this.options)).join(" ").split(/\s+/).map(f=>l_(f,this.options));i&&(c=c.filter(f=>(ee("loose invalid filter",f,this.options),!!f.match(Ce[Ie.COMPARATORLOOSE])))),ee("range list",c);let l=new Map,u=c.map(f=>new Ai(f,this.options));for(let f of u){if(Tu(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let d=[...l.values()];return wu.set(n,d),d}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>vu(n,r)&&e.set.some(s=>vu(s,r)&&n.every(i=>s.every(a=>i.intersects(a,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Ky(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(d_(this.set[r],e,this.options))return!0;return!1}};Su.exports=xi;var qy=Eu(),wu=new qy,Wy=An(),Ai=Sr(),ee=Tr(),Ky=Se(),{safeRe:Ce,t:Ie,comparatorTrimReplace:Zy,tildeTrimReplace:Jy,caretTrimReplace:Yy}=Yt(),{FLAG_INCLUDE_PRERELEASE:Xy,FLAG_LOOSE:Qy}=wr(),Tu=o(t=>t.value==="<0.0.0-0","isNullSet"),e_=o(t=>t.value==="","isAny"),vu=o((t,e)=>{let r=!0,n=t.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,e)),s=n.pop();return r},"isSatisfiable"),t_=o((t,e)=>(t=t.replace(Ce[Ie.BUILD],""),ee("comp",t,e),t=s_(t,e),ee("caret",t),t=r_(t,e),ee("tildes",t),t=a_(t,e),ee("xrange",t),t=c_(t,e),ee("stars",t),t),"parseComparator"),Re=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),r_=o((t,e)=>t.trim().split(/\s+/).map(r=>n_(r,e)).join(" "),"replaceTildes"),n_=o((t,e)=>{let r=e.loose?Ce[Ie.TILDELOOSE]:Ce[Ie.TILDE];return t.replace(r,(n,s,i,a,c)=>{ee("tilde",t,n,s,i,a,c);let l;return Re(s)?l="":Re(i)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:Re(a)?l=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:c?(ee("replaceTilde pr",c),l=`>=${s}.${i}.${a}-${c} <${s}.${+i+1}.0-0`):l=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,ee("tilde return",l),l})},"replaceTilde"),s_=o((t,e)=>t.trim().split(/\s+/).map(r=>i_(r,e)).join(" "),"replaceCarets"),i_=o((t,e)=>{ee("caret",t,e);let r=e.loose?Ce[Ie.CARETLOOSE]:Ce[Ie.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,(s,i,a,c,l)=>{ee("caret",t,s,i,a,c,l);let u;return Re(i)?u="":Re(a)?u=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Re(c)?i==="0"?u=`>=${i}.${a}.0${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.0${n} <${+i+1}.0.0-0`:l?(ee("replaceCaret pr",l),i==="0"?a==="0"?u=`>=${i}.${a}.${c}-${l} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}-${l} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c}-${l} <${+i+1}.0.0-0`):(ee("no pr"),i==="0"?a==="0"?u=`>=${i}.${a}.${c}${n} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c} <${+i+1}.0.0-0`),ee("caret return",u),u})},"replaceCaret"),a_=o((t,e)=>(ee("replaceXRanges",t,e),t.split(/\s+/).map(r=>o_(r,e)).join(" ")),"replaceXRanges"),o_=o((t,e)=>{t=t.trim();let r=e.loose?Ce[Ie.XRANGELOOSE]:Ce[Ie.XRANGE];return t.replace(r,(n,s,i,a,c,l)=>{ee("xRange",t,n,s,i,a,c,l);let u=Re(i),d=u||Re(a),f=d||Re(c),_=f;return s==="="&&_&&(s=""),l=e.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&_?(d&&(a=0),c=0,s===">"?(s=">=",d?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):s==="<="&&(s="<",d?i=+i+1:a=+a+1),s==="<"&&(l="-0"),n=`${s+i}.${a}.${c}${l}`):d?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:f&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),ee("xRange return",n),n})},"replaceXRange"),c_=o((t,e)=>(ee("replaceStars",t,e),t.trim().replace(Ce[Ie.STAR],"")),"replaceStars"),l_=o((t,e)=>(ee("replaceGTE0",t,e),t.trim().replace(Ce[e.includePrerelease?Ie.GTE0PRE:Ie.GTE0],"")),"replaceGTE0"),u_=o(t=>(e,r,n,s,i,a,c,l,u,d,f,_)=>(Re(n)?r="":Re(s)?r=`>=${n}.0.0${t?"-0":""}`:Re(i)?r=`>=${n}.${s}.0${t?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,Re(u)?l="":Re(d)?l=`<${+u+1}.0.0-0`:Re(f)?l=`<${u}.${+d+1}.0-0`:_?l=`<=${u}.${d}.${f}-${_}`:t?l=`<${u}.${d}.${+f+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),"hyphenReplace"),d_=o((t,e,r)=>{for(let n=0;n<t.length;n++)if(!t[n].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let n=0;n<t.length;n++)if(ee(t[n].semver),t[n].semver!==Ai.ANY&&t[n].semver.prerelease.length>0){let s=t[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0},"testSet")});var Sr=P((GO,Ou)=>{"use strict";var Ir=Symbol("SemVer ANY"),Oi=class t{static{o(this,"Comparator")}static get ANY(){return Ir}constructor(e,r){if(r=Iu(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Ri("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===Ir?this.value="":this.value=this.operator+this.semver.version,Ri("comp",this)}parse(e){let r=this.options.loose?xu[Au.COMPARATORLOOSE]:xu[Au.COMPARATOR],n=e.match(r);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Cu(n[2],this.options.loose):this.semver=Ir}toString(){return this.value}test(e){if(Ri("Comparator.test",e,this.options.loose),this.semver===Ir||e===Ir)return!0;if(typeof e=="string")try{e=new Cu(e,this.options)}catch{return!1}return Ci(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ru(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new Ru(this.value,r).test(e.semver):(r=Iu(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Ci(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Ci(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Ou.exports=Oi;var Iu=An(),{safeRe:xu,t:Au}=Yt(),Ci=Si(),Ri=Tr(),Cu=Se(),Ru=ze()});var xr=P((VO,Nu)=>{"use strict";var f_=ze(),p_=o((t,e,r)=>{try{e=new f_(e,r)}catch{return!1}return e.test(t)},"satisfies");Nu.exports=p_});var ku=P((WO,Mu)=>{"use strict";var m_=ze(),h_=o((t,e)=>new m_(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");Mu.exports=h_});var Lu=P((ZO,Pu)=>{"use strict";var g_=Se(),y_=ze(),__=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new y_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===-1)&&(n=a,s=new g_(n,r))}),n},"maxSatisfying");Pu.exports=__});var $u=P((YO,Du)=>{"use strict";var b_=Se(),E_=ze(),w_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new E_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===1)&&(n=a,s=new b_(n,r))}),n},"minSatisfying");Du.exports=w_});var Bu=P((QO,Fu)=>{"use strict";var Ni=Se(),T_=ze(),Uu=vr(),v_=o((t,e)=>{t=new T_(t,e);let r=new Ni("0.0.0");if(t.test(r)||(r=new Ni("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n<t.set.length;++n){let s=t.set[n],i=null;s.forEach(a=>{let c=new Ni(a.semver.version);switch(a.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!i||Uu(c,i))&&(i=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),i&&(!r||Uu(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");Fu.exports=v_});var Hu=P((tN,ju)=>{"use strict";var S_=ze(),I_=o((t,e)=>{try{return new S_(t,e).range||"*"}catch{return null}},"validRange");ju.exports=I_});var Un=P((nN,qu)=>{"use strict";var x_=Se(),Vu=Sr(),{ANY:A_}=Vu,C_=ze(),R_=xr(),Gu=vr(),zu=kn(),O_=Ln(),N_=Pn(),M_=o((t,e,r,n)=>{t=new x_(t,n),e=new C_(e,n);let s,i,a,c,l;switch(r){case">":s=Gu,i=O_,a=zu,c=">",l=">=";break;case"<":s=zu,i=N_,a=Gu,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(R_(t,e,n))return!1;for(let u=0;u<e.set.length;++u){let d=e.set[u],f=null,_=null;if(d.forEach(g=>{g.semver===A_&&(g=new Vu(">=0.0.0")),f=f||g,_=_||g,s(g.semver,f.semver,n)?f=g:a(g.semver,_.semver,n)&&(_=g)}),f.operator===c||f.operator===l||(!_.operator||_.operator===c)&&i(t,_.semver))return!1;if(_.operator===l&&a(t,_.semver))return!1}return!0},"outside");qu.exports=M_});var Ku=P((iN,Wu)=>{"use strict";var k_=Un(),P_=o((t,e,r)=>k_(t,e,">",r),"gtr");Wu.exports=P_});var Ju=P((oN,Zu)=>{"use strict";var L_=Un(),D_=o((t,e,r)=>L_(t,e,"<",r),"ltr");Zu.exports=D_});var Qu=P((lN,Xu)=>{"use strict";var Yu=ze(),$_=o((t,e,r)=>(t=new Yu(t,r),e=new Yu(e,r),t.intersects(e,r)),"intersects");Xu.exports=$_});var td=P((dN,ed)=>{"use strict";var U_=xr(),F_=Ge();ed.exports=(t,e,r)=>{let n=[],s=null,i=null,a=t.sort((d,f)=>F_(d,f,r));for(let d of a)U_(d,e,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let c=[];for(let[d,f]of n)d===f?c.push(d):!f&&d===a[0]?c.push("*"):f?d===a[0]?c.push(`<=${f}`):c.push(`${d} - ${f}`):c.push(`>=${d}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var od=P((fN,ad)=>{"use strict";var rd=ze(),ki=Sr(),{ANY:Mi}=ki,Ar=xr(),Pi=Ge(),B_=o((t,e,r={})=>{if(t===e)return!0;t=new rd(t,r),e=new rd(e,r);let n=!1;e:for(let s of t.set){for(let i of e.set){let a=H_(s,i,r);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},"subset"),j_=[new ki(">=0.0.0-0")],nd=[new ki(">=0.0.0")],H_=o((t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Mi){if(e.length===1&&e[0].semver===Mi)return!0;r.includePrerelease?t=j_:t=nd}if(e.length===1&&e[0].semver===Mi){if(r.includePrerelease)return!0;e=nd}let n=new Set,s,i;for(let g of t)g.operator===">"||g.operator===">="?s=sd(s,g,r):g.operator==="<"||g.operator==="<="?i=id(i,g,r):n.add(g.semver);if(n.size>1)return null;let a;if(s&&i){if(a=Pi(s.semver,i.semver,r),a>0)return null;if(a===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let g of n){if(s&&!Ar(g,String(s),r)||i&&!Ar(g,String(i),r))return null;for(let y of e)if(!Ar(g,String(y),r))return!1;return!0}let c,l,u,d,f=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,_=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;f&&f.prerelease.length===1&&i.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let g of e){if(d=d||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",s){if(_&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===_.major&&g.semver.minor===_.minor&&g.semver.patch===_.patch&&(_=!1),g.operator===">"||g.operator===">="){if(c=sd(s,g,r),c===g&&c!==s)return!1}else if(s.operator===">="&&!Ar(s.semver,String(g),r))return!1}if(i){if(f&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===f.major&&g.semver.minor===f.minor&&g.semver.patch===f.patch&&(f=!1),g.operator==="<"||g.operator==="<="){if(l=id(i,g,r),l===g&&l!==i)return!1}else if(i.operator==="<="&&!Ar(i.semver,String(g),r))return!1}if(!g.operator&&(i||s)&&a!==0)return!1}return!(s&&u&&!i&&a!==0||i&&d&&!s&&a!==0||_||f)},"simpleSubset"),sd=o((t,e,r)=>{if(!t)return e;let n=Pi(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),id=o((t,e,r)=>{if(!t)return e;let n=Pi(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");ad.exports=B_});var dd=P((mN,ud)=>{"use strict";var Li=Yt(),cd=wr(),G_=Se(),ld=bi(),z_=Dt(),V_=Ll(),q_=$l(),W_=Bl(),K_=Gl(),Z_=Vl(),J_=Wl(),Y_=Zl(),X_=Yl(),Q_=Ge(),eb=tu(),tb=nu(),rb=Mn(),nb=ou(),sb=lu(),ib=vr(),ab=kn(),ob=Ti(),cb=vi(),lb=Pn(),ub=Ln(),db=Si(),fb=_u(),pb=Sr(),mb=ze(),hb=xr(),gb=ku(),yb=Lu(),_b=$u(),bb=Bu(),Eb=Hu(),wb=Un(),Tb=Ku(),vb=Ju(),Sb=Qu(),Ib=td(),xb=od();ud.exports={parse:z_,valid:V_,clean:q_,inc:W_,diff:K_,major:Z_,minor:J_,patch:Y_,prerelease:X_,compare:Q_,rcompare:eb,compareLoose:tb,compareBuild:rb,sort:nb,rsort:sb,gt:ib,lt:ab,eq:ob,neq:cb,gte:lb,lte:ub,cmp:db,coerce:fb,Comparator:pb,Range:mb,satisfies:hb,toComparators:gb,maxSatisfying:yb,minSatisfying:_b,minVersion:bb,validRange:Eb,outside:wb,gtr:Tb,ltr:vb,intersects:Sb,simplifyRange:Ib,subset:xb,SemVer:G_,re:Li.re,src:Li.src,tokens:Li.t,SEMVER_SPEC_VERSION:cd.SEMVER_SPEC_VERSION,RELEASE_TYPES:cd.RELEASE_TYPES,compareIdentifiers:ld.compareIdentifiers,rcompareIdentifiers:ld.rcompareIdentifiers}});var of=P(Qn=>{"use strict";Qn.byteLength=YE;Qn.toByteArray=QE;Qn.fromByteArray=rw;var lt=[],qe=[],JE=typeof Uint8Array<"u"?Uint8Array:Array,ia="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Bt=0,sf=ia.length;Bt<sf;++Bt)lt[Bt]=ia[Bt],qe[ia.charCodeAt(Bt)]=Bt;var Bt,sf;qe[45]=62;qe[95]=63;function af(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}o(af,"getLens");function YE(t){var e=af(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(YE,"byteLength");function XE(t,e,r){return(e+r)*3/4-r}o(XE,"_byteLength");function QE(t){var e,r=af(t),n=r[0],s=r[1],i=new JE(XE(t,n,s)),a=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=qe[t.charCodeAt(l)]<<18|qe[t.charCodeAt(l+1)]<<12|qe[t.charCodeAt(l+2)]<<6|qe[t.charCodeAt(l+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=qe[t.charCodeAt(l)]<<2|qe[t.charCodeAt(l+1)]>>4,i[a++]=e&255),s===1&&(e=qe[t.charCodeAt(l)]<<10|qe[t.charCodeAt(l+1)]<<4|qe[t.charCodeAt(l+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}o(QE,"toByteArray");function ew(t){return lt[t>>18&63]+lt[t>>12&63]+lt[t>>6&63]+lt[t&63]}o(ew,"tripletToBase64");function tw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(ew(n));return s.join("")}o(tw,"encodeChunk");function rw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,c=r-n;a<c;a+=i)s.push(tw(t,a,a+i>c?c:a+i));return n===1?(e=t[r-1],s.push(lt[e>>2]+lt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(lt[e>>10]+lt[e>>4&63]+lt[e<<2&63]+"=")),s.join("")}o(rw,"fromByteArray")});var If=P((R3,mt)=>{var fa=require("fs"),ts=require("path"),xw=require("os"),Aw=require("crypto"),Ef=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function Cw(){return Ef[Math.floor(Math.random()*Ef.length)]}o(Cw,"_getRandomTip");function tr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(tr,"parseBoolean");function Rw(){return process.stdout.isTTY}o(Rw,"supportsAnsi");function Ow(t){return Rw()?`\x1B[2m${t}\x1B[0m`:t}o(Ow,"dim");var Nw=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Mw(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
+ `);let n;for(;(n=Nw.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
3
+ `),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(Mw,"parse");function kw(t){t=t||{};let e=Sf(t);t.path=e;let r=pe.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=vf(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=Lw(r,c);i=pe.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return pe.parse(i)}o(kw,"_parseVault");function Pw(t){console.error(`\u26A0 ${t}`)}o(Pw,"_warn");function $r(t){console.log(`\u2506 ${t}`)}o($r,"_debug");function Tf(t){console.log(`\u25C7 ${t}`)}o(Tf,"_log");function vf(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(vf,"_dotenvKey");function Lw(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(Lw,"_instructions");function Sf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)fa.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ts.resolve(process.cwd(),".env.vault");return fa.existsSync(e)?e:null}o(Sf,"_vaultPath");function wf(t){return t[0]==="~"?ts.join(xw.homedir(),t.slice(1)):t}o(wf,"_resolveHome");function Dw(t){let e=tr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=tr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Tf("loading env from encrypted .env.vault");let n=pe._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),pe.populate(s,n,t),{parsed:n}}o(Dw,"_configVault");function $w(t){let e=ts.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=tr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=tr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&$r("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[wf(t.path)];else{a=[];for(let d of t.path)a.push(wf(d))}let c,l={};for(let d of a)try{let f=pe.parse(fa.readFileSync(d,{encoding:r}));pe.populate(l,f,t)}catch(f){s&&$r(`failed to load ${d} ${f.message}`),c=f}let u=pe.populate(n,l,t);if(s=tr(n.DOTENV_CONFIG_DEBUG||s),i=tr(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,f=[];for(let _ of a)try{let g=ts.relative(process.cwd(),_);f.push(g)}catch(g){s&&$r(`failed to load ${_} ${g.message}`),c=g}Tf(`injected env (${d}) from ${f.join(",")} ${Ow(`// tip: ${Cw()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o($w,"configDotenv");function Uw(t){if(vf(t).length===0)return pe.configDotenv(t);let e=Sf(t);return e?pe._configVault(t):(Pw(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),pe.configDotenv(t))}o(Uw,"config");function Fw(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=Aw.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(Fw,"decrypt");function Bw(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&$r(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(Bw,"populate");var pe={configDotenv:$w,_configVault:Dw,_parseVault:kw,config:Uw,decrypt:Fw,parse:Mw,populate:Bw};mt.exports.configDotenv=pe.configDotenv;mt.exports._configVault=pe._configVault;mt.exports._parseVault=pe._parseVault;mt.exports.config=pe.config;mt.exports.decrypt=pe.decrypt;mt.exports.parse=pe.parse;mt.exports.populate=pe.populate;mt.exports=pe});var pa=P((s5,Nf)=>{Nf.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var rs=P(kf=>{var Mf={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Vw(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}o(Vw,"E");for(let t of Object.keys(Mf))kf[t]=Vw(Mf[t])});var Uf=P((o5,$f)=>{var qw=require("fs"),de=require("path"),Pf=pa(),Ww=rs(),Kw=typeof process=="object"&&process.platform==="win32",Lf=o(t=>typeof t=="object"&&t!==null,"is_Obj"),Df=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ne(t){this.sep=de.sep,this.fs=qw,Lf(t)&&Lf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}o(ne,"Utils");$f.exports=ne;ne.prototype.makeDir=function(t){let e=this;function r(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){s+=e.sep+i;var a;try{a=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(a&&a.isFile())throw Ww.FILE_IN_THE_WAY(`"${s}"`)}})}o(r,"mkdirSync"),r(t)};ne.prototype.writeFileTo=function(t,e,r,n){let s=this;if(s.fs.existsSync(t)){if(!r)return!1;var i=s.fs.statSync(t);if(i.isDirectory())return!1}var a=de.dirname(t);s.fs.existsSync(a)||s.makeDir(a);var c;try{c=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),c=s.fs.openSync(t,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(t,n||438),!0};ne.prototype.writeFileToAsync=function(t,e,r,n,s){typeof n=="function"&&(s=n,n=void 0);let i=this;i.fs.exists(t,function(a){if(a&&!r)return s(!1);i.fs.stat(t,function(c,l){if(a&&l&&l.isDirectory())return s(!1);var u=de.dirname(t);i.fs.exists(u,function(d){if(!d)try{i.makeDir(u)}catch{return s(!1)}let f=o(function(_){i.fs.write(_,e,0,e.length,0,function(g){i.fs.close(_,function(){if(g)return s(!1);i.fs.chmod(t,n||438,function(){s(!0)})})})},"writeToFd");i.fs.open(t,"w",438,function(_,g){_?i.fs.chmod(t,438,function(){i.fs.open(t,"w",438,function(y,E){if(y||!E)return s(!1);f(E)})}):g?f(g):s(!1)})})})})};ne.prototype.findFiles=function(t){let e=this;function r(n,s,i,a){typeof s=="boolean"&&(i=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!s||s.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&i){let f=e.fs.realpathSync(u);a.has(f)||(a.add(f),c=c.concat(r(u,s,i,a)))}}),c}return o(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ne.prototype.findFilesAsync=function(t,e){let r=this,n=[],s=!1,i=o(function(c){s||(s=!0,e(c,c?void 0:n))},"finish"),a=o(function(c,l,u){r.fs.readdir(c,function(d,f){if(d)return u(d);let _=f.length;if(!_)return u();f.forEach(function(g){let y=de.join(c,g);r.fs.stat(y,function(E,w){if(E)return u(E);if(!w){--_||u();return}if(n.push(de.normalize(y)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--_||u();return}r.fs.realpath(y,function(S,I){if(S)return u(S);if(l.has(I)){--_||u();return}l.add(I),a(y,l,function(m){if(m)return u(m);--_||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return i(c);a(t,new Set([l]),i)})};ne.prototype.getAttributes=function(){};ne.prototype.setAttributes=function(){};ne.crc32update=function(t,e){return Df[(t^e)&255]^t>>>8};ne.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ne.crc32update(r,t[n++]);return~r>>>0};ne.methodToString=function(t){switch(t){case Pf.STORED:return"STORED ("+t+")";case Pf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ne.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ne.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ne.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};ne.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,s=r.length;n<s;n++){var i=de.normalize(de.join(t,r.slice(n,s).join(de.sep)));if(i===t||i.startsWith(t+de.sep))return i}return de.normalize(de.join(t,de.basename(e)))};ne.toBuffer=o(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");ne.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ne.writeBigUInt64LE=function(t,e,r){let n=e>>>0,s=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(s,r+4)};ne.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ne.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ne.isWin=Kw;ne.crcTable=Df});var Bf=P((l5,Ff)=>{var Zw=require("path");Ff.exports=function(t,{fs:e}){var r=t||"",n=i(),s=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return o(i,"newAttr"),r&&e.existsSync(r)?(s=e.statSync(r),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=Zw.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:o(function(){},"decodeAttributes"),encodeAttributes:o(function(){},"encodeAttributes"),toJSON:o(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Hf=P((d5,jf)=>{jf.exports={efs:!0,encode:o(t=>Buffer.from(t,"utf8"),"encode"),decode:o(t=>t.toString("utf8"),"decode")}});var nr=P((p5,rr)=>{rr.exports=Uf();rr.exports.Constants=pa();rr.exports.Errors=rs();rr.exports.FileAttr=Bf();rr.exports.decoder=Hf()});var zf=P((m5,Gf)=>{var It=nr(),M=It.Constants;Gf.exports=function(){var t=20,e=10,r=0,n=0,s=0,i=0,a=0,c=0,l=0,u=0,d=0,f=0,_=0,g=0,y=0;t|=It.isWin?2560:768,r|=M.FLG_EFS;let E={extraLen:0},w=o(m=>Math.max(0,m)>>>0,"uint32"),S=o(m=>Math.max(0,m)&65535,"uint16"),I=o(m=>Math.max(0,m)&255,"uint8");return s=It.fromDate2DOS(new Date),{get made(){return t},set made(m){t=m},get version(){return e},set version(m){e=m},get flags(){return r},set flags(m){r=m},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(m){m?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(m){m?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(m){switch(m){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=m},get time(){return It.fromDOS2Date(this.timeval)},set time(m){m=new Date(m),this.timeval=It.fromDate2DOS(m)},get timeval(){return s},set timeval(m){s=w(m)},get timeHighByte(){return I(s>>>8)},get crc(){return i},set crc(m){i=w(m)},get compressedSize(){return a},set compressedSize(m){a=w(m)},get size(){return c},set size(m){c=w(m)},get fileNameLength(){return l},set fileNameLength(m){l=m},get extraLength(){return u},set extraLength(m){u=m},get extraLocalLength(){return E.extraLen},set extraLocalLength(m){E.extraLen=m},get commentLength(){return d},set commentLength(m){d=m},get diskNumStart(){return f},set diskNumStart(m){f=w(m)},get inAttr(){return _},set inAttr(m){_=w(m)},get attr(){return g},set attr(m){g=w(m)},get fileAttr(){return(g||0)>>16&4095},get offset(){return y},set offset(m){y=w(m)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return y+M.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:o(function(m){var T=m.slice(y,y+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw It.Errors.INVALID_LOC();E.version=T.readUInt16LE(M.LOCVER),E.flags=T.readUInt16LE(M.LOCFLG),E.flags_desc=(E.flags&M.FLG_DESC)>0,E.method=T.readUInt16LE(M.LOCHOW),E.time=T.readUInt32LE(M.LOCTIM),E.crc=T.readUInt32LE(M.LOCCRC),E.compressedSize=T.readUInt32LE(M.LOCSIZ),E.size=T.readUInt32LE(M.LOCLEN),E.fnameLen=T.readUInt16LE(M.LOCNAM),E.extraLen=T.readUInt16LE(M.LOCEXT);let A=y+M.LOCHDR+E.fnameLen,N=A+E.extraLen;return m.slice(A,N)},"loadLocalHeaderFromBinary"),loadFromBinary:o(function(m){if(m.length!==M.CENHDR||m.readUInt32LE(0)!==M.CENSIG)throw It.Errors.INVALID_CEN();t=m.readUInt16LE(M.CENVEM),e=m.readUInt16LE(M.CENVER),r=m.readUInt16LE(M.CENFLG),n=m.readUInt16LE(M.CENHOW),s=m.readUInt32LE(M.CENTIM),i=m.readUInt32LE(M.CENCRC),a=m.readUInt32LE(M.CENSIZ),c=m.readUInt32LE(M.CENLEN),l=m.readUInt16LE(M.CENNAM),u=m.readUInt16LE(M.CENEXT),d=m.readUInt16LE(M.CENCOM),f=m.readUInt16LE(M.CENDSK),_=m.readUInt16LE(M.CENATT),g=m.readUInt32LE(M.CENATX),y=m.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:o(function(){var m=Buffer.alloc(M.LOCHDR);return m.writeUInt32LE(M.LOCSIG,0),m.writeUInt16LE(e,M.LOCVER),m.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),m.writeUInt16LE(n,M.LOCHOW),m.writeUInt32LE(s,M.LOCTIM),m.writeUInt32LE(i,M.LOCCRC),m.writeUInt32LE(a,M.LOCSIZ),m.writeUInt32LE(c,M.LOCLEN),m.writeUInt16LE(l,M.LOCNAM),m.writeUInt16LE(E.extraLen,M.LOCEXT),m},"localHeaderToBinary"),centralHeaderToBinary:o(function(){var m=Buffer.alloc(M.CENHDR+l+u+d);return m.writeUInt32LE(M.CENSIG,0),m.writeUInt16LE(t,M.CENVEM),m.writeUInt16LE(e,M.CENVER),m.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),m.writeUInt16LE(n,M.CENHOW),m.writeUInt32LE(s,M.CENTIM),m.writeUInt32LE(i,M.CENCRC),m.writeUInt32LE(a,M.CENSIZ),m.writeUInt32LE(c,M.CENLEN),m.writeUInt16LE(l,M.CENNAM),m.writeUInt16LE(u,M.CENEXT),m.writeUInt16LE(d,M.CENCOM),m.writeUInt16LE(f,M.CENDSK),m.writeUInt16LE(_,M.CENATT),m.writeUInt32LE(g,M.CENATX),m.writeUInt32LE(y,M.CENOFF),m},"centralHeaderToBinary"),toJSON:o(function(){let m=o(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:It.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:m(a),size:m(c),fileNameLength:m(l),extraLength:m(u),commentLength:m(d),diskNumStart:f,inAttr:_,attr:g,offset:y,centralHeaderSize:m(M.CENHDR+l+u+d)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var qf=P((g5,Vf)=>{var We=nr(),H=We.Constants;Vf.exports=function(){var t=0,e=0,r=0,n=0,s=0;let i=o(()=>t>H.EF_ZIP64_OR_16||e>H.EF_ZIP64_OR_16||r>H.EF_ZIP64_OR_32||n>H.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return r},set size(a){r=a},get offset(){return n},set offset(a){n=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return(i()?H.ZIP64HDR+H.END64HDR:0)+H.ENDHDR+s},loadFromBinary:o(function(a){if((a.length!==H.ENDHDR||a.readUInt32LE(0)!==H.ENDSIG)&&(a.length<H.ZIP64HDR||a.readUInt32LE(0)!==H.ZIP64SIG))throw We.Errors.INVALID_END();a.readUInt32LE(0)===H.ENDSIG?(t=a.readUInt16LE(H.ENDSUB),e=a.readUInt16LE(H.ENDTOT),r=a.readUInt32LE(H.ENDSIZ),n=a.readUInt32LE(H.ENDOFF),s=a.readUInt16LE(H.ENDCOM)):(t=We.readBigUInt64LE(a,H.ZIP64SUB),e=We.readBigUInt64LE(a,H.ZIP64TOT),r=We.readBigUInt64LE(a,H.ZIP64SIZB),n=We.readBigUInt64LE(a,H.ZIP64OFF),s=0)},"loadFromBinary"),toBinary:o(function(){if(!i()){var a=Buffer.alloc(H.ENDHDR+s);return a.writeUInt32LE(H.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,H.ENDSUB),a.writeUInt16LE(e,H.ENDTOT),a.writeUInt32LE(r,H.ENDSIZ),a.writeUInt32LE(n,H.ENDOFF),a.writeUInt16LE(s,H.ENDCOM),a.fill(" ",H.ENDHDR),a}var a=Buffer.alloc(this.mainHeaderSize);let c=0;a.writeUInt32LE(H.ZIP64SIG,c),We.writeBigUInt64LE(a,H.ZIP64HDR-H.ZIP64LEAD,c+H.ZIP64SIZE),a.writeUInt16LE(45,c+H.ZIP64VEM),a.writeUInt16LE(45,c+H.ZIP64VER),a.writeUInt32LE(0,c+H.ZIP64DSK),a.writeUInt32LE(0,c+H.ZIP64DSKDIR),We.writeBigUInt64LE(a,t,c+H.ZIP64SUB),We.writeBigUInt64LE(a,e,c+H.ZIP64TOT),We.writeBigUInt64LE(a,r,c+H.ZIP64SIZB),We.writeBigUInt64LE(a,n,c+H.ZIP64OFF);let l=n+r;return c+=H.ZIP64HDR,a.writeUInt32LE(H.END64SIG,c),a.writeUInt32LE(0,c+H.END64START),We.writeBigUInt64LE(a,l,c+H.END64OFF),a.writeUInt32LE(1,c+H.END64NUMDISKS),c+=H.END64HDR,a.writeUInt32LE(H.ENDSIG,c),a.writeUInt32LE(0,c+4),a.writeUInt16LE(Math.min(t,H.EF_ZIP64_OR_16),c+H.ENDSUB),a.writeUInt16LE(Math.min(e,H.EF_ZIP64_OR_16),c+H.ENDTOT),a.writeUInt32LE(Math.min(r,H.EF_ZIP64_OR_32),c+H.ENDSIZ),a.writeUInt32LE(Math.min(n,H.EF_ZIP64_OR_32),c+H.ENDOFF),a.writeUInt16LE(s,c+H.ENDCOM),a.fill(" ",c+H.ENDHDR),a},"toBinary"),toJSON:o(function(){let a=o(function(c,l){let u=c.toString(16).toUpperCase();for(;u.length<l;)u="0"+u;return"0x"+u},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:a(n,4),commentLength:s}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ha=P(ma=>{ma.EntryHeader=zf();ma.MainHeader=qf()});var Kf=P((b5,Wf)=>{Wf.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:o(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:o(function(n){var s=e.createDeflateRaw(r),i=[],a=0;s.on("data",function(c){i.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var u=0;u<i.length;u++){var d=i[u];d.copy(c,l),l+=d.length}n&&n(c)}),s.end(t)},"deflateAsync")}}});var Jf=P((w5,Zf)=>{var Jw=+(process?.versions?.node??"").split(".")[0]||0;Zf.exports=function(t,e){var r=require("zlib");let n=Jw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:o(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:o(function(s){var i=r.createInflateRaw(n),a=[],c=0;i.on("data",function(l){a.push(l),c+=l.length}),i.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<a.length;d++){var f=a[d];f.copy(l,u),u+=f.length}s&&s(l)}),i.end(t)},"inflateAsync")}}});var tp=P((v5,ep)=>{"use strict";var{randomFillSync:Yf}=require("crypto"),Yw=rs(),Xw=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Qf=o((t,e)=>Math.imul(t,e)>>>0,"uMul"),Xf=o((t,e)=>Xw[(t^e)&255]^t>>>8,"crc32update"),Ur=o(()=>typeof Yf=="function"?Yf(Buffer.alloc(12)):Ur.node(),"genSalt");Ur.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ns={genSalt:Ur};function ss(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}o(ss,"Initkeys");ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Xf(e[0],t),e[1]+=e[0]&255,e[1]=Qf(e[1],134775813)+1,e[2]=Xf(e[2],e[1]>>>24),t};ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Qf(t,t^1)>>8&255};function Qw(t){let e=new ss(t);return function(r){let n=Buffer.alloc(r.length),s=0;for(let i of r)n[s++]=e.updateKeys(i^e.next());return n}}o(Qw,"make_decrypter");function e0(t){let e=new ss(t);return function(r,n,s=0){n||(n=Buffer.alloc(r.length));for(let i of r){let a=e.next();n[s++]=i^a,e.updateKeys(i)}return n}}o(e0,"make_encrypter");function t0(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Qw(r),s=n(t.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==i)throw Yw.WRONG_PASSWORD();return n(t.slice(12))}o(t0,"decrypt");function r0(t){Buffer.isBuffer(t)&&t.length>=12?ns.genSalt=function(){return t.slice(0,12)}:t==="node"?ns.genSalt=Ur.node:ns.genSalt=Ur}o(r0,"_salter");function n0(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=e0(r),i=ns.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(t.length+12);return s(i,a),s(t,a,12)}o(n0,"encrypt");ep.exports={decrypt:t0,encrypt:n0,_salter:r0}});var rp=P(is=>{is.Deflater=Kf();is.Inflater=Jf();is.ZipCrypto=tp()});var ya=P((x5,np)=>{var X=nr(),s0=ha(),je=X.Constants,ga=rp();np.exports=function(t,e){var r=new s0.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let d=t,f=typeof d.decoder=="object"?d.decoder:X.decoder;u=f.hasOwnProperty("efs")?f.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}o(_,"getCompressedDataFromZip");function g(m){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(m)===T}o(g,"crc32OK");function y(m,T,A){if(typeof T>"u"&&typeof m=="string"&&(A=m,m=void 0),i)return m&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var N=_();if(N.length===0)return m&&T&&T(N),N;if(r.encrypted){if(typeof A!="string"&&!Buffer.isBuffer(A))throw X.Errors.INVALID_PASS_PARAM();N=ga.ZipCrypto.decrypt(N,r,A)}var O;switch(r.method){case X.Constants.STORED:if(O=Buffer.alloc(N.length),N.copy(O),g(O))return m&&T&&T(O),O;throw m&&T&&T(O,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var b=new ga.Inflater(N,r.size);if(m)b.inflateAsync(function(j){T&&(g(j)?T(j):T(j,X.Errors.BAD_CRC()))});else{if(O=b.inflate(),!g(O))throw X.Errors.BAD_CRC(`"${f.decode(n)}"`);return O}break;default:throw m&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}o(y,"decompress");function E(m,T){if((!a||!a.length)&&Buffer.isBuffer(e))return m&&T&&T(_()),_();if(a.length&&!i){var A;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,A=Buffer.alloc(a.length),a.copy(A),m&&T&&T(A),A;default:case X.Constants.DEFLATED:var N=new ga.Deflater(a);if(m)N.deflateAsync(function(b){A=Buffer.alloc(b.length),r.compressedSize=b.length,b.copy(A),T&&T(A)});else{var O=N.deflate();return r.compressedSize=O.length,O}N=null;break}}else if(m&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}o(E,"compress");function w(m,T){return X.readBigUInt64LE(m,T)}o(w,"readUInt64LE");function S(m){try{for(var T=0,A,N,O;T+4<m.length;)A=m.readUInt16LE(T),T+=2,N=m.readUInt16LE(T),T+=2,O=m.slice(T,T+N),T+=N,je.ID_ZIP64===A&&I(O)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}o(S,"parseExtra");function I(m){var T,A,N,O;m.length>=je.EF_ZIP64_SCOMP&&(T=w(m,je.EF_ZIP64_SUNCOMP),r.size===je.EF_ZIP64_OR_32&&(r.size=T)),m.length>=je.EF_ZIP64_RHO&&(A=w(m,je.EF_ZIP64_SCOMP),r.compressedSize===je.EF_ZIP64_OR_32&&(r.compressedSize=A)),m.length>=je.EF_ZIP64_DSN&&(N=w(m,je.EF_ZIP64_RHO),r.offset===je.EF_ZIP64_OR_32&&(r.offset=N)),m.length>=je.EF_ZIP64_DSN+4&&(O=m.readUInt32LE(je.EF_ZIP64_DSN),r.diskNumStart===je.EF_ZIP64_OR_16&&(r.diskNumStart=O))}return o(I,"parseZip64ExtendedInformation"),{get entryName(){return f.decode(n)},get rawEntryName(){return n},set entryName(m){n=X.toBuffer(m,f.encode);var T=n[n.length-1];i=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(m){c=m,r.extraLength=m.length,S(m)},get comment(){return f.decode(s)},set comment(m){if(s=X.toBuffer(m,f.encode),r.commentLength=s.length,s.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let m=f.decode(n);return i?m.replace(/[/\\]$/,"").split("/").pop():m.split("/").pop()},get isDirectory(){return i},getCompressedData:o(function(){return E(!1,null)},"getCompressedData"),getCompressedDataAsync:o(function(m){E(!0,m)},"getCompressedDataAsync"),setData:o(function(m){a=X.toBuffer(m,X.decoder.encode),!i&&a.length?(r.size=a.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(m),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:o(function(m){return r.changed?a:y(!1,null,m)},"getData"),getDataAsync:o(function(m,T){r.changed?m(a):y(!0,m,T)},"getDataAsync"),set attr(m){r.attr=m},get attr(){return r.attr},set header(m){r.loadFromBinary(m)},get header(){return r},packCentralHeader:o(function(){r.flags_efs=this.efs,r.extraLength=c.length;var m=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(m,T),T+=n.length,c.copy(m,T),T+=r.extraLength,s.copy(m,T),m},"packCentralHeader"),packLocalHeader:o(function(){let m=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),A=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(A,m),m+=T.length,n.copy(A,m),m+=n.length,l.copy(A,m),m+=l.length,A},"packLocalHeader"),toJSON:o(function(){let m=o(function(T){return"<"+(T&&T.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:m(e),data:m(a)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ap=P((C5,ip)=>{var sp=ya(),i0=ha(),Ne=nr();ip.exports=function(t,e){var r=[],n=Object.create(null),s=Buffer.alloc(0),i=new i0.MainHeader,a=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:f}=u;t?y(u.readEntries):a=!0;function _(){let w=new Set;for(let S of Object.keys(n)){let I=S.split("/");if(I.pop(),!!I.length)for(let m=0;m<I.length;m++){let T=I.slice(0,m+1).join("/")+"/";w.add(T)}}for(let S of w)if(!(S in n)){let I=new sp(u);I.entryName=S,I.attr=16,I.temporary=!0,r.push(I),n[I.entryName]=I,l.add(I)}}o(_,"makeTemporaryFolders");function g(){if(a=!0,n=Object.create(null),i.diskEntries>(t.length-i.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(i.diskEntries);for(var w=i.offset,S=0;S<r.length;S++){var I=w,m=new sp(u,t);m.header=t.slice(I,I+=Ne.Constants.CENHDR),m.entryName=t.slice(I,I+=m.header.fileNameLength),m.header.extraLength&&(m.extra=t.slice(I,I+=m.header.extraLength)),m.header.commentLength&&(m.comment=t.slice(I,I+m.header.commentLength)),w+=m.header.centralHeaderSize,r[S]=m,n[m.entryName]=m}l.clear(),_()}o(g,"readEntries");function y(w){var S=t.length-Ne.Constants.ENDHDR,I=Math.max(0,S-65535),m=I,T=t.length,A=-1,N=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(I=0),S;S>=m;S--)if(t[S]===80){if(t.readUInt32LE(S)===Ne.Constants.ENDSIG){A=S,N=S,T=S+Ne.Constants.ENDHDR,m=S-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(S)===Ne.Constants.END64SIG){m=I;continue}if(t.readUInt32LE(S)===Ne.Constants.ZIP64SIG){A=S,T=S+Ne.readBigUInt64LE(t,S+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(A==-1)throw Ne.Errors.INVALID_FORMAT();i.loadFromBinary(t.slice(A,T)),i.commentLength&&(s=t.slice(N+Ne.Constants.ENDHDR)),w&&g()}o(y,"readMainHeader");function E(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,S)=>w.key.localeCompare(S.key)).map(w=>w.entry))}return o(E,"sortEntries"),{get entries(){return a||g(),r.filter(w=>!l.has(w))},get comment(){return f.decode(s)},set comment(w){s=Ne.toBuffer(w,f.encode),i.commentLength=s.length},getEntryCount:o(function(){return a?r.length:i.diskEntries},"getEntryCount"),forEach:o(function(w){this.entries.forEach(w)},"forEach"),getEntry:o(function(w){return a||g(),n[w]||null},"getEntry"),setEntry:o(function(w){a||g(),r.push(w),n[w.entryName]=w,i.totalEntries=r.length},"setEntry"),deleteFile:o(function(w,S=!0){a||g();let I=n[w];this.getEntryChildren(I,S).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:o(function(w){a||g();let S=n[w],I=r.indexOf(S);I>=0&&(r.splice(I,1),delete n[w],i.totalEntries=r.length)},"deleteEntry"),getEntryChildren:o(function(w,S=!0){if(a||g(),typeof w=="object")if(w.isDirectory&&S){let I=[],m=w.entryName;for(let T of r)T.entryName.startsWith(m)&&I.push(T);return I}else return[w];return[]},"getEntryChildren"),getChildCount:o(function(w){if(w&&w.isDirectory){let S=this.getEntryChildren(w);return S.includes(w)?S.length-1:S.length}return 0},"getChildCount"),compressToBuffer:o(function(){a||g(),E();let w=[],S=[],I=0,m=0;i.size=0,i.offset=0;let T=0;for(let O of this.entries){let b=O.getCompressedData();O.header.offset=m;let j=O.packLocalHeader(),G=j.length+b.length;m+=G,w.push(j),w.push(b);let B=O.packCentralHeader();S.push(B),i.size+=B.length,I+=G+B.length,T++}I+=i.mainHeaderSize,i.offset=m,i.totalEntries=T,m=0;let A=Buffer.alloc(I);for(let O of w)O.copy(A,m),m+=O.length;for(let O of S)O.copy(A,m),m+=O.length;let N=i.toBinary();return s&&s.copy(N,N.length-s.length),N.copy(A,m),t=A,a=!1,A},"compressToBuffer"),toAsyncBuffer:o(function(w,S,I,m){try{a||g(),E();let T=[],A=[],N=0,O=0,b=0;i.size=0,i.offset=0;let j=o(function(G){if(G.length>0){let B=G.shift(),Z=B.entryName+B.extra.toString();I&&I(Z),B.getCompressedDataAsync(function(ce){m&&m(Z),B.header.offset=O;let ke=B.packLocalHeader(),xt=ke.length+ce.length;O+=xt,T.push(ke),T.push(ce);let K=B.packCentralHeader();A.push(K),i.size+=K.length,N+=xt+K.length,b++,j(G)})}else{N+=i.mainHeaderSize,i.offset=O,i.totalEntries=b,O=0;let B=Buffer.alloc(N);T.forEach(function(ce){ce.copy(B,O),O+=ce.length}),A.forEach(function(ce){ce.copy(B,O),O+=ce.length});let Z=i.toBinary();s&&s.copy(Z,Z.length-s.length),Z.copy(B,O),t=B,a=!1,w(B)}},"compress2Buffer");j(Array.from(this.entries))}catch(T){S(T)}},"toAsyncBuffer")}}});var lp=P((O5,cp)=>{var ae=nr(),ie=require("path"),a0=ya(),o0=ap(),jt=o((...t)=>ae.findLast(t,e=>typeof e=="boolean"),"get_Bool"),op=o((...t)=>ae.findLast(t,e=>typeof e=="string"),"get_Str"),c0=o((...t)=>ae.findLast(t,e=>typeof e=="function"),"get_Fun"),l0={noSort:!1,readEntries:!1,method:ae.Constants.NONE,fs:null};cp.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),l0);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=ae.Constants.BUFFER,t=void 0)),Object.assign(n,e);let s=new ae(n),i=o(y=>{y.filter(E=>E.attr).sort((E,w)=>w.path.length-E.path.length).forEach(E=>s.fs.chmodSync(E.path,E.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))n.method=ae.Constants.FILE,n.filename=t,r=s.fs.readFileSync(t);else throw ae.Errors.INVALID_FILENAME();let a=new o0(r,n),{canonical:c,sanitize:l,zipnamefix:u}=ae;function d(y){if(y&&a){var E;if(typeof y=="string"&&(E=a.getEntry(ie.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=a.getEntry(y.entryName)),E)return E}return null}o(d,"getEntry");function f(y){let{join:E,normalize:w,sep:S}=ie.posix;return E(ie.isAbsolute(y)?"/":".",w(S+y.split("\\").join(S)+S))}o(f,"fixPath");function _(y){return y instanceof RegExp?(function(E){return function(w){return E.test(w)}})(y):typeof y!="function"?()=>!0:y}o(_,"filenameFilter");let g=o((y,E)=>{let w=E.slice(-1);return w=w===s.sep?s.sep:"",ie.relative(y,E)+w},"relativePath");return{readFile:o(function(y,E){var w=d(y);return w&&w.getData(E)||null},"readFile"),childCount:o(function(y){let E=d(y);if(E)return a.getChildCount(E)},"childCount"),readFileAsync:o(function(y,E){var w=d(y);w?w.getDataAsync(E):E(null,"getEntry failed for:"+y)},"readFileAsync"),readAsText:o(function(y,E){var w=d(y);if(w){var S=w.getData();if(S&&S.length)return S.toString(E||"utf8")}return""},"readAsText"),readAsTextAsync:o(function(y,E,w){var S=d(y);S?S.getDataAsync(function(I,m){if(m){E(I,m);return}I&&I.length?E(I.toString(w||"utf8")):E("")}):E("")},"readAsTextAsync"),deleteFile:o(function(y,E=!0){var w=d(y);w&&a.deleteFile(w.entryName,E)},"deleteFile"),deleteEntry:o(function(y){var E=d(y);E&&a.deleteEntry(E.entryName)},"deleteEntry"),addZipComment:o(function(y){a.comment=y},"addZipComment"),getZipComment:o(function(){return a.comment||""},"getZipComment"),addZipEntryComment:o(function(y,E){var w=d(y);w&&(w.comment=E)},"addZipEntryComment"),getZipEntryComment:o(function(y){var E=d(y);return E&&E.comment||""},"getZipEntryComment"),updateFile:o(function(y,E){var w=d(y);w&&w.setData(E)},"updateFile"),addLocalFile:o(function(y,E,w,S){if(s.fs.existsSync(y)){E=E?f(E):"";let I=ie.win32.basename(ie.win32.normalize(y));E+=w||I;let m=s.fs.statSync(y),T=m.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);m.isDirectory()&&(E+=s.sep),this.addFile(E,T,S,m)}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFile"),addLocalFileAsync:o(function(y,E){y=typeof y=="object"?y:{localPath:y};let w=ie.resolve(y.localPath),{comment:S}=y,{zipPath:I,zipName:m}=y,T=this;s.fs.stat(w,function(A,N){if(A)return E(A,!1);I=I?f(I):"";let O=ie.win32.basename(ie.win32.normalize(w));if(I+=m||O,N.isFile())s.fs.readFile(w,function(b,j){return b?E(b,!1):(T.addFile(I,j,S,N),setImmediate(E,void 0,!0))});else if(N.isDirectory())return I+=s.sep,T.addFile(I,Buffer.alloc(0),S,N),setImmediate(E,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:o(function(y,E,w){if(w=_(w),E=E?f(E):"",y=ie.normalize(y),s.fs.existsSync(y)){let S=s.findFiles(y),I=this;if(S.length)for(let m of S){let T=ie.join(E,g(y,m));w(T)&&I.addLocalFile(m,ie.dirname(T))}}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFolder"),addLocalFolderAsync:o(function(y,E,w,S){S=_(S),w=w?f(w):"",y=ie.normalize(y);var I=this;s.fs.open(y,"r",function(m){if(m&&m.code==="ENOENT")E(void 0,ae.Errors.FILE_NOT_FOUND(y));else if(m)E(void 0,m);else{var T=s.findFiles(y),A=-1,N=o(function(){if(A+=1,A<T.length){var O=T[A],b=g(y,O).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(b)?s.fs.stat(O,function(j,G){j&&E(void 0,j),G.isFile()?s.fs.readFile(O,function(B,Z){B?E(void 0,B):(I.addFile(w+b,Z,"",G),N())}):(I.addFile(w+b+"/",Buffer.alloc(0),"",G),N())}):process.nextTick(()=>{N()})}else E(!0,void 0)},"next");N()}})},"addLocalFolderAsync"),addLocalFolderAsync2:o(function(y,E){let w=this;y=typeof y=="object"?y:{localPath:y};let S=ie.resolve(f(y.localPath)),{zipPath:I,filter:m,namefix:T}=y;m instanceof RegExp?m=(function(O){return function(b){return O.test(b)}})(m):typeof m!="function"&&(m=o(function(){return!0},"filter")),I=I?f(I):"",T==="latin1"&&(T=o(O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=o(O=>O,"namefix"));let A=o(O=>ie.join(I,T(g(S,O))),"relPathFix"),N=o(O=>ie.win32.basename(ie.win32.normalize(T(O))),"fileNameFix");s.fs.open(S,"r",function(O){O&&O.code==="ENOENT"?E(void 0,ae.Errors.FILE_NOT_FOUND(S)):O?E(void 0,O):s.findFilesAsync(S,function(b,j){if(b)return E(b);j=j.filter(G=>m(A(G))),j.length||E(void 0,!1),setImmediate(j.reverse().reduce(function(G,B){return function(Z,ce){if(Z||ce===!1)return setImmediate(G,Z,!1);w.addLocalFileAsync({localPath:B,zipPath:ie.dirname(A(B)),zipName:N(B)},G)}},E))})})},"addLocalFolderAsync2"),addLocalFolderPromise:o(function(y,E){return new Promise((w,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(I,m)=>{I&&S(I),m&&w(this)})})},"addLocalFolderPromise"),addFile:o(function(y,E,w,S){y=u(y);let I=d(y),m=I!=null;m||(I=new a0(n),I.entryName=y),I.comment=w||"";let T=typeof S=="object"&&S instanceof s.fs.Stats;T&&(I.header.time=S.mtime);var A=I.isDirectory?16:0;let N=I.isDirectory?16384:32768;return T?N|=4095&S.mode:typeof S=="number"?N|=4095&S:N|=I.isDirectory?493:420,A=(A|N<<16)>>>0,I.attr=A,I.setData(E),m||a.setEntry(I),I},"addFile"),getEntries:o(function(y){return a.password=y,a?a.entries:[]},"getEntries"),getEntry:o(function(y){return d(y)},"getEntry"),getEntryCount:o(function(){return a.getEntryCount()},"getEntryCount"),forEach:o(function(y){return a.forEach(y)},"forEach"),extractEntryTo:o(function(y,E,w,S,I,m){S=jt(!1,S),I=jt(!1,I),w=jt(!0,w),m=op(I,m);var T=d(y);if(!T)throw ae.Errors.NO_ENTRY();var A=c(T.entryName),N=l(E,m&&!T.isDirectory?c(m):w?A:ie.basename(A));if(T.isDirectory){var O=a.getEntryChildren(T);return O.forEach(function(G){if(G.isDirectory)return;var B=G.getData();if(!B)throw ae.Errors.CANT_EXTRACT_FILE();var Z=c(w?G.entryName:G.entryName.substring(T.entryName.length)),ce=l(E,Z);let ke=I?G.header.fileAttr:void 0;s.writeFileTo(ce,B,S,ke)}),!0}var b=T.getData(a.password);if(!b)throw ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(N)&&!S)throw ae.Errors.CANT_OVERRIDE();let j=I?y.header.fileAttr:void 0;return s.writeFileTo(N,b,S,j),!0},"extractEntryTo"),test:o(function(y){if(!a)return!1;for(var E of a.entries)try{if(E.isDirectory)continue;var w=E.getData(y);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:o(function(y,E,w,S){if(w=jt(!1,w),S=op(w,S),E=jt(!1,E),!a)throw ae.Errors.NO_ZIP();let I=[];a.entries.forEach(function(m){var T=l(y,c(m.entryName));if(m.isDirectory){s.makeDir(T),w&&I.push({path:T,attr:m.header.fileAttr});return}var A=m.getData(S);if(!A)throw ae.Errors.CANT_EXTRACT_FILE();let N=w?m.header.fileAttr:void 0;s.writeFileTo(T,A,E,N);try{s.fs.utimesSync(T,m.header.time,m.header.time)}catch{}}),i(I)},"extractAllTo"),extractAllToAsync:o(function(y,E,w,S){if(S=c0(E,w,S),w=jt(!1,w),E=jt(!1,E),!S)return new Promise((b,j)=>{this.extractAllToAsync(y,E,w,function(G){G?j(G):b(this)})});if(!a){S(ae.Errors.NO_ZIP());return}y=ie.resolve(y);let I=o(b=>l(y,ie.normalize(c(b.entryName))),"getPath"),m=o((b,j)=>new Error(b+': "'+j+'"'),"getError"),T=[],A=[];a.entries.forEach(b=>{b.isDirectory?T.push(b):A.push(b)});let N=[];for(let b of T){let j=I(b),G=w?b.header.fileAttr:void 0;try{s.makeDir(j)}catch{S(m("Unable to create folder",j));continue}G&&N.push({path:j,attr:G});try{s.fs.utimesSync(j,b.header.time,b.header.time)}catch{}}let O=o(b=>{if(!b)try{i(N)}catch(j){return S(m("Unable to set folder permissions",j.path||""))}S(b)},"done");A.reverse().reduce(function(b,j){return function(G){if(G)b(G);else{let B=ie.normalize(c(j.entryName)),Z=l(y,B);j.getDataAsync(function(ce,ke){if(ke)b(ke);else if(!ce)b(ae.Errors.CANT_EXTRACT_FILE());else{let xt=w?j.header.fileAttr:void 0;s.writeFileToAsync(Z,ce,E,xt,function(K){if(!K)return b(m("Unable to write file",Z));s.fs.utimes(Z,j.header.time,j.header.time,function(){b()})})}})}}},O)()},"extractAllToAsync"),writeZip:o(function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&n.filename&&(y=n.filename),!!y){var w=a.compressToBuffer();if(w){var S=s.writeFileTo(y,w,!0);typeof E=="function"&&E(S?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:o(function(y,E){let{overwrite:w,perm:S}=Object.assign({overwrite:!0},E);return new Promise((I,m)=>{!y&&n.filename&&(y=n.filename),y||m("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let A=o(N=>N?I(N):m("ADM-ZIP: Wasn't able to write zip file"),"ret");s.writeFileToAsync(y,T,w,S,A)},m)})},"writeZipPromise"),toBufferPromise:o(function(){return new Promise((y,E)=>{a.toAsyncBuffer(y,E)})},"toBufferPromise"),toBuffer:o(function(y,E,w,S){return typeof y=="function"?(a.toAsyncBuffer(y,E,w,S),null):a.compressToBuffer()},"toBuffer")}}});var gp=P((P5,ht)=>{var ba=require("fs"),os=require("path"),d0=require("os"),f0=require("crypto"),dp=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function p0(){return dp[Math.floor(Math.random()*dp.length)]}o(p0,"_getRandomTip");function sr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(sr,"parseBoolean");function m0(){return process.stdout.isTTY}o(m0,"supportsAnsi");function h0(t){return m0()?`\x1B[2m${t}\x1B[0m`:t}o(h0,"dim");var g0=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function y0(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
4
+ `);let n;for(;(n=g0.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
5
+ `),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(y0,"parse");function _0(t){t=t||{};let e=hp(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=mp(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=E0(r,c);i=me.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return me.parse(i)}o(_0,"_parseVault");function b0(t){console.error(`\u26A0 ${t}`)}o(b0,"_warn");function Fr(t){console.log(`\u2506 ${t}`)}o(Fr,"_debug");function pp(t){console.log(`\u25C7 ${t}`)}o(pp,"_log");function mp(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(mp,"_dotenvKey");function E0(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(E0,"_instructions");function hp(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)ba.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=os.resolve(process.cwd(),".env.vault");return ba.existsSync(e)?e:null}o(hp,"_vaultPath");function fp(t){return t[0]==="~"?os.join(d0.homedir(),t.slice(1)):t}o(fp,"_resolveHome");function w0(t){let e=sr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=sr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&pp("loading env from encrypted .env.vault");let n=me._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),me.populate(s,n,t),{parsed:n}}o(w0,"_configVault");function T0(t){let e=os.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=sr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=sr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&Fr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[fp(t.path)];else{a=[];for(let d of t.path)a.push(fp(d))}let c,l={};for(let d of a)try{let f=me.parse(ba.readFileSync(d,{encoding:r}));me.populate(l,f,t)}catch(f){s&&Fr(`failed to load ${d} ${f.message}`),c=f}let u=me.populate(n,l,t);if(s=sr(n.DOTENV_CONFIG_DEBUG||s),i=sr(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,f=[];for(let _ of a)try{let g=os.relative(process.cwd(),_);f.push(g)}catch(g){s&&Fr(`failed to load ${_} ${g.message}`),c=g}pp(`injected env (${d}) from ${f.join(",")} ${h0(`// tip: ${p0()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(T0,"configDotenv");function v0(t){if(mp(t).length===0)return me.configDotenv(t);let e=hp(t);return e?me._configVault(t):(b0(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}o(v0,"config");function S0(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=f0.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(S0,"decrypt");function I0(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&Fr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(I0,"populate");var me={configDotenv:T0,_configVault:w0,_parseVault:_0,config:v0,decrypt:S0,parse:y0,populate:I0};ht.exports.configDotenv=me.configDotenv;ht.exports._configVault=me._configVault;ht.exports._parseVault=me._parseVault;ht.exports.config=me.config;ht.exports.decrypt=me.decrypt;ht.exports.parse=me.parse;ht.exports.populate=me.populate;ht.exports=me});var PT={};wm(PT,{TestRunMonitor:()=>_s});module.exports=Tm(PT);var vs=o(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var z3=require("@playwright/test");var f3=require("@playwright/test");var yv=require("@playwright/test");var pv=require("@playwright/test");var Wa=Object.defineProperty,W=o((t,e)=>{let r={};for(var n in t)Wa(r,n,{get:t[n],enumerable:!0});return e||Wa(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function Ka(t){let e=Symbol.for(t);return{brand(r,n){let s=n?Symbol.for(`${t}.${n}`):e;class i extends r{static{o(this,"_Branded")}[s]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&s in c&&c[s]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return Ka(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(Ka,"createNamespace");var Za=Ka("langchain");var Ss=Za.sub("error"),Ja=class extends Ss.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Sm=class extends Ss.brand(Ja,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Av=class Ya extends Ss.brand(Ja,"context-overflow"){static{o(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new Ya(e.message);return r.cause=e,r}};var Im=/([A-Z]+)([A-Z][a-z0-9]+)/g,xm=/([a-z0-9])([A-Z])/g,Am=/[-_\s]+/g;function Cm(t){return t.replace(Im,"$1_$2").replace(xm,"$1_$2").replace(Am,"_").toLowerCase()}o(Cm,"snakeCase");function Xa(t,e){return e?.[t]||Cm(t)}o(Xa,"keyToJson");function Qa(t,e,r){let n={};for(let s in t)Object.hasOwn(t,s)&&(n[e(s,r)]=t[s]);return n}o(Qa,"mapKeys");var Rm="__lc_escaped__";function Om(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Om,"needsEscaping");function Nm(t){return{[Rm]:t}}o(Nm,"escapeObject");function Mm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Mm,"isSerializableLike");function km(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}o(km,"createNotImplemented");function qr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return km(t);if(Mm(t))return t;e.add(t);let r=t;if(Om(r))return e.delete(t),Nm(r);let n={};for(let[s,i]of Object.entries(r))n[s]=qr(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>qr(r,e)):t}o(qr,"escapeIfNeeded");function eo(t){return Array.isArray(t)?[...t]:{...t}}o(eo,"shallowCopy");function Pm(t,e){let r=eo(t);for(let[n,s]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),c=r;for(let l of a.reverse()){if(c[l]===void 0)break;c[l]=eo(c[l]),c=c[l]}c[i]!==void 0&&(c[i]={lc:1,type:"secret",id:[s]})}return r}o(Pm,"replaceSecrets");function Is(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}o(Is,"get_lc_unique_name");var Ot=class to{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Is(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof to||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...f]=c.split(".").reverse();for(let _ of f.reverse()){if(!(_ in l)||l[_]===void 0)return;(!(_ in u)||u[_]===void 0)&&(typeof l[_]=="object"&&l[_]!=null?u[_]={}:Array.isArray(l[_])&&(u[_]=[])),l=l[_],u=u[_]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let s={},i=new WeakSet;i.add(this);for(let[c,l]of Object.entries(n))s[c]=qr(l,i);let a=Qa(Object.keys(r).length?Pm(s,r):s,Xa,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function ur(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}o(ur,"isDataContentBlock");function Wr(t){return ur(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(Wr,"isURLContentBlock");function Kr(t){return ur(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(Kr,"isBase64ContentBlock");function xs(t){return ur(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(xs,"isIDContentBlock");function Zr({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let s=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:s}}}o(Zr,"parseBase64DataUrl");function k(t,e){return F(t)&&t.type===e}o(k,"_isContentBlock");function F(t){return typeof t=="object"&&t!==null}o(F,"_isObject");function fe(t){return Array.isArray(t)}o(fe,"_isArray");function x(t){return typeof t=="string"}o(x,"_isString");function Ue(t){return typeof t=="number"}o(Ue,"_isNumber");function Jr(t){return t instanceof Uint8Array}o(Jr,"_isBytesArray");function As(t){try{return JSON.parse(t)}catch{return}}o(As,"safeParseJson");var Fe=o(t=>t(),"iife");function Lm(t){if(t.type==="char_location"&&x(t.document_title)&&Ue(t.start_char_index)&&Ue(t.end_char_index)&&x(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="page_location"&&x(t.document_title)&&Ue(t.start_page_number)&&Ue(t.end_page_number)&&x(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="content_block_location"&&x(t.document_title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="web_search_result_location"&&x(t.url)&&x(t.title)&&x(t.encrypted_index)&&x(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:s}}if(t.type==="search_result_location"&&x(t.source)&&x(t.title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:s,cited_text:i,...a}=t;return{...a,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:s,citedText:i}}}o(Lm,"convertAnthropicAnnotation");function no(t){if(k(t,"document")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&x(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(k(t,"image")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}o(no,"convertToV1FromAnthropicContentBlock");function so(t){function*e(){for(let r of t){let n=no(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(so,"convertToV1FromAnthropicInput");function ro(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){let{text:s,citations:i,...a}=n;if(fe(i)&&i.length){let c=i.reduce((l,u)=>{let d=Lm(u);return d?[...l,d]:l},[]);yield{...a,type:"text",text:s,annotations:c};continue}else{yield{...a,type:"text",text:s};continue}}else if(k(n,"thinking")&&x(n.thinking)){let{thinking:s,signature:i,...a}=n;yield{...a,type:"reasoning",reasoning:s,signature:i};continue}else if(k(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_use")&&x(n.name)&&x(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(k(n,"input_json_delta")){if(Dm(t)&&t.tool_call_chunks?.length){let s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(k(n,"server_tool_use")&&x(n.name)&&x(n.id)){let{name:s,id:i}=n;if(s==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.query))return n.input.query;if(x(n.partial_json)){let a=As(n.partial_json);if(a?.query)return a.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.code))return n.input.code;if(x(n.partial_json)){let a=As(n.partial_json);if(a?.code)return a.code}return""})}};continue}}else if(k(n,"web_search_tool_result")&&x(n.tool_use_id)&&fe(n.content)){let{content:s,tool_use_id:i}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:s.reduce((a,c)=>k(c,"web_search_result")?[...a,c.url]:a,[])}};continue}else if(k(n,"code_execution_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(k(n,"mcp_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(k(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(k(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let s=no(n);if(s){yield s;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(ro,"convertToV1FromAnthropicMessage");var io={translateContent:ro,translateContentChunk:ro};function Dm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o(Dm,"_isAIMessageChunk");function $m(t){return Wr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Kr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:xs(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o($m,"convertToV1FromDataContentBlock");function ao(t){return t.map($m)}o(ao,"convertToV1FromDataContent");function oo(t){return!!(k(t,"image_url")&&F(t.image_url)||k(t,"input_audio")&&F(t.input_audio)||k(t,"file")&&F(t.file))}o(oo,"isOpenAIDataBlock");function co(t){if(k(t,"image_url")&&F(t.image_url)&&x(t.image_url.url)){let e=Zr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(k(t,"input_audio")&&F(t.input_audio)&&x(t.input_audio.data)&&x(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(k(t,"file")&&F(t.file)&&x(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(x(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}o(co,"convertToV1FromOpenAIDataBlock");function Um(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Um,"convertToV1FromChatCompletions");function Fm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Fm,"convertToV1FromChatCompletionsChunk");function Yr(t){let e=[];for(let r of t)oo(r)?e.push(co(r)):e.push(r);return e}o(Yr,"convertToV1FromChatCompletionsInput");function Bm(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:s}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:s}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}o(Bm,"convertResponsesAnnotation");function lo(t){function*e(){F(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,s)=>F(s)&&x(s.text)?`${n}${s.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(k(n,"text")){let{text:s,annotations:i,phase:a,extras:c,...l}=n,u=F(c)?{...c}:{};x(a)&&(u.phase=a);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(i)?yield{...l,...d,type:"text",text:String(s),annotations:i.map(Bm)}:yield{...l,...d,type:"text",text:String(s)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(F(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(k(n,"web_search_call")){let s={};if(F(n.action)&&x(n.action.query)&&(s.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:s},n.status==="completed"||n.status==="failed"){let i={};F(n.action)&&(i.action=n.action),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:i}}continue}else if(k(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:fe(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(k(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(k(n,"code_interpreter_call")){if(x(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let s=Fe(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let i of n.outputs)if(k(i,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(i.logs),stdout:[0,void 0].includes(s)?String(i.logs):void 0}};continue}}continue}else if(k(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(k(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(k(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_search_call")){let s={};F(n.arguments)&&Object.assign(s,n.arguments);let i={};x(n.execution)&&(i.execution=n.execution),x(n.status)&&(i.status=n.status),x(n.call_id)&&(i.call_id=n.call_id),yield{id:x(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:s,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(k(n,"tool_search_output")){let s={name:"tool_search"};x(n.execution)&&(s.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:s};continue}else if(k(n,"image_generation_call")){x(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:x(n.id)?n.id:void 0,metadata:{status:x(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}F(n)&&(yield{type:"non_standard",value:n})}}return o(e,"iterateContent"),Array.from(e())}o(lo,"convertToV1FromResponses");function jm(t){function*e(){yield*lo(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return o(e,"iterateContent"),Array.from(e())}o(jm,"convertToV1FromResponsesChunk");var uo={translateContent:o(t=>typeof t.content=="string"?Um(t):lo(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Fm(t):jm(t),"translateContentChunk")};function Cs(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(Cs,"isMessage");function fo(t,e="pretty"){return e==="pretty"?Hm(t):JSON.stringify(t)}o(fo,"convertToFormattedString");function Hm(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),s="=".repeat(n),i=r.length%2===0?s:`${s}=`;if(e.push(`${s}${r}${i}`),t.type==="ai"){let a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(let c of a.tool_calls){e.push(` ${c.name} (${c.id})`),e.push(` Call ID: ${c.id}`),e.push(" Args:");for(let[l,u]of Object.entries(c.args))e.push(` ${l}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
6
+ `)}o(Hm,"convertToPrettyString");var Rs=Symbol.for("langchain.message");function Gm(t,e){function r(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,s+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],s+1);return i}return o(r,"helper"),JSON.stringify(r(t,0),null,2)}o(Gm,"stringifyWithDepthLimit");var ut=class extends Ot{static{o(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Rs]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ao,Yr,so].reduce((e,r)=>r(e),t)}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}}static isInstance(t){return typeof t=="object"&&t!==null&&Rs in t&&t[Rs]===!0&&Cs(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=Gm(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return fo(this,t)}};function Os(t){let e=[],r=[];for(let n of t)if(n.function){let s=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:s||"",args:i||{},id:n.id})}catch{r.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}o(Os,"defaultToolCallParser");function Ns(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}o(Ns,"convertFileFormatToMimeType");function qm(t){if(F(t.document)&&F(t.document.source)){let e=Ns(F(t.document)&&x(t.document.format)?t.document.format:"");if(F(t.document.source)){if(F(t.document.source.s3Location)&&x(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Jr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(x(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(fe(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>F(n)&&x(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}o(qm,"convertConverseDocumentBlock");function Wm(t){if(k(t,"image")&&F(t.image)){let e=Ns(F(t.image)&&x(t.image.format)?t.image.format:"");if(F(t.image.source)){if(F(t.image.source.s3Location)&&x(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Jr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}o(Wm,"convertConverseImageBlock");function Km(t){if(k(t,"video")&&F(t.video)){let e=Ns(F(t.video)&&x(t.video.format)?t.video.format:"");if(F(t.video.source)){if(F(t.video.source.s3Location)&&x(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Jr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}o(Km,"convertConverseVideoBlock");function po(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(k(n,"citations_content")&&F(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((s,i)=>F(i)&&x(i.text)?s+i.text:s,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((s,i)=>{if(F(i)){let a=fe(i.sourceContent)?i.sourceContent.reduce((l,u)=>F(u)&&x(u.text)?l+u.text:l,""):"",c=Fe(()=>{if(F(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(F(l))return{source:Ue(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ue(l.start)?l.start:void 0,endIndex:Ue(l.end)?l.end:void 0}}return{}});s.push({type:"citation",citedText:a,...c})}return s},[]):[]};continue}else if(k(n,"document")&&F(n.document)){yield qm(n);continue}else if(k(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(k(n,"image")&&F(n.image)){yield Wm(n);continue}else if(k(n,"reasoning_content")&&x(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(k(n,"tool_call"))continue;if(k(n,"video")&&F(n.video)){yield Km(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(po,"convertToV1FromChatBedrockConverseMessage");var mo={translateContent:po,translateContentChunk:po};function ho(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(ho,"convertToV1FromDeepSeekMessage");var go={translateContent:ho,translateContentChunk:ho};function yo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(k(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(k(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(k(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(yo,"convertToV1FromChatGoogleMessage");var _o={translateContent:yo,translateContentChunk:yo};function bo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"reasoning")&&x(n.reasoning)){let s=Fe(()=>{let i=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});x(s)?yield{type:"reasoning",reasoning:n.reasoning,signature:s}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"image_url")){if(x(n.image_url))if(n.image_url.startsWith("data:")){let s=n.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(k(n,"media")&&x(n.mimeType)&&x(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(bo,"convertToV1FromChatVertexMessage");var Eo={translateContent:bo,translateContentChunk:bo};function wo(t){let e=[],r=t.additional_kwargs?.reasoning;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,s=n.match(/<think>([\s\S]*?)<\/think>/);if(s){let i=s[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)){let s=n.text,i=s.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(wo,"convertToV1FromGroqMessage");var To={translateContent:wo,translateContentChunk:wo};function vo(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(vo,"convertToV1FromOllamaMessage");var So={translateContent:vo,translateContentChunk:vo};function Io(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let s of r){if(s==null||typeof s!="object")continue;let i=s.type;if(i==="reasoning.summary"){let a=s.summary;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}else if(i==="reasoning.text"){let a=s.text;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}}if(!n){let s=t.additional_kwargs?.reasoning_content;x(s)&&s.length>0&&e.push({type:"reasoning",reasoning:s})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&x(s.text)&&e.push({type:"text",text:s.text});for(let s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}o(Io,"convertToV1FromOpenRouterMessage");var xo={translateContent:Io,translateContentChunk:Io};function Ao(t){let e=[];if(F(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let s=n.summary.reduce((i,a)=>F(a)&&x(a.text)?`${i}${a.text}`:i,"");s.length>0&&e.push({type:"reasoning",reasoning:s})}}let r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Ao,"convertToV1FromXAIMessage");var Co={translateContent:Ao,translateContentChunk:Ao};function Ro(t){function*e(){let r=Fe(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(s=>"thoughtSignature"in s)){let s=[...t.content];for(let i=s.length-1;i>=0;i--){let a=s[i];if(a.type==="text"&&!a.thought)return a.thoughtSignature=n.thoughtSignature,s}}return t.content}});for(let n of r){let s=Fe(()=>k(n,"text")&&x(n.text)?{type:"text",text:n.text}:k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:k(n,"functionResponse")?{type:"non_standard",value:n}:k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:k(n,"executableCode")?{type:"non_standard",value:n}:k(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),i=Fe(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),a={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...i};for(let c in a)a[c]===void 0&&delete a[c];yield a}}return o(e,"iterateContent"),Array.from(e())}o(Ro,"convertToV1FromChatGoogleMessage");var Oo={translateContent:Ro,translateContentChunk:Ro};globalThis.lc_block_translators_registry??=new Map([["anthropic",io],["bedrock-converse",mo],["deepseek",go],["google",Oo],["google-genai",_o],["google-vertexai",Eo],["groq",To],["ollama",So],["openai",uo],["openrouter",xo],["xai",Co]]);function No(t){return globalThis.lc_block_translators_registry.get(t)}o(No,"getTranslator");function Mo(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}o(Mo,"mergeModalitiesTokenDetails");function Zm(t,e){let r={...Mo(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}o(Zm,"mergeInputTokenDetails");function Jm(t,e){let r={...Mo(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(Jm,"mergeOutputTokenDetails");function Xr(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:Zm(t?.input_token_details,e?.input_token_details),output_token_details:Jm(t?.output_token_details,e?.output_token_details)}}o(Xr,"mergeUsageMetadata");var bt=class extends ut{static{o(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
7
+
8
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[s,i]=Os(r);e.tool_calls=s??[],e.invalid_tool_calls=i??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let i=e.tool_calls.filter(a=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===a.id&&c.name===a.name));e.contentBlocks.push(...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let s=e.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!e.tool_calls?.some(a=>a.id===i.id&&a.name===i.name));s.length>0&&(e.tool_calls=[...e.tool_calls??[],...s.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=No(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function nh(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}o(nh,"_contentBlockToString");function tn(t,e="Human",r="AI"){let n=[];for(let s of t){let i;if(s.type==="human")i=e;else if(s.type==="ai")i=r;else if(s.type==="system")i="System";else if(s.type==="tool")i="Tool";else if(s.type==="generic")i=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);let a=s.name?`${s.name}, `:"",c=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(nh).filter(Boolean).join(""):"",l=`${i}: ${a}${c}`;if(s.type==="ai"){let u=s;u.tool_calls&&u.tool_calls.length>0?l+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(l+=JSON.stringify(u.additional_kwargs.function_call))}n.push(l)}return n.join(`
9
+ `)}o(tn,"getBufferString");var $="0123456789abcdef".split(""),sh=[-2147483648,8388608,32768,128],Ze=[24,16,8,0],rn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ge=[];function et(t,e){e?(ge[0]=ge[16]=ge[1]=ge[2]=ge[3]=ge[4]=ge[5]=ge[6]=ge[7]=ge[8]=ge[9]=ge[10]=ge[11]=ge[12]=ge[13]=ge[14]=ge[15]=0,this.blocks=ge):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}o(et,"Sha256");et.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,i,a=t.length,c=this.blocks;s<a;){if(this.hashed&&(this.hashed=!1,c[0]=this.block,this.block=c[16]=c[1]=c[2]=c[3]=c[4]=c[5]=c[6]=c[7]=c[8]=c[9]=c[10]=c[11]=c[12]=c[13]=c[14]=c[15]=0),e)for(i=this.start;s<a&&i<64;++s)c[i>>>2]|=t[s]<<Ze[i++&3];else for(i=this.start;s<a&&i<64;++s)n=t.charCodeAt(s),n<128?c[i>>>2]|=n<<Ze[i++&3]:n<2048?(c[i>>>2]|=(192|n>>>6)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):n<55296||n>=57344?(c[i>>>2]|=(224|n>>>12)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++s)&1023),c[i>>>2]|=(240|n>>>18)<<Ze[i++&3],c[i>>>2]|=(128|n>>>12&63)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=c[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};et.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=sh[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};et.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=this.blocks,u,d,f,_,g,y,E,w,S,I,m;for(u=16;u<64;++u)g=l[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=l[u-2],f=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,l[u]=l[u-16]+d+l[u-7]+f<<0;for(m=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,g=l[0]-1413257819,c=g-150054599<<0,n=g+24177077<<0):(w=704751109,g=l[0]-210244248,c=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),f=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),w=t&e,_=w^t&r^m,E=s&i^~s&a,g=c+f+E+rn[u]+l[u],y=d+_,c=n+g<<0,n=g+y<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),f=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),S=n&t,_=S^n&e^w,E=a&c^~a&s,g=i+f+E+rn[u+1]+l[u+1],y=d+_,a=r+g<<0,r=g+y<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),f=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),I=r&n,_=I^r&t^S,E=i&a^~i&c,g=s+f+E+rn[u+2]+l[u+2],y=d+_,i=e+g<<0,e=g+y<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),f=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),m=e&r,_=m^e&n^I,E=i&a^~i&c,g=s+f+E+rn[u+3]+l[u+3],y=d+_,s=t+g<<0,t=g+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0,this.h5=this.h5+i<<0,this.h6=this.h6+a<<0,this.h7=this.h7+c<<0};et.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=$[t>>>28&15]+$[t>>>24&15]+$[t>>>20&15]+$[t>>>16&15]+$[t>>>12&15]+$[t>>>8&15]+$[t>>>4&15]+$[t&15]+$[e>>>28&15]+$[e>>>24&15]+$[e>>>20&15]+$[e>>>16&15]+$[e>>>12&15]+$[e>>>8&15]+$[e>>>4&15]+$[e&15]+$[r>>>28&15]+$[r>>>24&15]+$[r>>>20&15]+$[r>>>16&15]+$[r>>>12&15]+$[r>>>8&15]+$[r>>>4&15]+$[r&15]+$[n>>>28&15]+$[n>>>24&15]+$[n>>>20&15]+$[n>>>16&15]+$[n>>>12&15]+$[n>>>8&15]+$[n>>>4&15]+$[n&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[a>>>28&15]+$[a>>>24&15]+$[a>>>20&15]+$[a>>>16&15]+$[a>>>12&15]+$[a>>>8&15]+$[a>>>4&15]+$[a&15];return this.is224||(l+=$[c>>>28&15]+$[c>>>24&15]+$[c>>>20&15]+$[c>>>16&15]+$[c>>>12&15]+$[c>>>8&15]+$[c>>>4&15]+$[c&15]),l};et.prototype.toString=et.prototype.hex;et.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};et.prototype.array=et.prototype.digest;et.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var yh=_e(cn(),1);var Xo=/^(?:[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 fr(t){return typeof t=="string"&&Xo.test(t)}o(fr,"validate");function pr(t){if(!fr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}o(pr,"parse");var be=[];for(let t=0;t<256;++t)be.push((t+256).toString(16).slice(1));function Et(t,e=0){return(be[t[e+0]]+be[t[e+1]]+be[t[e+2]]+be[t[e+3]]+"-"+be[t[e+4]]+be[t[e+5]]+"-"+be[t[e+6]]+be[t[e+7]]+"-"+be[t[e+8]]+be[t[e+9]]+"-"+be[t[e+10]]+be[t[e+11]]+be[t[e+12]]+be[t[e+13]]+be[t[e+14]]+be[t[e+15]]).toLowerCase()}o(Et,"unsafeStringify");var _h=new Uint8Array(16);function mr(){return crypto.getRandomValues(_h)}o(mr,"rng");function bh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}o(bh,"f");function Us(t,e){return t<<e|t>>>32-e}o(Us,"ROTL");function Qo(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let c=0;c<i;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];a[c]=l}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<i;++c){let l=new Uint32Array(80);for(let y=0;y<16;++y)l[y]=a[c][y];for(let y=16;y<80;++y)l[y]=Us(l[y-3]^l[y-8]^l[y-14]^l[y-16],1);let u=r[0],d=r[1],f=r[2],_=r[3],g=r[4];for(let y=0;y<80;++y){let E=Math.floor(y/20),w=Us(u,5)+bh(E,d,f,_)+g+e[E]+l[y]>>>0;g=_,_=f,f=Us(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+f>>>0,r[3]=r[3]+_>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}o(Qo,"sha1");function Eh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}o(Eh,"stringToBytes");var ec="6ba7b810-9dad-11d1-80b4-00c04fd430c8",tc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function rc(t,e,r,n,s,i){let a=typeof r=="string"?Eh(r):r,c=typeof n=="string"?pr(n):n;if(typeof n=="string"&&(n=pr(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+a.length);if(l.set(c),l.set(a,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,s){if(i??=0,i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=l[u];return s}return Et(l)}o(rc,"v35");function Fs(t,e,r,n){return rc(80,Qo,t,e,r,n)}o(Fs,"v5");Fs.DNS=ec;Fs.URL=tc;var Bs={};function sc(t,e,r){let n;if(t)n=nc(t.random??t.rng?.()??mr(),t.msecs,t.seq,e,r);else{let s=Date.now(),i=mr();Th(Bs,s,i),n=nc(i,Bs.msecs,Bs.seq,e,r)}return e??Et(n)}o(sc,"v7");function Th(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}o(Th,"updateV7State");function nc(t,e,r,n,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),s=0;else if(s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[s++]=e/1099511627776&255,n[s++]=e/4294967296&255,n[s++]=e/16777216&255,n[s++]=e/65536&255,n[s++]=e/256&255,n[s++]=e&255,n[s++]=112|r>>>28&15,n[s++]=r>>>20&255,n[s++]=128|r>>>14&63,n[s++]=r>>>6&255,n[s++]=r<<2&255|t[10]&3,n[s++]=t[11],n[s++]=t[12],n[s++]=t[13],n[s++]=t[14],n[s++]=t[15],n}o(nc,"v7Bytes");var tt=sc;var ic=Symbol.for("ls:tracing_async_local_storage"),Mt=Symbol.for("lc:context_variables"),ac=o(t=>{globalThis[ic]=t},"setGlobalAsyncLocalStorageInstance"),wt=o(()=>globalThis[ic],"getGlobalAsyncLocalStorageInstance");var vh=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Sh=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Ih=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Hs=o(()=>typeof Deno<"u","isDeno"),xh=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hs(),"isNode"),Ah=o(()=>{let t;return vh()?t="browser":xh()?t="node":Sh()?t="webworker":Ih()?t="jsdom":Hs()?t="deno":t="other",t},"getEnv"),js;function oc(){return js===void 0&&(js={library:"langchain-js",runtime:Ah()}),js}o(oc,"getRuntimeEnvironment");function Je(t){try{return typeof process<"u"?process.env?.[t]:Hs()?Deno?.env.get(t):void 0}catch{return}}o(Je,"getEnvironmentVariable");var Ch=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var qt=class extends Ch{static{o(this,"BaseCallbackHandler")}lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Is(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Ot.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ot.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends qt{static{o(this,"Handler")}name=tt();constructor(){super(),Object.assign(this,t)}}return new e}},cc=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var lc=/^(?:[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 Rh(t){return typeof t=="string"&&lc.test(t)}o(Rh,"validate");var uc=Rh;function Oh(t){if(!uc(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}o(Oh,"parse");var dc=Oh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function Wt(t,e=0){return(Ee[t[e+0]]+Ee[t[e+1]]+Ee[t[e+2]]+Ee[t[e+3]]+"-"+Ee[t[e+4]]+Ee[t[e+5]]+"-"+Ee[t[e+6]]+Ee[t[e+7]]+"-"+Ee[t[e+8]]+Ee[t[e+9]]+"-"+Ee[t[e+10]]+Ee[t[e+11]]+Ee[t[e+12]]+Ee[t[e+13]]+Ee[t[e+14]]+Ee[t[e+15]]).toLowerCase()}o(Wt,"unsafeStringify");var fc=_e(require("node:crypto"));var un=new Uint8Array(256),ln=un.length;function hr(){return ln>un.length-16&&(fc.default.randomFillSync(un),ln=0),un.slice(ln,ln+=16)}o(hr,"rng");function Nh(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(Nh,"stringToBytes");var Mh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",kh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Gs(t,e,r){function n(s,i,a,c){var l;if(typeof s=="string"&&(s=Nh(s)),typeof i=="string"&&(i=dc(i)),((l=i)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+s.length);if(u.set(i),u.set(s,i.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=u[d];return a}return Wt(u)}o(n,"generateUUID");try{n.name=t}catch{}return n.DNS=Mh,n.URL=kh,n}o(Gs,"v35");var pc=_e(require("node:crypto")),zs={randomUUID:pc.default.randomUUID};function Ph(t,e,r){if(zs.randomUUID&&!e&&!t)return zs.randomUUID();t=t||{};let n=t.random||(t.rng||hr)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Wt(n)}o(Ph,"v4");var kt=Ph;var mc=_e(require("node:crypto"));function Lh(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),mc.default.createHash("sha1").update(t).digest()}o(Lh,"sha1");var hc=Lh;var Dh=Gs("v5",80,hc),Vs=Dh;var gc=null,yc=null,Ye=0;function $h(t,e,r){t=t||{};let n=e&&r||0,s=e||new Uint8Array(16),i=t.random||(t.rng||hr)(),a=t.msecs!==void 0?t.msecs:Date.now(),c=t.seq!==void 0?t.seq:null,l=yc,u=gc;return a>Ye&&t.msecs===void 0&&(Ye=a,c!==null&&(l=null,u=null)),c!==null&&(c>2147483647&&(c=2147483647),l=c>>>19&4095,u=c&524287),(l===null||u===null)&&(l=i[6]&127,l=l<<8|i[7],u=i[8]&63,u=u<<8|i[9],u=u<<5|i[10]>>>3),a+1e4>Ye&&c===null?++u>524287&&(u=0,++l>4095&&(l=0,Ye++)):Ye=a,yc=l,gc=u,s[n++]=Ye/1099511627776&255,s[n++]=Ye/4294967296&255,s[n++]=Ye/16777216&255,s[n++]=Ye/65536&255,s[n++]=Ye/256&255,s[n++]=Ye&255,s[n++]=l>>>4&15|112,s[n++]=l&255,s[n++]=u>>>13&63|128,s[n++]=u>>>5&255,s[n++]=u<<3&255|i[10]&7,s[n++]=i[11],s[n++]=i[12],s[n++]=i[13],s[n++]=i[14],s[n++]=i[15],e||Wt(s)}o($h,"v7");var gr=$h;var _c="gen_ai.operation.name",bc="gen_ai.system",qs="gen_ai.request.model",Ec="gen_ai.response.model",Ws="gen_ai.usage.input_tokens",Ks="gen_ai.usage.output_tokens",Zs="gen_ai.usage.total_tokens",wc="gen_ai.request.max_tokens",Tc="gen_ai.request.temperature",vc="gen_ai.request.top_p",Sc="gen_ai.request.frequency_penalty",Ic="gen_ai.request.presence_penalty",xc="gen_ai.response.finish_reasons",Ac="gen_ai.prompt",Cc="gen_ai.completion",Rc="gen_ai.request.extra_query",Oc="gen_ai.request.extra_body",Nc="gen_ai.serialized.name",Mc="gen_ai.serialized.signature",kc="gen_ai.serialized.doc",Pc="gen_ai.response.id",Lc="gen_ai.response.service_tier",Dc="gen_ai.response.system_fingerprint",$c="gen_ai.usage.input_token_details",Uc="gen_ai.usage.output_token_details",Fc="langsmith.trace.session_id",Bc="langsmith.trace.session_name",jc="langsmith.span.kind",Hc="langsmith.trace.name",Gc="langsmith.metadata",Js="langsmith.span.tags";var zc="langsmith.request.streaming",Vc="langsmith.request.headers";var Bh=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),jh,qc=Symbol.for("ls:fetch_implementation");var Wc=o(()=>globalThis[qc]===void 0?!0:jh??!1,"_shouldStreamForGlobalFetchImplementation"),Kc=o(t=>async(...e)=>{if(t||te("DEBUG")==="true"){let[n,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${n}`)}let r=await(globalThis[qc]??Bh)(...e);return(t||te("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var yr=o(()=>te("PROJECT")??Be("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var Zc={};function Pt(t){Zc[t]||(console.warn(t),Zc[t]=!0)}o(Pt,"warnOnce");var R=o(t=>BigInt(t),"n"),Qc=R("0x9E3779B1"),el=R("0x85EBCA77"),Hh=R("0xC2B2AE3D"),Tt=R("0x9E3779B185EBCA87"),Lt=R("0xC2B2AE3D27D4EB4F"),tl=R("0x165667B19E3779F9"),ei=R("0x85EBCA77C2B2AE63"),Gh=R("0x27D4EB2F165667C5"),zh=R("0x165667919E3779F9"),Vh=R("0x9FB21C651E98DF25");function qh(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}o(qh,"hexToBytes");var rt=qh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Zt=(R(1)<<R(128))-R(1),q=(R(1)<<R(64))-R(1),mn=(R(1)<<R(32))-R(1),dt=64,rl=dt/8,Wh=8,dn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}o(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}o(Q,"readBigUInt64LE");function Kt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}o(Kt,"readUInt32LE");function Ys(t,e=0){return t[e]}o(Ys,"readUInt8");var Kh=o(t=>(t&R(255))<<R(56)|(t&R(65280))<<R(40)|(t&R(16711680))<<R(24)|(t&R(4278190080))<<R(8)|(t&R(0xff00000000))>>R(8)|(t&R(0xff0000000000))>>R(24)|(t&R(0xff000000000000))>>R(40)|(t&R(0xff00000000000000))>>R(56),"bswap64"),Zh=o(t=>(t=(t&R(65535))<<R(16)|(t&R(4294901760))>>R(16),t=(t&R(16711935))<<R(8)|(t&R(4278255360))>>R(8),t),"bswap32"),Jh=o((t,e)=>(t&mn)*(e&mn)&q,"XXH_mult32to64"),Jt=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function Yh(t,e){return(t<<e|t>>R(32)-e)&mn}o(Yh,"rotl32");function nl(t,e,r){for(let n=0;n<rl;n++){let s=Q(e,n*8),i=s^Q(r,n*8);t[n^1]+=s,t[n]+=Jh(i,i>>R(32))}return t}o(nl,"XXH3_accumulate_512");function Jc(t,e,r,n){for(let s=0;s<n;s++)nl(t,Y(e,s*dt),Y(r,s*8));return t}o(Jc,"XXH3_accumulate");function Xh(t,e){for(let r=0;r<rl;r++){let n=Q(e,r*8),s=t[r];s=Xs(s,R(47)),s^=n,s*=Qc,t[r]=s&q}return t}o(Xh,"XXH3_scrambleAcc");function fn(t,e){return sl(t[0]^Q(e,0),t[1]^Q(e,Wh))}o(fn,"XXH3_mix2Accs");function Yc(t,e,r){let n=r;return n+=fn(t.slice(0),Y(e,0*dn)),n+=fn(t.slice(2),Y(e,4*dn)),n+=fn(t.slice(4),Y(e,8*dn)),n+=fn(t.slice(6),Y(e,12*dn)),nt(n&q)}o(Yc,"XXH3_mergeAccs");function Qh(t,e,r,n,s){let i=Math.floor((r.byteLength-dt)/8),a=dt*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l++)t=Jc(t,Y(e,l*a),r,i),t=s(t,Y(r,r.byteLength-dt));{let l=Math.floor((e.byteLength-1-a*c)/dt);t=Jc(t,Y(e,c*a),r,l),t=n(t,Y(e,e.byteLength-dt),Y(r,r.byteLength-dt-7))}return t}o(Qh,"XXH3_hashLong");function eg(t,e,r){let n=new BigUint64Array([Hh,Tt,Lt,tl,ei,el,Gh,Qc]);Jt(t.length>128),n=Qh(n,t,e,nl,Xh),Jt(n.length*8==64);{let s=Yc(n,Y(e,11),R(t.byteLength)*Tt&q);return Yc(n,Y(e,e.byteLength-dt-11),~(R(t.byteLength)*Lt)&q)<<R(64)|s}}o(eg,"XXH3_hashLong_128b");function sl(t,e){let r=t*e&Zt;return r&q^r>>R(64)}o(sl,"XXH3_mul128_fold64");function Xc(t,e,r){return sl((Q(t,0)^Q(e,0)+r)&q,(Q(t,8)^Q(e,8)-r)&q)}o(Xc,"XXH3_mix16B");function pn(t,e,r,n,s){let i=t&q,a=t>>R(64)&q;return i+=Xc(e,n,s),i^=Q(r,0)+Q(r,8),i&=q,a+=Xc(r,Y(n,16),s),a^=Q(e,0)+Q(e,8),a&=q,a<<R(64)|i}o(pn,"XXH3_mix32B");function nt(t){return t^=t>>R(37),t*=zh,t&=q,t^=t>>R(32),t}o(nt,"XXH3_avalanche");function hn(t){return t^=t>>R(33),t*=Lt,t&=q,t^=t>>R(29),t*=tl,t&=q,t^=t>>R(32),t}o(hn,"XXH3_avalanche64");function tg(t,e,r){let n=t.byteLength;Jt(n>0&&n<=3);let s=R(Ys(t,n-1))|R(n<<8)|R(Ys(t,0)<<16)|R(Ys(t,n>>1)<<24),i=(R(Kt(e,0))^R(Kt(e,4)))+r,a=(s^i)&q,c=(R(Kt(e,8))^R(Kt(e,12)))-r,l=(Yh(Zh(s),R(13))^c)&q;return(hn(l)&q)<<R(64)|hn(a)}o(tg,"XXH3_len_1to3_128b");function Xs(t,e){return t^t>>e}o(Xs,"xorshift64");function rg(t,e,r){let n=t.byteLength;Jt(n>=4&&n<=8);{let s=Kt(t,0),i=Kt(t,n-4),a=R(s)|R(i)<<R(32),c=(Q(e,16)^Q(e,24))+r&q,u=(a^c)*(Tt+(R(n)<<R(2)))&Zt;return u+=(u&q)<<R(65),u&=Zt,u^=u>>R(67),Xs(Xs(u&q,R(35))*Vh&q,R(28))|nt(u>>R(64))<<R(64)}}o(rg,"XXH3_len_4to8_128b");function ng(t,e,r){let n=t.byteLength;Jt(n>=9&&n<=16);{let s=(Q(e,32)^Q(e,40))+r&q,i=(Q(e,48)^Q(e,56))-r&q,a=Q(t),c=Q(t,n-8),l=(a^c^s)*Tt,u=(l&q)+(R(n-1)<<R(54));l=l&(Zt^q)|u,c^=i,l+=c+(c&mn)*(el-R(1))<<R(64),l&=Zt,l^=Kh(l>>R(64));let d=(l&q)*Lt;return d+=(l>>R(64))*Lt<<R(64),d&=Zt,nt(d&q)|nt(d>>R(64))<<R(64)}}o(ng,"XXH3_len_9to16_128b");function sg(t,e){let r=t.byteLength;return Jt(r<=16),r>8?ng(t,rt,e):r>=4?rg(t,rt,e):r>0?tg(t,rt,e):hn(e^Q(rt,64)^Q(rt,72))|hn(e^Q(rt,80)^Q(rt,88))<<R(64)}o(sg,"XXH3_len_0to16_128b");function Qs(t){return~t+R(1)&q}o(Qs,"inv64");function ig(t,e,r){let n=R(t.byteLength)*Tt&q,s=R(t.byteLength-1)/R(32);for(;s>=0;){let c=Number(s);n=pn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),s--}let i=n+(n>>R(64))&q;i=nt(i);let a=(n&q)*Tt+(n>>R(64))*ei+(R(t.byteLength)-r&q)*Lt;return a&=q,a=Qs(nt(a)),i|a<<R(64)}o(ig,"XXH3_len_17to128_128b");function ag(t,e,r){let n=R(t.byteLength)*Tt&q;for(let a=32;a<160;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,a-32),r);n=nt(n&q)|nt(n>>R(64))<<R(64);for(let a=160;a<=t.byteLength;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,3+a-160),r);n=pn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),Qs(r));let s=n+(n>>R(64))&q;s=nt(s);let i=(n&q)*Tt+(n>>R(64))*ei+(R(t.byteLength)-r&q)*Lt;return i&=q,i=Qs(nt(i)),s|i<<R(64)}o(ag,"XXH3_len_129to240_128b");function il(t,e=R(0)){let r=t.byteLength;return r<=16?sg(t,e):r<=128?ig(t,rt,e):r<=240?ag(t,rt,e):eg(t,rt,e)}o(il,"XXH3_128");function al(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&q,s=t>>R(64);return r.setBigUint64(0,s,!1),r.setBigUint64(8,n,!1),e}o(al,"xxh128ToBytes");var ol=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z(t,e){if(!ol.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o(z,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return gr({msecs:e,seq:0})}o(gn,"uuid7FromTime");function og(t){if(!ol.test(t))return null;let e=t[14];return parseInt(e,16)}o(og,"getUuidVersion");function cg(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}o(cg,"uuidToBytes");function lg(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}o(lg,"bytesToUuid");var ug=new TextEncoder;function dg(t){let e=ug.encode(t),r=il(e);return al(r)}o(dg,"_fastHash128");function _r(t,e){let r=`${t}:${e}`,n=dg(r),s=new Uint8Array(16);if(og(t)===7){let a=cg(t);s.set(a.slice(0,6),0)}else{let a=Date.now();s[0]=a/1099511627776&255,s[1]=a/4294967296&255,s[2]=a/16777216&255,s[3]=a/65536&255,s[4]=a/256&255,s[5]=a&255}return s[6]=112|n[0]&15,s[7]=n[1],s[8]=128|n[2]&63,s.set(n.slice(3,10),9),lg(s)}o(_r,"nonCryptographicUuid7Deterministic");var He=_e(require("node:fs"),1),Xe=_e(require("node:fs/promises"),1),fg=_e(require("node:path"),1);var br=fg;async function cl(t){await Xe.mkdir(t,{recursive:!0})}o(cl,"mkdir");async function ll(t,e){let r=`${t}.tmp`;await Xe.writeFile(r,e,{encoding:"utf8",mode:384}),await Xe.rename(r,t)}o(ll,"writeFileAtomic");async function ul(t){return Xe.readdir(t)}o(ul,"readdir");async function dl(t){return Xe.stat(t)}o(dl,"stat");function yn(t){return He.existsSync(t)}o(yn,"existsSync");function fl(t){He.mkdirSync(t,{recursive:!0})}o(fl,"mkdirSync");function pl(t,e){He.writeFileSync(t,e)}o(pl,"writeFileSync");function ml(t,e){He.renameSync(t,e)}o(ml,"renameSync");function hl(t){He.unlinkSync(t)}o(hl,"unlinkSync");function gl(t){return He.readFileSync(t,"utf-8")}o(gl,"readFileSync");function mg(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(mg,"isStale");var _n=class{static{o(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let s={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[i,a]of this.cache.entries())r[i]=a.value;let n=br.dirname(e);yn(n)||fl(n);let s=`${e}.tmp`;try{pl(s,JSON.stringify({entries:r},null,2)),ml(s,e)}catch(i){throw yn(s)&&hl(s),i}}load(e){if(!yn(e))return 0;let r;try{let i=gl(e);r=JSON.parse(i).entries??null}catch{return 0}if(!r)return 0;let n=0,s=Date.now();for(let[i,a]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:a,createdAt:s};this.cache.set(i,c),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())mg(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let s=await n.refreshFunc();this.set(r,s,n.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},bn=new _n;var En="0.5.16";var st,hg=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),gg=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),yg=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),yl=o(()=>typeof Deno<"u","isDeno"),_g=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!yl(),"isNode"),ni=o(()=>st||(typeof Bun<"u"?st="bun":hg()?st="browser":_g()?st="node":gg()?st="webworker":yg()?st="jsdom":yl()?st="deno":st="other",st),"getEnv"),ti;function wn(){if(ti===void 0){let t=ni(),e=Eg();ti={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:En,...e}}return ti}o(wn,"getRuntimeEnvironment");function si(){let t=bg(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,s]of Object.entries(t))typeof s=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}o(si,"getLangSmithEnvVarsMetadata");function bg(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}o(bg,"getLangSmithEnvironmentVariables");function Be(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}o(Be,"getEnvironmentVariable");function te(t){return Be(`LANGSMITH_${t}`)||Be(`LANGCHAIN_${t}`)}o(te,"getLangSmithEnvironmentVariable");var ri;function Eg(){if(ri!==void 0)return ri;let t=["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"],e={};for(let r of t){let n=Be(r);n!==void 0&&(e[r]=n)}return ri=e,e}o(Eg,"getShas");function Tn(){return Be("OTEL_ENABLED")==="true"||te("OTEL_ENABLED")==="true"}o(Tn,"getOtelEnabled");var oi=class{static{o(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Tn()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},ci=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new oi})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},li=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ii=Symbol.for("ls:otel_trace"),ai=Symbol.for("ls:otel_context"),_l=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),wg=new ci,Tg=new li,ui=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[ii]??wg}getContextInstance(){return globalThis[ai]??Tg}initializeGlobalInstances(e){globalThis[ii]===void 0&&(globalThis[ii]=e.trace),globalThis[ai]===void 0&&(globalThis[ai]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[_l]=e}getDefaultOTLPTracerComponents(){return globalThis[_l]??void 0}},di=new ui;function vn(){return di.getTraceInstance()}o(vn,"getOTELTrace");function bl(){return di.getContextInstance()}o(bl,"getOTELContext");function El(){return di.getDefaultOTLPTracerComponents()}o(El,"getDefaultOTLPTracerComponents");var vg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Sg(t){return vg[t]||t}o(Sg,"getOperationName");var Sn=class{static{o(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let s=this.createSpanForRun(n,n.run,r.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,r,n){let s=n&&vn().getSpan(n);if(s)try{return this.finishSpanSetup(s,r,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let s=r.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(jc,r.run_type);let c=Sg(r.run_type||"chain");e.setAttribute(_c,c)}"name"in r&&r.name&&e.setAttribute(Hc,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Fc,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Bc,r.session_name),this.setGenAiSystem(e,r);let s=this.extractModelName(r);s&&e.setAttribute(qs,s),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ws,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Ks,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Zs,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[c,l]of Object.entries(i))l!=null&&e.setAttribute(`${Gc}.${c}`,String(l));let a=r.tags;if(a&&Array.isArray(a)?e.setAttribute(Js,a.join(", ")):a&&e.setAttribute(Js,String(a)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(Nc,String(c.name)),c.signature&&e.setAttribute(Mc,String(c.signature)),c.doc&&e.setAttribute(kc,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",s=this.extractModelName(r);if(s){let i=s.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?n="anthropic":i.includes("bedrock")?n="aws.bedrock":i.includes("azure")&&i.includes("openai")?n="az.ai.openai":i.includes("azure")&&i.includes("inference")?n="az.ai.inference":i.includes("cohere")?n="cohere":i.includes("deepseek")?n="deepseek":i.includes("gemini")?n="gemini":i.includes("groq")?n="groq":i.includes("watson")||i.includes("ibm")?n="ibm.watsonx.ai":i.includes("mistral")?n="mistral_ai":i.includes("gpt")||i.includes("openai")?n="openai":i.includes("perplexity")||i.includes("sonar")?n="perplexity":i.includes("vertex")?n="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(n="xai")}e.setAttribute(bc,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(wc,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Tc,n.temperature),n.top_p!==void 0&&e.setAttribute(vc,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Sc,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Ic,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(qs,n.model),n.stream!==void 0&&e.setAttribute(zc,n.stream),n.extra_headers&&e.setAttribute(Vc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Rc,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Oc,JSON.stringify(n.extra_body))),e.setAttribute(Ac,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(Ws,s[0]),e.setAttribute(Ks,s[1]),e.setAttribute(Zs,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Ec,String(n.model)),n.id&&e.setAttribute(Pc,n.id),n.choices&&Array.isArray(n.choices)){let i=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);i.length>0&&e.setAttribute(xc,i.join(", "))}if(n.service_tier&&e.setAttribute(Lc,n.service_tier),n.system_fingerprint&&e.setAttribute(Dc,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute($c,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(Uc,JSON.stringify(i.output_token_details))}}e.setAttribute(Cc,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let a of n){let c=e[a];if(!(!c||typeof c!="object")&&(r=this.extractUnifiedRunTokens(c.usage_metadata),r||c.lc===1&&c.kwargs&&typeof c.kwargs=="object"&&(r=this.extractUnifiedRunTokens(c.kwargs.usage_metadata),r)))return r}let s=e.generations||[];if(!Array.isArray(s))return null;let i=Array.isArray(s[0])?s.flat():s;for(let a of i)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var Ig=Object.prototype.toString,xg=o(t=>Ig.call(t)==="[object Error]","isError"),Ag=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function fi(t){if(!(t&&xg(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:Ag.has(r)}o(fi,"isNetworkError");function Cg(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}o(Cg,"validateRetries");function In(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}o(In,"validateNumberOption");var pi=class extends Error{static{o(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Rg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(r-1));return s=Math.min(s,e.maxTimeout),s}o(Rg,"calculateDelay");function wl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(wl,"calculateRemainingTime");async function Og({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:s}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof pi)throw i.originalError;let a=Number.isFinite(s.retries)?Math.max(0,s.retries-r):s.retries,c=s.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:r});if(await s.onFailedAttempt(l),wl(n,c)<=0)throw i;let u=await s.shouldConsumeRetry(l),d=wl(n,c);if(d<=0||a<=0)throw i;if(i instanceof TypeError&&!fi(i)){if(u)throw i;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(l))throw i;if(!u)return s.signal?.throwIfAborted(),!1;let f=Rg(r,s),_=Math.min(f,d);return _>0&&await new Promise((g,y)=>{let E=o(()=>{clearTimeout(w),s.signal?.removeEventListener("abort",E),y(s.signal.reason)},"onAbort"),w=setTimeout(()=>{s.signal?.removeEventListener("abort",E),g()},_);s.unref&&w.unref?.(),s.signal?.addEventListener("abort",E,{once:!0})}),s.signal?.throwIfAborted(),!0}o(Og,"onAttemptFailure");async function mi(t,e={}){if(e={...e},Cg(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,In("factor",e.factor,{min:0,allowInfinity:!1}),In("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),In("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),In("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let i=await t(r);return e.signal?.throwIfAborted(),i}catch(i){await Og({error:i,attemptNumber:r,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(mi,"pRetry");var xn=_e(cn(),1),Tl="default"in xn.default?xn.default.default:xn.default;var Ng=[408,425,429,500,502,503,504],Er=class{static{o(this,"AsyncCaller")}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,"maxQueueSizeBytes",{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}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Tl({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);let i=this.onFailedResponseHook,a=this.queue.add(()=>mi(()=>r(...n).catch(c=>{throw c instanceof Error?c:new Error(c)}),{async onFailedAttempt({error:c}){if(typeof c!="object"||c==null)throw c;let l="message"in c&&typeof c.message=="string"?c.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in c&&c.name==="TimeoutError"||"code"in c&&c.code==="ECONNABORTED")throw c;let u="response"in c?c.response:void 0;if(i&&await i(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!Ng.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(a=a.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([a,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):a}};function hi(t){return typeof t?._getType=="function"}o(hi,"isLangChainMessage");function gi(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}o(gi,"convertLangChainMessageToExample");var Ab=_e(dd(),1);function Bn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
10
+ - "prompt-name" (for private prompts)
11
+ - "owner/prompt-name" (for prompts with explicit owner)
12
+ - "prompt-name:commit-hash" (with commit reference)
13
+ - "owner/prompt-name:commit-hash" (with owner and commit)`}o(Bn,"getInvalidPromptIdentifierMsg");var Di=class extends Error{static{o(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},$i=class extends Error{static{o(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Ui(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Ui,"isLangSmithNotFoundError");async function U(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let c=new Error(`${t.status} ${t.statusText}`);throw c.status=t?.status,c}if(n===void 0)try{n=await t.text()}catch{n=""}let s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new $i(s);if(t.status===409)throw new Di(s);let i=new Error(s);throw i.status=t.status,i}o(U,"raiseForStatus");var fd="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{o(this,"ConflictingEndpointsError")}constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:fd}),this.name="ConflictingEndpointsError"}};function pd(t){return typeof t=="object"&&t!==null&&t.code===fd}o(pd,"isConflictingEndpointsError");function at(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Bn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[s,i]=e.split("/",2);if(!s||!i)throw new Error(Bn(t));return[s,i,n]}else{if(!e)throw new Error(Bn(t));return["-",e,n]}}o(at,"parsePromptIdentifier");var md="[...]",Cb={result:"[Circular]"},Hn=[],Xt=[],Rb=new TextEncoder;function Ob(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}o(Ob,"defaultOptions");function jn(t){return Rb.encode(t)}o(jn,"encodeString");function hd(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}o(hd,"serializeWellKnownTypes");function Nb(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return hd(r)}}o(Nb,"createDefaultReplacer");function Pe(t,e,r,n,s){try{let i=JSON.stringify(t,Nb(r),n);return jn(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
14
+ Context: ${e}`:""}`),jn("[Unserializable]");te("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
15
+ Context: ${e}`:""}`),typeof s>"u"&&(s=Ob()),Bi(t,"",0,[],void 0,0,s);let a;try{Xt.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Mb(r),n)}catch{return jn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Hn.length!==0;){let c=Hn.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return jn(a)}}o(Pe,"serialize");function Fi(t,e,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:t}),Hn.push([n,r,e,s])):Xt.push([e,r,t]):(n[r]=t,Hn.push([n,r,e]))}o(Fi,"setReplace");function Bi(t,e,r,n,s,i,a){i+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Fi(Cb,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Fi(md,t,e,s);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Fi(md,t,e,s);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)Bi(t[c],c,c,n,t,i,a);else{t=hd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];Bi(t[u],u,c,n,t,i,a)}}n.pop()}}o(Bi,"decirc");function Mb(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Xt.length>0)for(var n=0;n<Xt.length;n++){var s=Xt[n];if(s[1]===e&&s[0]===r){r=s[2],Xt.splice(n,1);break}}return t.call(this,e,r)}}o(Mb,"replaceGetterValues");function gd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(gd,"_ensureUTCTimestamp");function Cr(t){return{...t,start_time:gd(t.start_time),end_time:gd(t.end_time)}}o(Cr,"_normalizeRunTimestamps");function yd(t,e,r){if(r)return t;let n=wn(),s=e??si(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...a}},t}o(yd,"mergeRuntimeEnvIntoRun");var kb=o(t=>{let e=t?.toString()??te("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),Pb=o(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Lb(t){let e=[];for await(let r of t)e.push(r);return e}o(Lb,"toArray");function Gn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(Gn,"trimQuotes");var Db=o(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function _d(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(_d,"_formatFeedbackScore");var $b=24*1024*1024,wd=1024*1024*1024,Ub=1e4,Fb=100,bd="https://api.smith.langchain.com",ji=class{static{o(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??wd}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),s=Pe(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:s}),this.sizeBytes+=s,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),s+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),s+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},vt=class t{static{o(this,"Client")}get _fetch(){return this.fetchImplementation||Kc(this.debug)}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,"workspaceId",{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,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:te("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();if(this.tracingSampleRate=kb(e.tracingSamplingRate),this.apiUrl=Gn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Gn(e.apiKey??r.apiKey),this.webUrl=Gn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Gn(e.workspaceId??te("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Er({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=te("FAILED_TRACES_DIR")||void 0;let n=te("FAILED_TRACES_MAX_MB");if(n){let i=parseInt(n,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}let s=e.maxIngestMemoryBytes??wd;this.batchIngestCaller=new Er({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Db,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new ji(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Tn()&&(this.langSmithToOTELTranslator=new Sn),this.cachedLSEnvVarsForMetadata=si(),e.cache!==void 0&&e.disablePromptCache&&Pt("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Pt("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=bn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=bn)}static getDefaultClientConfig(){let e=te("API_KEY"),r=te("ENDPOINT")??bd,n=te("HIDE_INPUTS")==="true",s=te("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:Pb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),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.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${En}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){let n=r?.toString()??"",s=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,`fetch ${e}`),a})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let s=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(s)),r.set("limit",String(i));let a=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<i))break;s+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",s="runs"){let i=r?{...r}:{};for(;;){let a=JSON.stringify(i),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(d,`fetch ${e}`),d})).json();if(!l||!l[s])break;yield l[s];let u=l.cursors;if(!u||!u.next)break;i.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{let n=[];for(let s of e){let i=s.trace_id??s.id;this.filteredPostUuids.has(i)||(s.id===i?this._shouldSample()?n.push(s):this.filteredPostUuids.add(i):n.push(s))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??$b}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Fb}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!s.length){i();break}let a=s.reduce((u,d)=>{let f=d.apiUrl??this.apiUrl,_=d.apiKey??this.apiKey,y=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl?"default":`${f}|${_}`;return u[y]||(u[y]=[]),u[y].push(d),u},{}),c=[];for(let[u,d]of Object.entries(a)){let f=this._processBatch(d,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});c.push(f)}let l=Promise.all(c).finally(i);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,s,i){try{let a=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:s,headers:n,body_base64:a.toString("base64")}),l=`trace_${Date.now()}_${kt().slice(0,8)}.json`,u=br.join(e,l);if(t._fallbackDirsCreated.has(e)||(await cl(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let f=(await ul(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),_=0;for(let g of f){let{size:y}=await dl(br.join(e,g));_+=y}if(_>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${_} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ll(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((s,i)=>s+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let s={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(s,{...r,useGzip:c,sizeBytes:n})}catch(l){if(Ui(l))this._multipartDisabled=!0,await this.batchIngestRuns(s,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(s,{...r,sizeBytes:n})}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let s of e)s.item.id&&s.otelContext&&(r.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=yd(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Ub),...this.fetchOptions});return await U(n,"get server info"),n})).json();return this.debug&&console.log(`
16
+ === LangSmith Server Configuration ===
17
+ `+JSON.stringify(r,null,2)+`
18
+ `),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=vn(),r=bl();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=yd(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let c=Pe(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(s.length>0&&i.length>0){let l=s.reduce((d,f)=>(f.id&&(d[f.id]=f),d),{}),u=[];for(let d of i)d.id!==void 0&&l[d.id]?l[d.id]={...l[d.id],...d}:u.push(d);s=Object.values(l),i=u}let a={post:s,patch:i};if(!a.post.length&&!a.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=a[u].reverse(),f=d.pop();for(;f!==void 0;)c[u].push(f),f=d.pop()}if(c.post.length>0||c.patch.length>0){let l=c.post.map(u=>u.id).concat(c.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Pe(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await U(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s={},i=[];for(let f of e??[]){let _=await this.prepareRunCreateOrUpdateInputs(f);_.id!==void 0&&_.attachments!==void 0&&(s[_.id]=_.attachments),delete _.attachments,i.push(_)}let a=[];for(let f of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(f));if(i.find(f=>f.trace_id===void 0||f.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(f=>f.trace_id===void 0||f.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let f=i.reduce((g,y)=>(y.id&&(g[y.id]=y),g),{}),_=[];for(let g of a)g.id!==void 0&&f[g.id]?f[g.id]={...f[g.id],...g}:_.push(g);i=Object.values(f),a=_}if(i.length===0&&a.length===0)return;let u=[],d=[];for(let[f,_]of[["post",i],["patch",a]])for(let g of _){let{inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m,attachments:T,...A}=g,N={inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m},O=Pe(A,`Serializing for multipart ingestion of run with id: ${A.id}`);d.push({name:`${f}.${A.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(let[b,j]of Object.entries(N)){if(j===void 0)continue;let G=Pe(j,`Serializing ${b} for multipart ingestion of run with id: ${A.id}`);d.push({name:`${f}.${A.id}.${b}`,payload:new Blob([G],{type:`application/json; length=${G.length}`})})}if(A.id!==void 0){let b=s[A.id];if(b){delete s[A.id];for(let[j,G]of Object.entries(b)){let B,Z;if(Array.isArray(G)?[B,Z]=G:(B=G.mimeType,Z=G.data),j.includes(".")){console.warn(`Skipping attachment '${j}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${A.id}.${j}`,payload:new Blob([Z],{type:`${B}; length=${Z.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let a of e)n.push(new Blob([`--${r}\r
19
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
20
+ `,`Content-Type: ${a.payload.type}\r
21
+ \r
22
+ `])),n.push(a.payload),n.push(new Blob([`\r
23
+ `]));return n.push(new Blob([`--${r}--\r
24
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=o(async c=>{typeof c=="string"?i.enqueue(n.encode(c)):i.enqueue(c)},"writeChunk");for(let c of e){await a(`--${r}\r
25
+ `),await a(`Content-Disposition: form-data; name="${c.name}"\r
26
+ `),await a(`Content-Type: ${c.payload.type}\r
27
+ \r
28
+ `);let u=c.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)i.enqueue(d.value)}finally{u.releaseLock()}await a(`\r
29
+ `)}await a(`--${r}--\r
30
+ `),i.close()}})}async _sendMultipartRequest(e,r,n){let s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=o(()=>this._createNodeFetchBody(e,s),"buildBuffered"),a=o(()=>this._createMultipartStream(e,s),"buildStream"),c=o(async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(f=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let _=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(_,"Failed to send multipart request",!0),_}),"sendWithRetry");try{let l,u=!1;Wc()&&!this.multipartStreamingDisabled&&ni()!=="bun"?(u=!0,l=await c(a)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==bd&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){if(Ui(l))throw l;if(console.warn(`${l.message.trim()}
31
+
32
+ Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){z(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let s={...r,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=Pe(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){z(e);let n=Cr(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let s;r.session_id?s=r.session_id:n?.projectName?s=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?s=n?.projectId:s=(await this.readProject({projectName:te("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${r.id}?poll=true`}else if(e!==void 0){let s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Lb(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(s[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:s,traceId:i,referenceExampleId:a,startTime:c,executionOrder:l,isRoot:u,runType:d,error:f,id:_,query:g,filter:y,traceFilter:E,treeFilter:w,limit:S,select:I,order:m}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let b=Array.isArray(n)?n:[n],j=await Promise.all(b.map(G=>this.readProject({projectName:G}).then(B=>B.id)));T.push(...j)}let A=["app_path","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"],N={session:T.length?T:null,run_type:d,reference_example:a,query:g,filter:y,trace_filter:E,tree_filter:w,execution_order:l,parent_run:s,start_time:c?c.toISOString():null,error:f,id:_,limit:S,trace:i,select:I||A,is_root:u,order:m};N.select.includes("child_run_ids")&&Pt("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let b of this._getCursorPaginatedList("/runs/query",N)){let j=b.map(Cr);if(S){if(O>=S)break;if(j.length+O>S){yield*j.slice(0,S-O);break}O+=j.length,yield*j}else yield*j}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:s,filter:i,startTime:a,endTime:c,limit:l,offset:u}=e,f={session_id:r||(await this.readProject({projectName:n})).id,group_by:s,filter:i,start_time:a?a.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},_=Number(u)||0,g="/runs/group",y=`${this.apiUrl}${g}`;for(;;){let E={...f,offset:_},w=Object.fromEntries(Object.entries(E).filter(([N,O])=>O!==void 0)),S=JSON.stringify(w),m=await(await this.caller.call(async()=>{let N=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await U(N,`Failed to fetch ${g}`),N})).json(),{groups:T,total:A}=m;if(T.length===0)break;for(let N of T)yield N;if(_+=T.length,_>=A)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:s,isRoot:i=!0,limit:a,filter:c,order:l="asc"}=e;if(!n&&!s)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=c?`and(${u}, ${c})`:u;yield*this.listRuns({projectId:n??void 0,projectName:s??void 0,isRoot:i,limit:a,filter:d,order:l})}async listThreads(e){let{projectId:r,projectName:n,limit:s,offset:i=0,filter:a,startTime:c,isRoot:l=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=c??new Date(Date.now()-1440*60*1e3),_={session:[u],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};a!=null&&(_.filter=a);let g=new Map;for await(let S of this._getCursorPaginatedList("/runs/query",_))for(let I of S){let m=Cr(I),T=m.thread_id;if(T){let A=g.get(T)??[];A.push(m),g.set(T,A)}}let y=[];for(let[S,I]of g.entries()){I.sort((O,b)=>{let j=O,G=b,B=j.start_time??"",Z=G.start_time??"";if(B!==Z)return B.localeCompare(Z);let ce=j.dotted_order??"",ke=G.dotted_order??"";return ce.localeCompare(ke)});let T=[...I.map(O=>O.start_time).filter(Boolean)].sort(),A=T.length?T[0]:"",N=T.length?T[T.length-1]:"";y.push({thread_id:S,runs:I,count:I.length,filter:"",total_tokens:0,total_cost:null,min_start_time:A,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}y.sort((S,I)=>{let m=S.max_start_time??"";return(I.max_start_time??"").localeCompare(m)});let E=i>0?y.slice(i):y;return s!==void 0?E.slice(0,s):E}async getRunStats({id:e,trace:r,parentRun:n,runType:s,projectNames:i,projectIds:a,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:f,filter:_,traceFilter:g,treeFilter:y,isRoot:E,dataSourceType:w}){let S=a||[];i&&(S=[...a||[],...await Promise.all(i.map(O=>this.readProject({projectName:O}).then(b=>b.id)))]);let m=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:s,session:S,reference_example:c,start_time:l,end_time:u,error:d,query:f,filter:_,trace_filter:g,tree_filter:y,is_root:E,data_source_type:w}).filter(([O,b])=>b!==void 0)),T=JSON.stringify(m);return await(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await U(O,"get run stats"),O})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||kt()};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share run"),c})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare run",!0),r})}async readRunSharedLink(e){z(e);let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let a of r)n.append("id",a);return z(e),(await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"list shared runs"),a})).json()).map(Cr)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),z(e);let s=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(c,"share dataset"),c})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare dataset",!0),r})}async readSharedDataset(e){return z(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read shared dataset"),s})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let s=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>s.append(c,u)):s.append(c,l)});let i=await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(c,"list shared examples"),c}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples.
33
+ Status: ${i.status}
34
+ Message: ${Array.isArray(a.detail)?a.detail.join(`
35
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(c=>({...c,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:s=!1,projectExtra:i=null,referenceDatasetId:a=null}){let c=s?"?upsert=true":"",l=`${this.apiUrl}/sessions${c}`,u=i||{};n&&(u.metadata=n);let d={name:e,extra:u,description:r};a!==null&&(d.reference_dataset_id=a);let f=JSON.stringify(d);return await(await this.caller.call(async()=>{let y=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:f});return await U(y,"create project"),y})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:s=null,projectExtra:i=null,endTime:a=null}){let c=`${this.apiUrl}/sessions/${e}`,l=i;s&&(l={...l||{},metadata:s});let u=JSON.stringify({name:r,extra:l,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let _=await this._fetch(c,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"update project"),_})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),n+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let s="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),s+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(s,i),c;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);c=a[0]}else c=a;return c}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:s,referenceDatasetName:i,includeStats:a,datasetVersion:c,referenceFree:l,metadata:u}={}){let d=new URLSearchParams;if(e!==void 0)for(let f of e)d.append("id",f);if(r!==void 0&&d.append("name",r),n!==void 0&&d.append("name_contains",n),s!==void 0)d.append("reference_dataset",s);else if(i!==void 0){let f=await this.readDataset({datasetName:i});d.append("reference_dataset",f.id)}a!==void 0&&d.append("include_stats",a.toString()),c!==void 0&&d.append("dataset_version",c),l!==void 0&&d.append("reference_free",l.toString()),u!==void 0&&d.append("metadata",JSON.stringify(u));for await(let f of this._getPaginated("/sessions",d))yield*f}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,z(n),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,`delete session ${n} (${r})`,!0),s})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:s,description:i,dataType:a,name:c}){let l=`${this.apiUrl}/datasets/upload`,u=new FormData,d=new Blob([e],{type:"text/csv"});return u.append("file",d,r),n.forEach(g=>{u.append("input_keys",g)}),s.forEach(g=>{u.append("output_keys",g)}),i&&u.append("description",i),a&&u.append("data_type",a),c&&u.append("name",c),await(await this.caller.call(async()=>{let g=await this._fetch(l,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(g,"upload CSV"),g})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:s,outputsSchema:i,metadata:a}={}){let c={name:e,description:r,extra:{source:"sdk",...a?{metadata:a}:{}}};n&&(c.data_type=n),s&&(c.inputs_schema_definition=s),i&&(c.outputs_schema_definition=i);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(f,"create dataset"),f})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",s=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)z(e),n+=`/${e}`;else if(r)s.append("name",r);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(n,s),a;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:s}){let i=e;if(i===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:r})).id);let a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
36
+ `).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:s,datasetNameContains:i,metadata:a}={}){let c="/datasets",l=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)l.append("id",u);s!==void 0&&l.append("name",s),i!==void 0&&l.append("name_contains",i),a!==void 0&&l.append("metadata",JSON.stringify(a));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;z(i);let a=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:s,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;z(a);let c=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",s=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(s=(await this.readDataset({datasetName:r})).id),s!==void 0)z(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let s=e;if(!s&&!r)throw new Error("Must provide either datasetName or datasetId");if(s&&r)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:r})).id),z(s);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"index dataset"),l})).json()}async similarExamples(e,r,n,{filter:s}={}){let i={limit:n,inputs:e};s!==void 0&&(i.filter=s),z(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await U(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Ed(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(s===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,c;Ed(e)?c=e:c={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let l=await this._uploadExamplesMultipart(s,[c]);return await this.readExample(l.example_ids?.[0]??kt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let I=e,m=I[0].dataset_id,T=I[0].dataset_name;if(m===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:T})).id);let A=await this._uploadExamplesMultipart(m,I);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:f,datasetName:_}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=f,y=_;if(g===void 0&&y===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&y!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:y})).id);let E=r.map((I,m)=>({dataset_id:g,inputs:I,outputs:n?.[m],metadata:s?.[m],split:i?.[m],id:d?.[m],attachments:u?.[m],source_run_id:a?.[m],use_source_run_io:c?.[m],use_source_run_attachments:l?.[m]})),w=await this._uploadExamplesMultipart(g,E);return await Promise.all(w.example_ids.map(I=>this.readExample(I)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let s=e.map(a=>hi(a)?gi(a):a),i=hi(r)?gi(r):r;return this.createExample({input:s},{output:i},n)}async readExample(e){z(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:s,...i}=n,a=i;return s&&(a.attachments=Object.entries(s).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),a}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:s,splits:i,inlineS3Urls:a,metadata:c,limit:l,offset:u,filter:d,includeAttachments:f}={}){let _;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)_=e;else if(r!==void 0)_=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:_}),y=s?typeof s=="string"?s:s?.toISOString():void 0;y&&g.append("as_of",y);let E=a??!0;if(g.append("inline_s3_urls",E.toString()),n!==void 0)for(let S of n)g.append("id",S);if(i!==void 0)for(let S of i)g.append("splits",S);if(c!==void 0){let S=JSON.stringify(c);g.append("metadata",S)}l!==void 0&&g.append("limit",l.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),f===!0&&["attachment_urls","outputs","metadata"].forEach(S=>g.append("select",S));let w=0;for await(let S of this._getPaginated("/examples",g)){for(let I of S){let{attachment_urls:m,...T}=I,A=T;m&&(A.attachments=Object.entries(m).reduce((N,[O,b])=>(N[O.slice(11)]={presigned_url:b.presigned_url,mime_type:b.mime_type||void 0},N),{})),yield A,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){z(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>z(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"hard delete examples",!0),s})}else{let n=new URLSearchParams;e.forEach(s=>n.append("example_ids",s)),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"delete examples",!0),s})}}async updateExample(e,r){let n;r?n=e:n=e.id,z(n);let s;r?s={id:n,...r}:s=e;let i;return s.dataset_id!==void 0?i=s.dataset_id:i=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(i,[s])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:r})).id,z(i),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),s!==void 0&&a.append("tag",s),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let s;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:r})).id:s=e,z(s);let i=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${s}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,z(a);let c={split_name:n,examples:s.map(u=>(z(u),u)),remove:i},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update dataset splits",!0),u})}async createFeedback(e,r,{score:n,value:s,correction:i,comment:a,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:f,projectId:_,comparativeExperimentId:g,sessionId:y,startTime:E}){if(!e&&!_)throw new Error("One of runId or projectId must be provided");if(e&&_)throw new Error("Only one of runId or projectId can be provided");let w={type:l??"api",metadata:c??{}};u!==void 0&&w?.metadata!==void 0&&!w.metadata.__run&&(w.metadata.__run={run_id:u}),w?.metadata!==void 0&&w.metadata.__run?.run_id!==void 0&&z(w.metadata.__run.run_id);let S={id:d??gr(),run_id:e,key:r,score:_d(n),value:s,correction:i,comment:a,feedback_source:w,comparative_experiment_id:g,feedbackConfig:f,session_id:y??_,start_time:E},I=JSON.stringify(S),m=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let T=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await U(T,"create feedback",!0),T}),S}async updateFeedback(e,{score:r,value:n,correction:s,comment:i}){let a={};r!=null&&(a.score=_d(r)),n!=null&&(a.value=n),s!=null&&(a.correction=s),i!=null&&(a.comment=i),z(e);let c=JSON.stringify(a);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update feedback",!0),l})}async readFeedback(e){z(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){z(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let s=new URLSearchParams;if(e)for(let i of e)z(i),s.append("run",i);if(r)for(let i of r)s.append("key",i);if(n)for(let i of n)s.append("source",i);for await(let i of this._getPaginated("/feedback",s))yield*i}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:s}={}){let i={run_id:e,feedback_key:r,feedback_config:s};n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:s,description:i,metadata:a,id:c}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let l={id:c,name:e,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(s??new Date)?.toISOString(),extra:{}};a&&(l.extra.metadata=a);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){z(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){let s=this._selectEvalResults(e),i=[];for(let a of s){let c=n||{};a.evaluatorInfo&&(c={...a.evaluatorInfo,...c});let l=null;a.targetRunId?l=a.targetRunId:r&&(l=r.id),i.push(await this.createFeedback(l,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:c,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[s,i]}async logEvaluationFeedback(e,r,n){let[s]=await this._logEvaluationFeedback(e,r,n);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:s=!1}=e,i={feedback_key:r,feedback_config:n,is_lower_score_better:s};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:s}=e,i=new URLSearchParams;r&&r.forEach(c=>{i.append("key",c)}),n&&i.append("name_contains",n),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/feedback-configs",i))if(yield*c,a+=c.length,s!==void 0&&a>=s)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:s}=r,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),s!==void 0&&(i.is_lower_score_better=s),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"update feedback config"),c})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:s,limit:i}=e,a=new URLSearchParams;r&&r.forEach((l,u)=>{z(l,`queueIds[${u}]`),a.append("ids",l)}),n&&a.append("name",n),s&&a.append("name_contains",s),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",a))if(yield*l,c++,i!==void 0&&c>=i)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:s,rubricInstructions:i,rubricItems:a}=e,c={name:r,description:n,id:s||kt(),rubric_instructions:i,rubric_items:a},l=JSON.stringify(Object.fromEntries(Object.entries(c).filter(([d,f])=>f!==void 0)));return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:s,rubricInstructions:i,rubricItems:a}=r,c={};n!==void 0&&(c.name=n),s!==void 0&&(c.description=s),i!==void 0&&(c.rubric_instructions=i),a!==void 0&&(c.rubric_items=a);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=JSON.stringify(r.map((s,i)=>z(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${z(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"get run from annotation queue"),a})).json();return Cr(i)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs/${z(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
37
+
38
+ Current tenant: ${n.tenant_handle}
39
+
40
+ Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"get latest commit hash"),s})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,s,i]=at(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,`${r?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[r,n,s]=at(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${n}/${s.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}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){let[r,n,s]=at(e);for await(let i of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,a=>a.commits))yield*i}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,s=>s.repos))yield*n}async getPrompt(e){let[r,n,s]=at(e),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return c?.status===404?null:(await U(c,"get prompt"),c)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
41
+
42
+ creating a LangChain Hub handle.
43
+ You can add a handle by creating a public prompt at:
44
+
45
+ https://smith.langchain.com/prompts`);let[s,i,a]=at(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);let c={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},l=JSON.stringify(c),u=await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(f,"create prompt"),f}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[s,i,a]=at(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${s}/${i}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c},u=JSON.stringify(l),f=await(await this.caller.call(async()=>{let _=await this._fetch(`${this.apiUrl}/commits/${s}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"create commit"),_})).json();return this._getPromptUrl(`${s}/${i}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let c=a.id,l={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},u=Pe(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),a.inputs){let f=Pe(a.inputs,`Serializing inputs for example with id: ${c}`),_=new Blob([f],{type:"application/json"});n.append(`${c}.inputs`,_)}if(a.outputs){let f=Pe(a.outputs,`Serializing outputs whle updating example with id: ${c}`),_=new Blob([f],{type:"application/json"});n.append(`${c}.outputs`,_)}if(a.attachments)for(let[f,_]of Object.entries(a.attachments)){let g,y;Array.isArray(_)?[g,y]=_:(g=_.mimeType,y=_.data);let E=new Blob([y],{type:`${g}; length=${y.byteLength}`});n.append(`${c}.attachment.${f}`,E)}if(a.attachments_operations){let f=Pe(a.attachments_operations,`Serializing attachments while updating example with id: ${c}`),_=new Blob([f],{type:"application/json"});n.append(`${c}.attachments_operations`,_)}}let s=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let i of r){let a=(i.id??kt()).toString(),c={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Pe(c,`Serializing body for uploaded example with id: ${a}`),u=new Blob([l],{type:"application/json"});if(n.append(a,u),i.inputs){let d=Pe(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),f=new Blob([d],{type:"application/json"});n.append(`${a}.inputs`,f)}if(i.outputs){let d=Pe(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),f=new Blob([d],{type:"application/json"});n.append(`${a}.outputs`,f)}if(i.attachments)for(let[d,f]of Object.entries(i.attachments)){let _,g;Array.isArray(f)?[_,g]=f:(_=f.mimeType,g=f.data);let y=new Blob([g],{type:`${_}; length=${g.byteLength}`});n.append(`${a}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(i,"upload examples"),i})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,s]=at(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,s]=at(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,s,i]=at(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"pull prompt commit"),l})).json();return{owner:n,repo:s,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples}}async pullPromptCommit(e,r){let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let s=this._getPromptCacheKey(e,r?.includeModel),i=this._promptCache.get(s,n);if(i)return i;let a=await n();return this._promptCache.set(s,a,n),a}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(s=>s!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:s}=r,[i,a]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:i,apiKey:"placeholder"}),l=await c.readSharedDataset(a),u=s||l.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await c.listSharedExamples(a),f=await this.createDataset(u,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(_=>_.inputs),outputs:d.flatMap(_=>_.outputs?[_.outputs]:[]),datasetId:f.id})}catch(_){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),_}}parseTokenOrUrl(e,r,n=2,s="dataset"){try{return z(e),[r,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(c=>c!=="");if(a.length>=n){let c=a[a.length-n];return[r,c]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await El()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(vt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Ed(t){return"dataset_id"in t||"dataset_name"in t}o(Ed,"isExampleCreate");var Td=o(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>te(r)==="true"),"isTracingEnabled");var ot=Symbol.for("lc:context_variables");var zn=Symbol.for("langsmith:replica_trace_roots");function Hi(t,e){if(ot in t)return t[ot][e]}o(Hi,"getContextVar");function vd(t,e,r){let n=ot in t?t[ot]:{};n[e]=r,t[ot]=n}o(vd,"setContextVar");var Rr=36,Bb="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Sd(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Vs(r,Bb)}o(Sd,"getReplicaKey");function jb(t){return t.replace(/[-:.]/g,"")}o(jb,"stripNonAlphanumeric");function xd(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}o(xd,"getMicrosecondPrecisionDatestring");function Gi(t,e,r=1){let n=xd(t,r);return{dottedOrder:jb(n)+e,microsecondPrecisionDatestring:n}}o(Gi,"convertToDottedOrderFormat");var Hb=new Set(["projectName","updates","reroot"]);function Gb(t){let e={};for(let r of Object.keys(t))Hb.has(r)&&(e[r]=t[r]);return e}o(Gb,"filterReplicaForHeaders");var Vn=class t{static{o(this,"Baggage")}constructor(e,r,n,s){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}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=s}static fromHeader(e){let r=e.split(","),n={},s=[],i,a;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?s=d.split(","):l==="langsmith-project"?i=d:l==="langsmith-replicas"&&(a=JSON.parse(d).map(_=>Array.isArray(_)?_:Gb(_)))}return new t(n,s,i,a)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Qe=class t{static{o(this,"RunTree")}constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ad(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...s}=e,i=s.client??t.getSharedClient(),a={...n,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:a},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...r,...s,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=xd(this.start_time,this.execution_order)),this.id||(this.id=gn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Wb(this.replicas),!this.dotted_order){let{dottedOrder:c}=Gi(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:yr(),child_runs:[],api_url:Be("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Be("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new vt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(_=>{let{reroot:g,...y}=_;return y}),s=e.replicas??n,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),a=this.extra?.metadata??{},c=i.extra?.metadata??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...c}}),ot in this&&(i[ot]=this[ot]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(Vb(u)){let _={...u},g=zb(_.callbacks)?_.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:i.id}),g.handlers?.find(Cd)?.updateFromRunTree?.(i),_.callbacks=g),i.extra[l]=_}let d=new Set,f=this;for(;f!=null&&!d.has(f.id);)d.add(f.id),f.child_execution_order=Math.max(f.child_execution_order,r),f=f.parent_run;return this.child_runs.push(i),i}async end(e,r,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,r,n=!0){let s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),r))for(let[c,l]of Object.entries(r))s.runtime[c]||(s.runtime[c]=l);let i=e.parent_run?.id??e.parent_run_id,a;return n?a=[]:a=e.child_runs.map(c=>this._convertToCreate(c,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),s=null;for(let i=0;i<n.length;i++)if(n[i].slice(-Rr)===e){s=i;break}if(s!==null){let i=n.slice(s+1);r.dotted_order=i.join("."),i.length>0?r.trace_id=i[0].slice(-Rr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Hi(this,zn)??{};n[e]=r,vd(this,zn,n);for(let s of this.child_runs)s._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:c,apiKey:l,workspaceId:u}=e,d=this._convertToCreate(this,n,s);if(r===this.project_name)return{...d,session_name:r};if(i){if(a)this._sliceParentId(a,d);else if(d.parent_run_id=void 0,d.dotted_order){let I=d.dotted_order.split(".");I.length>0&&(d.dotted_order=I[I.length-1],d.trace_id=d.id)}let S=Sd({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});this._setReplicaTraceRoot(S,d.id)}let f;if(!i){let S=Hi(this,zn)??{},I=Sd({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});if(f=S[I],f&&(d.trace_id=f,d.dotted_order)){let m=d.dotted_order.split("."),T=null;for(let A=0;A<m.length;A++)if(m[A].slice(-Rr)===f){T=A;break}if(T!==null){let A=m.slice(T);d.dotted_order=A.join(".")}}}let _=d.id,g=_r(_,r),y;d.trace_id?y=_r(d.trace_id,r):y=g;let E;d.parent_run_id&&(E=_r(d.parent_run_id,r));let w;return d.dotted_order&&(w=d.dotted_order.split(".").map(m=>{let T=m.slice(-Rr),A=_r(T,r);return m.slice(0,-Rr)+A}).join(".")),{...d,id:g,trace_id:y,parent_run_id:E,dotted_order:w,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=wn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:s,apiUrl:i,workspaceId:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a});await this.client.createRun(l,{apiKey:s,apiUrl:i,workspaceId:a})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Pt("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:s,workspaceId:i,updates:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:n,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...a};e?.excludeInputs||(u.inputs=l.inputs),await this.client.updateRun(l.id,u,{apiKey:n,apiUrl:s,workspaceId:i})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,s,i,a,c=Td();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(f=>f?.name=="langchain_tracer");s=d?.getRun?.(u),i=d?.projectName,a=d?.client,c=c||!!d}return s?new t({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:a,tracingEnabled:c,project_name:i,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:a,tracingEnabled:c,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;let i=s.trim(),a=i.split(".").map(d=>{let[f,_]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:_}}),c=a[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:c,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let d=Vn.fromHeader(n.baggage);l.metadata=d.metadata,l.tags=d.tags,l.project_name=d.project_name,l.replicas=d.replicas}let u=new t(l);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Vn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,s]of Object.entries(r))e.set(n,s);return r}};Object.defineProperty(Qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ad(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(Ad,"isRunTree");function Cd(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(Cd,"isLangChainTracerLike");function Id(t){return Array.isArray(t)&&t.some(e=>Cd(e))}o(Id,"containsLangChainTracerLike");function zb(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(zb,"isCallbackManagerLike");function Vb(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(Id(e?.handlers)||Id(e))}o(Vb,"isRunnableConfigLike");function qb(){let t=Be("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){Kb(e);let r=[];for(let[n,s]of Object.entries(e)){let i=n.replace(/\/$/,"");if(typeof s=="string")r.push({apiUrl:i,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(pd(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}o(qb,"_getWriteReplicasFromEnv");function Wb(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):qb()}o(Wb,"_ensureWriteReplicas");function Kb(t){if(Object.keys(t).length>0&&te("ENDPOINT"))throw new Fn}o(Kb,"_checkEndpointEnvUnset");var Zb=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Vi(t,e){if(t)return new Qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Vi(e),child_runs:t.child_runs.map(r=>Vi(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:oc()},tracingEnabled:!1})}o(Vi,"convertRunToRunTree");function zi(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(zi,"_coerceToDict");function Qt(t){return typeof t._addRunToRunMap=="function"}o(Qt,"isBaseTracer");var $t=class extends qt{static{o(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?Zb(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
46
+
47
+ ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Gi(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},s=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?s?(this._addChildRun(s,n),s.child_execution_order=Math.max(s.child_execution_order,n.child_execution_order),n.trace_id=s.trace_id,s.dotted_order!==void 0&&(n.dotted_order=[s.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let i=Vi(n,s);i!==void 0&&this.runTreeMap.set(n.id,i)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleLLMStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleChatModelStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=t,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(t,e,r,n,s,i,a,c,l){let u=this._getExecutionOrder(n),d=Date.now(),f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:i?{...l,metadata:i}:{...l},tags:s||[]};return this._addRunToRunMap(f)}async handleChainStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=zi(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=zi(s.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=zi(s.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:e},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:e},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onRetrieverStart?.(c),c}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,s,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:i?.chunk}}),await this.onLLMNewToken?.(a,t,{chunk:i?.chunk}),a}};var Od={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function Oe(t,e){return`${t.open}${e}${t.close}`}o(Oe,"wrap");function Ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}o(Ve,"tryJsonStringify");function Rd(t){return typeof t=="string"?t.trim():t==null?t:Ve(t,t.toString())}o(Rd,"formatKVMapItem");function St(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}o(St,"elapsed");var{color:Le}=Od,qi=class extends $t{static{o(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,s)=>{let i=`${r.execution_order}:${r.run_type}:${r.name}`;return n===s.length-1?Oe(Od.bold,i):i}).join(" > ");return Oe(Le.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[chain/end]")} [${e}] [${St(t)}] Exiting Chain run with output: ${Ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[chain/error]")} [${e}] [${St(t)}] Chain run errored with error: ${Ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Oe(Le.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[llm/end]")} [${e}] [${St(t)}] Exiting LLM run with output: ${Ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[llm/error]")} [${e}] [${St(t)}] LLM run errored with error: ${Ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Rd(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[tool/end]")} [${e}] [${St(t)}] Exiting Tool run with output: "${Rd(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[tool/error]")} [${e}] [${St(t)}] Tool run errored with error: ${Ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[retriever/end]")} [${e}] [${St(t)}] Exiting Retriever run with output: ${Ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[retriever/error]")} [${e}] [${St(t)}] Retriever run errored with error: ${Ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Oe(Le.blue,"[agent/action]")} [${r}] Agent selected action: ${Ve(e.actions[e.actions.length-1],"[action]")}`)}};var Wi,Ki=o(()=>(Wi===void 0&&(Wi=new vt(Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Wi),"getDefaultLangChainClientSingleton");var Ji=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Zi=Symbol.for("ls:tracing_async_local_storage"),Jb=new Ji,Yi=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Zi]??Jb}initializeGlobalInstance(e){globalThis[Zi]===void 0&&(globalThis[Zi]=e)}},Yb=new Yi;function Nd(t=!1){let e=Yb.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
48
+
49
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}o(Nd,"getCurrentRunTree");var kd=new Set(["ls_agent_type"]);function Xb(t){let e;for(let r of t)for(let n of r)bt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Xr(e,n.message.usage_metadata));return e}o(Xb,"_getUsageMetadataFromGenerations");var Or=class Xi extends $t{static{o(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:s,replicas:i,metadata:a,tags:c}=e;this.projectName=n??yr(),this.replicas=i,this.exampleId=r,this.client=s??Ki(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=c??[];let l=Xi.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Md(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Md(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=Xb(r.generations);if(n!==void 0){e.extra=e.extra??{};let s=e.extra.metadata??{};s.usage_metadata=n,e.extra.metadata=s}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[a,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,a)||kd.has(a))&&(n[a]=c)}let s=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new Xi({...this.fields,metadata:n,tags:s});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let s=[r];for(;s.length>0;){let i=s.shift();!i||n.has(i.id)||(n.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&s.push(...i.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Nd(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Md(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[s,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,s)||kd.has(s))&&r[s]!==i&&(r[s]=i,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}o(Md,"_patchMissingTracingDefaults");var qn=_e(cn(),1);var Nr;function Qb(){return new("default"in qn.default?qn.default.default:qn.default)({autoStart:!0,concurrency:1})}o(Qb,"createQueue");function eE(){return typeof Nr>"u"&&(Nr=Qb()),Nr}o(eE,"getQueue");async function re(t,e){if(e===!0){let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Nr=eE(),Nr.add(async()=>{let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(re,"consumeCallback");var Pd=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Je(e)==="true"),"isTracingEnabled");function Qi(t){let e=wt();if(e!==void 0)return e.getStore()?.[Mt]?.[t]}o(Qi,"getContextVariable");var tE=Symbol("lc:configure_hooks"),Ld=o(()=>Qi(tE)||[],"_getConfigureHooks");var rE=class{static{o(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Wn=class{static{o(this,"BaseRunManager")}constructor(t,e,r,n,s,i,a,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>re(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},nE=class extends Wn{static{o(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Dd=class extends Wn{static{o(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleLLMEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},sE=class extends Wn{static{o(this,"CallbackManagerForChainRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleChainEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},iE=class extends Wn{static{o(this,"CallbackManagerForToolRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ut=class Mr extends rE{static{o(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:tt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return Qt(_)&&_._createRunForLLMStart(e,[u],f,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{await _.handleLLMStart?.(e,[u],f,this._parentRunId,i,this.tags,this.metadata,l)}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new Dd(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:tt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return Qt(_)&&_._createRunForChatModelStart(e,[u],f,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{if(_.handleChatModelStart)await _.handleChatModelStart?.(e,[u],f,this._parentRunId,i,this.tags,this.metadata,l);else if(_.handleLLMStart){let g=tn(u);await _.handleLLMStart?.(e,[g],f,this._parentRunId,i,this.tags,this.metadata,l)}}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new Dd(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=tt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return Qt(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u),re(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u)}catch(f){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${f}`),d.raiseError)throw f}},d.awaitHandlers)})),new sE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=tt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return Qt(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new iE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=tt(),s=void 0,i=void 0,a=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return Qt(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await l.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new nE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new Mr(this._parentRunId);for(let s of this.handlers){let i=this.inheritableHandlers.includes(s);n.addHandler(s,i)}for(let s of this.tags){let i=this.inheritableTags.includes(s);n.addTags([s],i)}for(let s of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(s);n.addMetadata({[s]:this.metadata[s]},i)}for(let s of e)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===s.name)||n.addHandler(s,r);return n}static fromHandlers(e){class r extends qt{static{o(this,"Handler")}name=tt();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,s,i,a,c){return this._configureSync(e,r,n,s,i,a,c)}static _configureSync(e,r,n,s,i,a,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new Mr,l.setHandlers(e?.map(ea)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(ea):r?.handlers,!1));let u=Je("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=Or.getTraceableRunTree(),f=d?.tracingEnabled??Pd();if(d?.tracingEnabled===!1&&l){let E=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of E)l.removeHandler(w)}let _=f||(Je("LANGCHAIN_TRACING")??!1);if(u||_){if(l||(l=new Mr),u&&!l.handlers.some(E=>E.name===qi.prototype.name)){let E=new qi;l.addHandler(E,!0)}if(_&&!l.handlers.some(E=>E.name==="langchain_tracer")&&f){let E=new Or;l.addHandler(E,!0)}f&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(E=>E.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:E,inheritable:w=!0,handlerClass:S,envVar:I}of Ld()){let m=I&&Je(I)==="true"&&S,T,A=E!==void 0?Qi(E):void 0;A&&cc(A)?T=A:m&&(T=new S({})),T!==void 0&&(l||(l=new Mr),l.handlers.some(N=>N.name===T.name)||l.addHandler(T,w))}(n||s)&&l&&(l.addTags(n??[]),l.addTags(s??[],!1)),(i||a)&&l&&(l.addMetadata(i??{}),l.addMetadata(a??{},!1));let g=c?.tracerInheritableMetadata,y=c?.tracerInheritableTags;return l&&(g||y)&&(l.handlers=l.handlers.map(E=>E instanceof Or?E.copyWithTracingConfig({metadata:g,tags:y}):E),l.inheritableHandlers=l.inheritableHandlers.map(E=>E instanceof Or?E.copyWithTracingConfig({metadata:g,tags:y}):E)),l}};function ea(t){return"name"in t?t:qt.fromMethods(t)}o(ea,"ensureHandler");var Ud=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},aE=new Ud,$d=Symbol.for("lc:child_config"),oE=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return wt()??aE}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[$d]}runWithConfig(t,e,r){let n=Ut._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),s=this.getInstance(),i=s.getStore(),a=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&a?l=c.getRunTreeWithTracingConfig(a):r||(l=new Qe({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[$d]:t}),i!==void 0&&i[Mt]!==void 0&&(l===void 0&&(l={}),l[Mt]=i[Mt]),s.run(l,e)}initializeGlobalInstance(t){wt()===void 0&&ac(t)}},kr=new oE;var cE=Object.prototype.hasOwnProperty;function jd(t,e){return cE.call(t,e)}o(jd,"hasOwnProperty");function Hd(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)jd(t,r)&&e.push(r);return e}o(Hd,"_objectKeys");function ft(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}o(ft,"_deepClone");function Zn(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}o(Zn,"isInteger");function Gd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(Gd,"unescapePathComponent");function Kn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Kn(t[r]))return!0}else if(typeof t=="object"){let r=Hd(t),n=r.length;for(var e=0;e<n;e++)if(Kn(t[r[e]]))return!0}}return!1}o(Kn,"hasUndefined");function Bd(t,e){let r=[t];for(let n in e){let s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&r.push(`${n}: ${s}`)}return r.join(`
50
+ `)}o(Bd,"patchErrorMessageFormatter");var zd=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,s){super(Bd(t,{name:e,index:r,operation:n,tree:s})),this.name=e,this.index=r,this.operation=n,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Bd(t,{name:e,index:r,operation:n,tree:s})}};var Vd=W({JsonPatchError:o(()=>se,"JsonPatchError"),_areEquals:o(()=>Pr,"_areEquals"),applyOperation:o(()=>Ft,"applyOperation"),applyPatch:o(()=>Xn,"applyPatch"),applyReducer:o(()=>dE,"applyReducer"),deepClone:o(()=>lE,"deepClone"),getValueByPointer:o(()=>Jn,"getValueByPointer"),validate:o(()=>qd,"validate"),validator:o(()=>Yn,"validator")}),se=zd,lE=ft,er={add:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:o(function(t,e,r){let n=Jn(r,this.path);n&&(n=ft(n));let s=Ft(r,{op:"remove",path:this.from}).removed;return Ft(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:n}},"move"),copy:o(function(t,e,r){let n=Jn(r,this.from);return Ft(r,{op:"add",path:this.path,value:ft(n)}),{newDocument:r}},"copy"),test:o(function(t,e,r){return{newDocument:r,test:Pr(t[e],this.value)}},"test"),_get:o(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},uE={add:o(function(t,e,r){return Zn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:o(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:o(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:er.move,copy:er.copy,test:er.test,_get:er._get};function Jn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ft(t,r),r.value}o(Jn,"getValueByPointer");function Ft(t,e,r=!1,n=!0,s=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Yn(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Jn(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Pr(t,e.value),a.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=ft(t));let a=(e.path||"").split("/"),c=t,l=1,u=a.length,d,f,_;for(typeof r=="function"?_=r:_=Yn;;){if(f=a[l],f&&f.indexOf("~")!=-1&&(f=Gd(f)),s&&(f=="__proto__"||f=="prototype"&&l>0&&a[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[f]===void 0?d=a.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&_(e,0,t,d)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!Zn(f))throw new se("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Zn(f)&&(f=~~f)}if(l>=u){if(r&&e.op==="add"&&f>c.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let g=uE[e.op].call(e,c,f,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}}else if(l>=u){let g=er[e.op].call(e,c,f,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}if(c=c[f],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}o(Ft,"applyOperation");function Xn(t,e,r,n=!0,s=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=ft(t));let i=new Array(e.length);for(let a=0,c=e.length;a<c;a++)i[a]=Ft(t,e[a],r,!0,s,a),t=i[a].newDocument;return i.newDocument=t,i}o(Xn,"applyPatch");function dE(t,e,r){let n=Ft(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}o(dE,"applyReducer");function Yn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(er[t.op]){if(typeof t.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Kn(t.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var s=t.path.split("/").length,i=n.split("/").length;if(s!==i+1&&s!==i)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a=qd([{op:"_get",path:t.from,value:void 0}],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}o(Yn,"validator");function qd(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xn(ft(e),ft(t),r||!0);else{r=r||Yn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(s){if(s instanceof se)return s;throw s}}o(qd,"validate");function Pr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),s,i,a;if(r&&n){if(i=t.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Pr(t[s],e[s]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!Pr(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}o(Pr,"_areEquals");({...Vd});var j$=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var _E=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bE=[0,31,28,31,30,31,30,31,31,30,31,30,31],EE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,wE=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,TE=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,vE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,SE=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,IE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xE=/^(?:\/(?:[^~/]|~0|~1)*)*$/,AE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,CE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,RE=o(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),OE=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,NE=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,ME=o(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function ct(t){return t.test.bind(t)}o(ct,"bind");var kE={date:Wd,time:Kd.bind(void 0,!1),"date-time":DE,duration:ME,uri:FE,"uri-reference":ct(TE),"uri-template":ct(vE),url:ct(SE),email:RE,hostname:ct(wE),ipv4:ct(OE),ipv6:ct(NE),regex:jE,uuid:ct(IE),"json-pointer":ct(xE),"json-pointer-uri-fragment":ct(AE),"relative-json-pointer":ct(CE)};function PE(t){return t%4===0&&(t%100!==0||t%400===0)}o(PE,"isLeapYear");function Wd(t){let e=t.match(_E);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&PE(r)?29:bE[n])}o(Wd,"date");function Kd(t,e){let r=e.match(EE);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!t||a)}o(Kd,"time");var LE=/t|\s/i;function DE(t){let e=t.split(LE);return e.length==2&&Wd(e[0])&&Kd(!0,e[1])}o(DE,"date_time");var $E=/\/|:/,UE=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function FE(t){return $E.test(t)&&UE.test(t)}o(FE,"uri");var BE=/[^\\]\\Z/;function jE(t){if(BE.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(jE,"regex");var Zd;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(Zd||(Zd={}));var cf=_e(of(),1);var nw=Object.defineProperty,sw=o((t,e,r)=>e in t?nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),iw=o((t,e,r)=>(sw(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function aw(t,e){let r=Array.from({length:t.length},(n,s)=>({start:s,end:s+1}));for(;r.length>1;){let n=null;for(let s=0;s<r.length-1;s++){let i=t.slice(r[s].start,r[s+1].end),a=e.get(i.join(","));a!=null&&(n==null||a<n[0])&&(n=[a,s])}if(n!=null){let s=n[1];r[s]={start:r[s].start,end:r[s+1].end},r.splice(s+1,1)}else break}return r}o(aw,"bytePairMerge");function ow(t,e){return t.length===1?[e.get(t.join(","))]:aw(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(ow,"bytePairEncode");function cw(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(cw,"escapeRegex");var aa=class{static{o(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
51
+ `).filter(Boolean).reduce((n,s)=>{let[i,a,...c]=s.split(" "),l=Number.parseInt(a,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,s]of Object.entries(r)){let i=cf.default.toByteArray(n);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,i])=>(n[i]=this.textEncoder.encode(s),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),s=aa.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):r);if(c.size>0){let u=aa.specialTokenRegex([...c]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let l=0;for(;;){let u=null,d=l;for(;s.lastIndex=d,u=s.exec(t),!(u==null||a.has(u[0]));)d=u.index+1;let f=u?.index??t.length;for(let g of t.substring(l,f).matchAll(n)){let y=this.textEncoder.encode(g[0]),E=this.rankMap.get(y.join(","));if(E!=null){i.push(E);continue}i.push(...ow(y,this.rankMap))}if(u==null)break;let _=this.specialTokens[u[0]];i.push(_),l=u.index+u[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],c=this.textMap.get(a)??this.inverseSpecialTokens[a];c!=null&&(e.push(c),r+=c.length)}let n=new Uint8Array(r),s=0;for(let i of e)n.set(i,s),s+=i.length;return this.textDecoder.decode(n)}},oa=aa;iw(oa,"specialTokenRegex",t=>new RegExp(t.map(e=>cw(e)).join("|"),"g"));var ff=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var pf=["image","video","audio","text-plain","file"];var dw=["text","reasoning",...ff,...pf];var bw=o(function(){let t={};t.parser=function(h,p){return new r(h,p)},t.SAXParser=r,t.SAXStream=u,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(h,p){if(!(this instanceof r))return new r(h,p);var C=this;s(C),C.q=C.c="",C.bufferCheckPosition=t.MAX_BUFFER_LENGTH,C.opt=p||{},C.opt.lowercase=C.opt.lowercase||C.opt.lowercasetags,C.looseCase=C.opt.lowercase?"toLowerCase":"toUpperCase",C.tags=[],C.closed=C.closedRoot=C.sawRoot=!1,C.tag=C.error=null,C.strict=!!h,C.noscript=!!(h||C.opt.noscript),C.state=b.BEGIN,C.strictEntities=C.opt.strictEntities,C.ENTITIES=C.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),C.attribList=[],C.opt.xmlns&&(C.ns=Object.create(y)),C.trackPosition=C.opt.position!==!1,C.trackPosition&&(C.position=C.line=C.column=0),G(C,"onready")}o(r,"SAXParser"),Object.create||(Object.create=function(h){function p(){}return o(p,"F"),p.prototype=h,new p}),Object.keys||(Object.keys=function(h){var p=[];for(var C in h)h.hasOwnProperty(C)&&p.push(C);return p});function n(h){for(var p=Math.max(t.MAX_BUFFER_LENGTH,10),C=0,v=0,J=e.length;v<J;v++){var le=h[e[v]].length;if(le>p)switch(e[v]){case"textNode":Z(h);break;case"cdata":B(h,"oncdata",h.cdata),h.cdata="";break;case"script":B(h,"onscript",h.script),h.script="";break;default:ke(h,"Max buffer length exceeded: "+e[v])}C=Math.max(C,le)}h.bufferCheckPosition=t.MAX_BUFFER_LENGTH-C+h.position}o(n,"checkBufferLength");function s(h){for(var p=0,C=e.length;p<C;p++)h[e[p]]=""}o(s,"clearBuffers");function i(h){Z(h),h.cdata!==""&&(B(h,"oncdata",h.cdata),h.cdata=""),h.script!==""&&(B(h,"onscript",h.script),h.script="")}o(i,"flushBuffers"),r.prototype={end:o(function(){xt(this)},"end"),write:mm,resume:o(function(){return this.error=null,this},"resume"),close:o(function(){return this.write(null)},"close"),flush:o(function(){i(this)},"flush")};var a=ReadableStream;a||(a=o(function(){},"Stream"));var c=t.EVENTS.filter(function(h){return h!=="error"&&h!=="end"});function l(h,p){return new u(h,p)}o(l,"createStream");function u(h,p){if(!(this instanceof u))return new u(h,p);a.apply(this),this._parser=new r(h,p),this.writable=!0,this.readable=!0;var C=this;this._parser.onend=function(){C.emit("end")},this._parser.onerror=function(v){C.emit("error",v),C._parser.error=null},this._decoder=null,c.forEach(function(v){Object.defineProperty(C,"on"+v,{get:o(function(){return C._parser["on"+v]},"get"),set:o(function(J){if(!J)return C.removeAllListeners(v),C._parser["on"+v]=J,J;C.on(v,J)},"set"),enumerable:!0,configurable:!1})})}o(u,"SAXStream"),u.prototype=Object.create(a.prototype,{constructor:{value:u}}),u.prototype.write=function(h){return this._parser.write(h.toString()),this.emit("data",h),!0},u.prototype.end=function(h){return h&&h.length&&this.write(h),this._parser.end(),!0},u.prototype.on=function(h,p){var C=this;return!C._parser["on"+h]&&c.indexOf(h)!==-1&&(C._parser["on"+h]=function(){var v=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);v.splice(0,0,h),C.emit.apply(C,v)}),a.prototype.on.call(C,h,p)};var d="[CDATA[",f="DOCTYPE",_="http://www.w3.org/XML/1998/namespace",g="http://www.w3.org/2000/xmlns/",y={xml:_,xmlns:g},E=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function m(h){return h===" "||h===`
52
+ `||h==="\r"||h===" "}o(m,"isWhitespace");function T(h){return h==='"'||h==="'"}o(T,"isQuote");function A(h){return h===">"||m(h)}o(A,"isAttribEnd");function N(h,p){return h.test(p)}o(N,"isMatch");function O(h,p){return!N(h,p)}o(O,"notMatch");var b=0;t.STATE={BEGIN:b++,BEGIN_WHITESPACE:b++,TEXT:b++,TEXT_ENTITY:b++,OPEN_WAKA:b++,SGML_DECL:b++,SGML_DECL_QUOTED:b++,DOCTYPE:b++,DOCTYPE_QUOTED:b++,DOCTYPE_DTD:b++,DOCTYPE_DTD_QUOTED:b++,COMMENT_STARTING:b++,COMMENT:b++,COMMENT_ENDING:b++,COMMENT_ENDED:b++,CDATA:b++,CDATA_ENDING:b++,CDATA_ENDING_2:b++,PROC_INST:b++,PROC_INST_BODY:b++,PROC_INST_ENDING:b++,OPEN_TAG:b++,OPEN_TAG_SLASH:b++,ATTRIB:b++,ATTRIB_NAME:b++,ATTRIB_NAME_SAW_WHITE:b++,ATTRIB_VALUE:b++,ATTRIB_VALUE_QUOTED:b++,ATTRIB_VALUE_CLOSED:b++,ATTRIB_VALUE_UNQUOTED:b++,ATTRIB_VALUE_ENTITY_Q:b++,ATTRIB_VALUE_ENTITY_U:b++,CLOSE_TAG:b++,CLOSE_TAG_SAW_WHITE:b++,SCRIPT:b++,SCRIPT_ENDING:b++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(h){var p=t.ENTITIES[h],C=typeof p=="number"?String.fromCharCode(p):p;t.ENTITIES[h]=C});for(var j in t.STATE)t.STATE[t.STATE[j]]=j;b=t.STATE;function G(h,p,C){h[p]&&h[p](C)}o(G,"emit");function B(h,p,C){h.textNode&&Z(h),G(h,p,C)}o(B,"emitNode");function Z(h){h.textNode=ce(h.opt,h.textNode),h.textNode&&G(h,"ontext",h.textNode),h.textNode=""}o(Z,"closeText");function ce(h,p){return h.trim&&(p=p.trim()),h.normalize&&(p=p.replace(/\s+/g," ")),p}o(ce,"textopts");function ke(h,p){return Z(h),h.trackPosition&&(p+=`
53
+ Line: `+h.line+`
54
+ Column: `+h.column+`
55
+ Char: `+h.c),p=new Error(p),h.error=p,G(h,"onerror",p),h}o(ke,"error");function xt(h){return h.sawRoot&&!h.closedRoot&&K(h,"Unclosed root tag"),h.state!==b.BEGIN&&h.state!==b.BEGIN_WHITESPACE&&h.state!==b.TEXT&&ke(h,"Unexpected end"),Z(h),h.c="",h.closed=!0,G(h,"onend"),r.call(h,h.strict,h.opt),h}o(xt,"end");function K(h,p){if(typeof h!="object"||!(h instanceof r))throw new Error("bad call to strictFail");h.strict&&ke(h,p)}o(K,"strictFail");function pm(h){h.strict||(h.tagName=h.tagName[h.looseCase]());var p=h.tags[h.tags.length-1]||h,C=h.tag={name:h.tagName,attributes:{}};h.opt.xmlns&&(C.ns=p.ns),h.attribList.length=0,B(h,"onopentagstart",C)}o(pm,"newTag");function bs(h,p){var C=h.indexOf(":")<0?["",h]:h.split(":"),v=C[0],J=C[1];return p&&h==="xmlns"&&(v="xmlns",J=""),{prefix:v,local:J}}o(bs,"qname");function Es(h){if(h.strict||(h.attribName=h.attribName[h.looseCase]()),h.attribList.indexOf(h.attribName)!==-1||h.tag.attributes.hasOwnProperty(h.attribName)){h.attribName=h.attribValue="";return}if(h.opt.xmlns){var p=bs(h.attribName,!0),C=p.prefix,v=p.local;if(C==="xmlns")if(v==="xml"&&h.attribValue!==_)K(h,"xml: prefix must be bound to "+_+`
56
+ Actual: `+h.attribValue);else if(v==="xmlns"&&h.attribValue!==g)K(h,"xmlns: prefix must be bound to "+g+`
57
+ Actual: `+h.attribValue);else{var J=h.tag,le=h.tags[h.tags.length-1]||h;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[v]=h.attribValue}h.attribList.push([h.attribName,h.attribValue])}else h.tag.attributes[h.attribName]=h.attribValue,B(h,"onattribute",{name:h.attribName,value:h.attribValue});h.attribName=h.attribValue=""}o(Es,"attrib");function At(h,p){if(h.opt.xmlns){var C=h.tag,v=bs(h.tagName);C.prefix=v.prefix,C.local=v.local,C.uri=C.ns[v.prefix]||"",C.prefix&&!C.uri&&(K(h,"Unbound namespace prefix: "+JSON.stringify(h.tagName)),C.uri=v.prefix);var J=h.tags[h.tags.length-1]||h;C.ns&&J.ns!==C.ns&&Object.keys(C.ns).forEach(function(Va){B(h,"onopennamespace",{prefix:Va,uri:C.ns[Va]})});for(var le=0,$e=h.attribList.length;le<$e;le++){var xe=h.attribList[le],Ke=xe[0],Ct=xe[1],Te=bs(Ke,!0),Rt=Te.prefix,hm=Te.local,za=Rt===""?"":C.ns[Rt]||"",Ts={name:Ke,value:Ct,prefix:Rt,local:hm,uri:za};Rt&&Rt!=="xmlns"&&!za&&(K(h,"Unbound namespace prefix: "+JSON.stringify(Rt)),Ts.uri=Rt),h.tag.attributes[Ke]=Ts,B(h,"onattribute",Ts)}h.attribList.length=0}h.tag.isSelfClosing=!!p,h.sawRoot=!0,h.tags.push(h.tag),B(h,"onopentag",h.tag),p||(!h.noscript&&h.tagName.toLowerCase()==="script"?h.state=b.SCRIPT:h.state=b.TEXT,h.tag=null,h.tagName=""),h.attribName=h.attribValue="",h.attribList.length=0}o(At,"openTag");function ws(h){if(!h.tagName){K(h,"Weird empty close tag."),h.textNode+="</>",h.state=b.TEXT;return}if(h.script){if(h.tagName!=="script"){h.script+="</"+h.tagName+">",h.tagName="",h.state=b.SCRIPT;return}B(h,"onscript",h.script),h.script=""}var p=h.tags.length,C=h.tagName;h.strict||(C=C[h.looseCase]());for(var v=C;p--&&h.tags[p].name!==v;)K(h,"Unexpected close tag");if(p<0){K(h,"Unmatched closing tag: "+h.tagName),h.textNode+="</"+h.tagName+">",h.state=b.TEXT;return}h.tagName=C;for(var J=h.tags.length;J-- >p;){var le=h.tag=h.tags.pop();h.tagName=h.tag.name,B(h,"onclosetag",h.tagName);var $e={};for(var xe in le.ns)$e[xe]=le.ns[xe];var Ke=h.tags[h.tags.length-1]||h;h.opt.xmlns&&le.ns!==Ke.ns&&Object.keys(le.ns).forEach(function(Ct){var Te=le.ns[Ct];B(h,"onclosenamespace",{prefix:Ct,uri:Te})})}p===0&&(h.closedRoot=!0),h.tagName=h.attribValue=h.attribName="",h.attribList.length=0,h.state=b.TEXT}o(ws,"closeTag");function ja(h){var p=h.entity,C=p.toLowerCase(),v,J="";return h.ENTITIES[p]?h.ENTITIES[p]:h.ENTITIES[C]?h.ENTITIES[C]:(p=C,p.charAt(0)==="#"&&(p.charAt(1)==="x"?(p=p.slice(2),v=parseInt(p,16),J=v.toString(16)):(p=p.slice(1),v=parseInt(p,10),J=v.toString(10))),p=p.replace(/^0+/,""),isNaN(v)||J.toLowerCase()!==p?(K(h,"Invalid character entity"),"&"+h.entity+";"):String.fromCodePoint(v))}o(ja,"parseEntity");function Ha(h,p){p==="<"?(h.state=b.OPEN_WAKA,h.startTagPosition=h.position):m(p)||(K(h,"Non-whitespace before first tag."),h.textNode=p,h.state=b.TEXT)}o(Ha,"beginWhiteSpace");function Ga(h,p){var C="";return p<h.length&&(C=h.charAt(p)),C}o(Ga,"charAt");function mm(h){var p=this;if(this.error)throw this.error;if(p.closed)return ke(p,"Cannot write after close. Assign an onready handler.");if(h===null)return xt(p);typeof h=="object"&&(h=h.toString());for(var C=0,v="";v=Ga(h,C++),p.c=v,!!v;)switch(p.trackPosition&&(p.position++,v===`
58
+ `?(p.line++,p.column=0):p.column++),p.state){case b.BEGIN:if(p.state=b.BEGIN_WHITESPACE,v==="\uFEFF")continue;Ha(p,v);continue;case b.BEGIN_WHITESPACE:Ha(p,v);continue;case b.TEXT:if(p.sawRoot&&!p.closedRoot){for(var J=C-1;v&&v!=="<"&&v!=="&";)v=Ga(h,C++),v&&p.trackPosition&&(p.position++,v===`
59
+ `?(p.line++,p.column=0):p.column++);p.textNode+=h.substring(J,C-1)}v==="<"&&!(p.sawRoot&&p.closedRoot&&!p.strict)?(p.state=b.OPEN_WAKA,p.startTagPosition=p.position):(!m(v)&&(!p.sawRoot||p.closedRoot)&&K(p,"Text data outside of root node."),v==="&"?p.state=b.TEXT_ENTITY:p.textNode+=v);continue;case b.SCRIPT:v==="<"?p.state=b.SCRIPT_ENDING:p.script+=v;continue;case b.SCRIPT_ENDING:v==="/"?p.state=b.CLOSE_TAG:(p.script+="<"+v,p.state=b.SCRIPT);continue;case b.OPEN_WAKA:if(v==="!")p.state=b.SGML_DECL,p.sgmlDecl="";else if(!m(v))if(N(E,v))p.state=b.OPEN_TAG,p.tagName=v;else if(v==="/")p.state=b.CLOSE_TAG,p.tagName="";else if(v==="?")p.state=b.PROC_INST,p.procInstName=p.procInstBody="";else{if(K(p,"Unencoded <"),p.startTagPosition+1<p.position){var le=p.position-p.startTagPosition;v=new Array(le).join(" ")+v}p.textNode+="<"+v,p.state=b.TEXT}continue;case b.SGML_DECL:(p.sgmlDecl+v).toUpperCase()===d?(B(p,"onopencdata"),p.state=b.CDATA,p.sgmlDecl="",p.cdata=""):p.sgmlDecl+v==="--"?(p.state=b.COMMENT,p.comment="",p.sgmlDecl=""):(p.sgmlDecl+v).toUpperCase()===f?(p.state=b.DOCTYPE,(p.doctype||p.sawRoot)&&K(p,"Inappropriately located doctype declaration"),p.doctype="",p.sgmlDecl=""):v===">"?(B(p,"onsgmldeclaration",p.sgmlDecl),p.sgmlDecl="",p.state=b.TEXT):(T(v)&&(p.state=b.SGML_DECL_QUOTED),p.sgmlDecl+=v);continue;case b.SGML_DECL_QUOTED:v===p.q&&(p.state=b.SGML_DECL,p.q=""),p.sgmlDecl+=v;continue;case b.DOCTYPE:v===">"?(p.state=b.TEXT,B(p,"ondoctype",p.doctype),p.doctype=!0):(p.doctype+=v,v==="["?p.state=b.DOCTYPE_DTD:T(v)&&(p.state=b.DOCTYPE_QUOTED,p.q=v));continue;case b.DOCTYPE_QUOTED:p.doctype+=v,v===p.q&&(p.q="",p.state=b.DOCTYPE);continue;case b.DOCTYPE_DTD:p.doctype+=v,v==="]"?p.state=b.DOCTYPE:T(v)&&(p.state=b.DOCTYPE_DTD_QUOTED,p.q=v);continue;case b.DOCTYPE_DTD_QUOTED:p.doctype+=v,v===p.q&&(p.state=b.DOCTYPE_DTD,p.q="");continue;case b.COMMENT:v==="-"?p.state=b.COMMENT_ENDING:p.comment+=v;continue;case b.COMMENT_ENDING:v==="-"?(p.state=b.COMMENT_ENDED,p.comment=ce(p.opt,p.comment),p.comment&&B(p,"oncomment",p.comment),p.comment=""):(p.comment+="-"+v,p.state=b.COMMENT);continue;case b.COMMENT_ENDED:v!==">"?(K(p,"Malformed comment"),p.comment+="--"+v,p.state=b.COMMENT):p.state=b.TEXT;continue;case b.CDATA:v==="]"?p.state=b.CDATA_ENDING:p.cdata+=v;continue;case b.CDATA_ENDING:v==="]"?p.state=b.CDATA_ENDING_2:(p.cdata+="]"+v,p.state=b.CDATA);continue;case b.CDATA_ENDING_2:v===">"?(p.cdata&&B(p,"oncdata",p.cdata),B(p,"onclosecdata"),p.cdata="",p.state=b.TEXT):v==="]"?p.cdata+="]":(p.cdata+="]]"+v,p.state=b.CDATA);continue;case b.PROC_INST:v==="?"?p.state=b.PROC_INST_ENDING:m(v)?p.state=b.PROC_INST_BODY:p.procInstName+=v;continue;case b.PROC_INST_BODY:if(!p.procInstBody&&m(v))continue;v==="?"?p.state=b.PROC_INST_ENDING:p.procInstBody+=v;continue;case b.PROC_INST_ENDING:v===">"?(B(p,"onprocessinginstruction",{name:p.procInstName,body:p.procInstBody}),p.procInstName=p.procInstBody="",p.state=b.TEXT):(p.procInstBody+="?"+v,p.state=b.PROC_INST_BODY);continue;case b.OPEN_TAG:N(w,v)?p.tagName+=v:(pm(p),v===">"?At(p):v==="/"?p.state=b.OPEN_TAG_SLASH:(m(v)||K(p,"Invalid character in tag name"),p.state=b.ATTRIB));continue;case b.OPEN_TAG_SLASH:v===">"?(At(p,!0),ws(p)):(K(p,"Forward-slash in opening tag not followed by >"),p.state=b.ATTRIB);continue;case b.ATTRIB:if(m(v))continue;v===">"?At(p):v==="/"?p.state=b.OPEN_TAG_SLASH:N(E,v)?(p.attribName=v,p.attribValue="",p.state=b.ATTRIB_NAME):K(p,"Invalid attribute name");continue;case b.ATTRIB_NAME:v==="="?p.state=b.ATTRIB_VALUE:v===">"?(K(p,"Attribute without value"),p.attribValue=p.attribName,Es(p),At(p)):m(v)?p.state=b.ATTRIB_NAME_SAW_WHITE:N(w,v)?p.attribName+=v:K(p,"Invalid attribute name");continue;case b.ATTRIB_NAME_SAW_WHITE:if(v==="=")p.state=b.ATTRIB_VALUE;else{if(m(v))continue;K(p,"Attribute without value"),p.tag.attributes[p.attribName]="",p.attribValue="",B(p,"onattribute",{name:p.attribName,value:""}),p.attribName="",v===">"?At(p):N(E,v)?(p.attribName=v,p.state=b.ATTRIB_NAME):(K(p,"Invalid attribute name"),p.state=b.ATTRIB)}continue;case b.ATTRIB_VALUE:if(m(v))continue;T(v)?(p.q=v,p.state=b.ATTRIB_VALUE_QUOTED):(K(p,"Unquoted attribute value"),p.state=b.ATTRIB_VALUE_UNQUOTED,p.attribValue=v);continue;case b.ATTRIB_VALUE_QUOTED:if(v!==p.q){v==="&"?p.state=b.ATTRIB_VALUE_ENTITY_Q:p.attribValue+=v;continue}Es(p),p.q="",p.state=b.ATTRIB_VALUE_CLOSED;continue;case b.ATTRIB_VALUE_CLOSED:m(v)?p.state=b.ATTRIB:v===">"?At(p):v==="/"?p.state=b.OPEN_TAG_SLASH:N(E,v)?(K(p,"No whitespace between attributes"),p.attribName=v,p.attribValue="",p.state=b.ATTRIB_NAME):K(p,"Invalid attribute name");continue;case b.ATTRIB_VALUE_UNQUOTED:if(!A(v)){v==="&"?p.state=b.ATTRIB_VALUE_ENTITY_U:p.attribValue+=v;continue}Es(p),v===">"?At(p):p.state=b.ATTRIB;continue;case b.CLOSE_TAG:if(p.tagName)v===">"?ws(p):N(w,v)?p.tagName+=v:p.script?(p.script+="</"+p.tagName,p.tagName="",p.state=b.SCRIPT):(m(v)||K(p,"Invalid tagname in closing tag"),p.state=b.CLOSE_TAG_SAW_WHITE);else{if(m(v))continue;O(E,v)?p.script?(p.script+="</"+v,p.state=b.SCRIPT):K(p,"Invalid tagname in closing tag."):p.tagName=v}continue;case b.CLOSE_TAG_SAW_WHITE:if(m(v))continue;v===">"?ws(p):K(p,"Invalid characters in closing tag");continue;case b.TEXT_ENTITY:case b.ATTRIB_VALUE_ENTITY_Q:case b.ATTRIB_VALUE_ENTITY_U:var $e,xe;switch(p.state){case b.TEXT_ENTITY:$e=b.TEXT,xe="textNode";break;case b.ATTRIB_VALUE_ENTITY_Q:$e=b.ATTRIB_VALUE_QUOTED,xe="attribValue";break;case b.ATTRIB_VALUE_ENTITY_U:$e=b.ATTRIB_VALUE_UNQUOTED,xe="attribValue";break}if(v===";")if(p.opt.unparsedEntities){var Ke=ja(p);p.entity="",p.state=$e,p.write(Ke)}else p[xe]+=ja(p),p.entity="",p.state=$e;else N(p.entity.length?I:S,v)?p.entity+=v:(K(p,"Invalid character in entity name"),p[xe]+="&"+p.entity+v,p.entity="",p.state=$e);continue;default:throw new Error(p,"Unknown state: "+p.state)}return p.position>=p.bufferCheckPosition&&n(p),p}o(mm,"write");return String.fromCodePoint||(function(){var h=String.fromCharCode,p=Math.floor,C=o(function(){var v=16384,J=[],le,$e,xe=-1,Ke=arguments.length;if(!Ke)return"";for(var Ct="";++xe<Ke;){var Te=Number(arguments[xe]);if(!isFinite(Te)||Te<0||Te>1114111||p(Te)!==Te)throw RangeError("Invalid code point: "+Te);Te<=65535?J.push(Te):(Te-=65536,le=(Te>>10)+55296,$e=Te%1024+56320,J.push(le,$e)),(xe+1===Ke||J.length>v)&&(Ct+=h.apply(null,J),J.length=0)}return Ct},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:C,configurable:!0,writable:!0}):String.fromCodePoint=C})(),t},"initializeSax"),Ew=bw();var $3=require("@playwright/test");var A3={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var xf=_e(If());xf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var jw="claude_4",Hw={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},Gw=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:jw},models:Hw,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ue=Gw();var P3={claude_4:ue.models.claude4sonnet,"claude_3.7":ue.models.claude37sonnet,claude_sonnet_4_6:ue.models.claudeSonnet46,claude_sonnet_5:ue.models.claudeSonnet5,claude_opus_4_8:ue.models.claudeOpus48,"gemini_2.5_pro":ue.models.gemini25pro,"gemini_2.0_flash":ue.models.gemini20flash,"gemini_2.5_flash_lite":ue.models.gemini25flash_lite,"gemini_2.5_flash":ue.models.gemini25flash,"gemini_3.5_flash":ue.models.gemini35flash,"gemini_3.1_flash_lite":ue.models.gemini31flashLite,gpt_4o_mini:ue.models.gpt4omini,gpt_4o_nano:ue.models.gpt4onano,gpt_41_nano:ue.models.gpt41nano,gpt_5_mini:ue.models.gpt5mini,gpt_5_nano:ue.models.gpt5nano,gpt_41_mini:ue.models.gpt41mini,gpt_41:ue.models.gpt41,o4_mini:ue.models.o4mini,o3_mini:ue.models.o3mini};var am=require("child_process"),Vr=require("crypto"),oe=require("fs"),om=require("fs/promises"),cm=require("stream/promises"),lm=require("http"),um=_e(require("net")),dm=require("os"),De=require("path");function zw(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}o(zw,"projectReportStatsForTelemetry");function Af(t,e,r){t.emit({outcome:e,stats:zw(r)})}o(Af,"emitReportProcessingStatsTelemetry");var Cf=["script","template"],Rf='<script id="playwrightReportBase64" type="application/zip">',Of="</script>";var $p=require("htmlparser2"),Up=_e(lp()),ye=require("node:fs"),Ht=require("node:path"),Fp=require("node:os"),Bp=require("node:crypto");var gt=_e(require("path")),wa=require("fs");var _a=require("path"),as=require("fs");function u0(t,e,r=10){let n=t;for(let s=0;s<r;s++){let i=(0,_a.join)(n,"package.json");if((0,as.existsSync)(i))try{if(JSON.parse((0,as.readFileSync)(i,"utf8")).name===e)return n}catch{}n=(0,_a.join)(n,"..")}}o(u0,"findRepositoryRoot");function up(t,e=10){return u0(t,"checksum-customer-engineering-workspace",e)}o(up,"findCustomerEngineeringRoot");var Ta=_e(gp());var Me=o((t,e)=>{if(t==null||t==="")return e?.default??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:e?.default??!1},"parseBoolean");function yp(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}o(yp,"resolveMaxRRwebBytes");var x0=__dirname,_p=gt.join(__dirname,".."),Ep=(0,wa.existsSync)(_p)?_p:x0;(0,Ta.config)({path:gt.resolve(Ep,".env")});var bp=Me(process.env.CHECKSUM_RUNTIME_DEV_MODE);function A0(){let t=__dirname;for(;!(0,wa.existsSync)(gt.join(t,"package.json"));)t=gt.join(t,"..");return t}o(A0,"findRoot");var Br=A0(),C0=up(Br,10);(0,Ta.config)({path:[Ep,C0].filter(t=>!!t).map(t=>gt.resolve(t,".env")),override:!1});var Ea=Me(process.env.CHECKSUM_RUNTIME_REPO_MODE),R0=Ea?gt.join(Br,"package","pw-report-template.html"):gt.join(Br,"pw-report-template.html"),O0=Me(process.env.CHECKSUM_DEBUG_ANALYTICS),N0=Me(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),M0=yp(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),cs={isDevMode:bp,isRepoMode:Ea,CI:!!process.env.CI,checksumRootFolderBypass:Ea&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(bp?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Br+"/checksumlib.js"},runtimeRoot:Br,playwrightReporter:{htmlReportTemplatePath:R0},bypassProxyForLocalhost:Me(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Me(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Me(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Me(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Me(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:M0},monitoring:{debugAnalytics:O0,logToConsole:N0,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Me(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Me(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Me(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Me(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Me(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var cH=require("@playwright/test/reporter");var ir=require("path");var va=o((t,e,r)=>`v2:${k0(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),k0=o(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var ls=require("fs"),he=_e(require("typescript"));var P0=/^[0-9a-zA-Z]+$/,L0=5;function wp(t){return t?t.length===L0&&P0.test(t):!1}o(wp,"isValidChecksumTestId");var Sa=class{static{o(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),s=n[n.length-1];if(!s||!s.endsWith(".checksum.spec.ts"))return;let a=s.replace(".checksum.spec.ts","").split(" - ").pop();return wp(a)?a:void 0}},Ia=class{static{o(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,ls.existsSync)(e)))try{let n=(0,ls.readFileSync)(e,"utf-8"),s=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),i=new Map,a=o(c=>{if(he.isCallExpression(c)&&this.isTestCall(c.expression)){let l=c.arguments[0];if(l&&he.isCallExpression(l)&&he.isIdentifier(l.expression)&&l.expression.text==="defineChecksumTest"){let u=this.extractDefineChecksumTestArgs(l);u&&wp(u.checksumTestId)&&i.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,a)},"visit");return a(s),r&&i.has(r)?i.get(r):i.size>0?Array.from(i.values())[0]:void 0}catch{return}}isTestCall(e){return he.isIdentifier(e)&&e.text==="test"?!0:he.isPropertyAccessExpression(e)?he.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],s=r[1];if(!n||!s)return;let i=this.extractStringLiteral(n),a=this.extractStringLiteral(s);if(i&&a)return{testTitle:i,checksumTestId:a}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},xa=class{static{o(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new Ia,new Sa]}extract(e,r){for(let n of this.strategies){let s=n.extract(e,r);if(s)return s}}};var Tp=new xa;function us(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?Tp.extract(t.filePath,t.title):void 0)}o(us,"resolveChecksumTestId");var Ca=o((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),Aa=o(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function Ra(t,e,r){let n=[],s=0,i=0,a=Aa(e.expected)+Aa(e.flaky),c=Aa(e.unexpected);for(let l of t){let u=D0(l,r);n.push(u),u.recovered&&i++,u.bug&&(s++,u.outcome==="expected"||u.outcome==="flaky"?a--:u.outcome==="unexpected"&&c--)}return{passed:a,failed:c,bug:s,recovered:i,tests:n}}o(Ra,"computeReportStats");function D0(t,e){let r=us({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=$0(t),s=U0(t.annotations),i=Ca(t.playwrightTestId,e.playwrightIdToMetadata),a=F0(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:i,bug:n,annotations:s,tags:t.tags,outcome:t.outcome,variantKey:va(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...t.projectName?{project:t.projectName}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{},...a!==void 0?{usingChecksumTestIdPlaceholder:a}:{}}}o(D0,"rowToTestWithMetadata");function vp(t,e){let r=t.files,n=o(c=>{let u=us({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=va(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),s=new Map;for(let c of r)for(let l of c.tests)s.set(n(l),l);let i=new Set(s.values()),a={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>i.has(l));for(let l of c.tests)a.total++,l.outcome==="expected"?a.expected++:l.outcome==="unexpected"?a.unexpected++:l.outcome==="flaky"?a.flaky++:a.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...a}}o(vp,"dedupeReportByChecksumTestId");var $0=o(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),U0=o(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),F0=o((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var Sp=o((t,e,r)=>{if(!t)return;let n=r||e,s;if((0,ir.isAbsolute)(t))s=t;else{let i=(0,ir.dirname)(e);s=(0,ir.resolve)(i,t)}return s.replace(n+"/","")},"toRelativeFilePath");var Ip=require("node:util");var ar=8*1024,jr=`
60
+ \u2026 [truncated]`,B0=/[\u001b\u0080-\u009f]/g;function Oa(t){let e=t.replaceAll("\0","");return j0((0,Ip.stripVTControlCharacters)(e))}o(Oa,"sanitizeTestErrorMessage");function j0(t){return t.replace(B0,"")}o(j0,"removeResidualVTControls");function ds(t){let e=Oa(t);if(Buffer.byteLength(e,"utf8")<=ar)return{value:e,truncated:!1};let r=ar-Buffer.byteLength(jr,"utf8"),n="",s=0;for(let i of e){let a=Buffer.byteLength(i,"utf8");if(s+a>r)break;n+=i,s+=a}return{value:n+jr,truncated:!0}}o(ds,"boundTestErrorMessage");var Ap=require("node:crypto");var H0=new Set(["failed","timedOut","interrupted"]),Na=new WeakMap;function Cp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return Na.set(t,new Map),t}o(Cp,"createErrorDetailIndex");function Rp(t,e){try{let r=G0(t);if(!r||z0(r.tests))return!1;for(let n of r.tests){if(!or(n))continue;let s=Pp(n.projectName),i=n.testId;if(s===void 0||!fs(i))continue;let a=V0(n);if(!a)continue;let c=W0(a);c.truncated&&(e.truncatedCount+=1),J0(e,kp(r.fileId,s,i),c.value,Z0(a))}return!0}catch{return!1}}o(Rp,"addTestFileErrorDetails");function Op(t){return or(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}o(Op,"isTestFileErrorDetailCandidate");function Np(t,e,r,n){let s=Pp(r);if(!fs(e)||s===void 0||!fs(n))return;let i=kp(e,s,n);if(!t.ambiguousKeys.has(i))return t.messages.get(i)}o(Np,"getTestErrorMessage");function G0(t){if(!or(t))return;let e=t.fileId,r=t.tests;if(!(!fs(e)||!Array.isArray(r)))return{fileId:e,tests:r}}o(G0,"parseTestFile");function z0(t){return t.length>0&&!t.some(or)}o(z0,"hasOnlyMalformedTests");function V0(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!or(r))return;let n=r.status;if(typeof n!="string"||!H0.has(n))return;let s=r.errors;if(Array.isArray(s))for(let i of s){let a=q0(i);if(a)return a}}o(V0,"extractFinalErrorDetail");function q0(t){if(typeof t=="string"){let n=Mp(t);return n?{message:n}:void 0}if(!or(t))return;let e=xp(t.message,t.value),r=xp(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}o(q0,"normalizeError");function W0(t){let{message:e,frame:r}=t;if(!e)return ds(r??"");if(!r)return ds(e);let n=Buffer.byteLength(e,"utf8");if(n>ar)return ds(e);let s=`
61
+
62
+ `,i=Buffer.byteLength(s,"utf8"),a=Buffer.byteLength(r,"utf8");if(n+i+a<=ar)return{value:`${e}${s}${r}`,truncated:!1};let c=i+Buffer.byteLength(jr,"utf8"),l=ar-n;if(l<c)return{value:e,truncated:!0};let u=K0(r,l-c);return{value:`${e}${s}${u}${jr}`,truncated:!0}}o(W0,"boundNormalizedErrorDetail");function K0(t,e){let r="",n=0;for(let s of t){let i=Buffer.byteLength(s,"utf8");if(n+i>e)break;r+=s,n+=i}return r}o(K0,"utf8Prefix");function Z0(t){let e=(0,Ap.createHash)("sha256");return t.message&&e.update(t.message,"utf8"),t.message&&t.frame&&e.update(`
63
+
64
+ `,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}o(Z0,"digestNormalizedErrorDetail");function Mp(t){let e=Oa(t);return e.trim().length===0?"":e.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}o(Mp,"normalizeErrorText");function J0(t,e,r,n){if(t.ambiguousKeys.has(e))return;let s=Na.get(t);if(s||(s=new Map,Na.set(t,s)),t.messages.get(e)===void 0){t.messages.set(e,r),s.set(e,n);return}s.get(e)!==n&&(t.messages.delete(e),s.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}o(J0,"addErrorDetail");function kp(t,e,r){return JSON.stringify([t,e,r])}o(kp,"createIdentityKey");function xp(...t){for(let e of t){if(typeof e!="string")continue;let r=Mp(e);if(r)return r}}o(xp,"firstMeaningfulString");function or(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(or,"isRecord");function Pp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}o(Pp,"normalizeProjectName");function fs(t){return typeof t=="string"&&t.length>0}o(fs,"isNonEmptyString");var Y0=o(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),X0=o(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function Lp(t,e=8388608){let r=Y0(e),n=0,s=t.tests?.map(i=>{if(i.errorMessage===void 0)return i;let a=X0(i.errorMessage);if(a<=r)return r-=a,i;n+=1;let c={...i};return delete c.errorMessage,c});return{stats:{...t,...s!==void 0?{tests:s}:{}},omittedCount:n}}o(Lp,"applyErrorDetailsPayloadBudget");var Dp=o(t=>Cf.includes(t),"isPayloadTag"),eT=o((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let s=e?Np(e,r.fileId,n.projectName,n.testId):void 0;return{playwrightTestId:n.testId,ok:!!n.ok,outcome:n.outcome,title:n.title,titlePath:n.path??[],filePath:n.location?.file,...n.projectName?{projectName:n.projectName}:{},tags:n.tags??[],annotations:n.annotations??[],...s?{errorMessage:s}:{}}})),"htmlReportToRows"),ps=class t{constructor(e,r,n,s={},i={},a,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=s;this.channel=a;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...i},this.checksumRoot=c||(0,Ht.dirname)((0,Ht.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{o(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,ye.statSync)(this.reportHTMLFilePath)?.size||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(i){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,i)}let r=(0,Ht.join)((0,Fp.tmpdir)(),`pw-report-${(0,Bp.randomUUID)()}.zip`),n=o(()=>{try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{}},"cleanupFile"),s={sigterm:o(()=>{n(),process.exit(143)},"sigterm"),sigint:o(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",s.sigterm),process.once("SIGINT",s.sigint),process.once("exit",s.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let i=Date.now();await this.extractBase64ToFile(r);let a=Date.now()-i;this.channel.debug("Modifying ZIP file...");let c=Date.now(),l=this.modifyZipFile(r),u=Date.now()-c;this.channel.debug("Writing output HTML...");let d=Date.now();await this.writeOutputWithStreamedZip(r);let f=Date.now()-d;return{report_html_bytes:e,extract_ms:a,modify_ms:u,write_ms:f,entry_count:l.entryCount,json_entry_count:l.jsonEntryCount,largest_entry_bytes:l.largestEntryBytes,largest_entry_name:l.largestEntryName,error_details_extracted:l.errorDetailsExtracted,error_details_truncated:l.errorDetailsTruncated,error_detail_parse_failures:l.errorDetailParseFailures,error_detail_identity_conflicts:l.errorDetailIdentityConflicts,error_details_payload_budget_omitted:l.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",s.sigterm),process.removeListener("SIGINT",s.sigint),process.removeListener("exit",s.exit);try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let s=!1,i=!1,a=!1,c=[],l=0,u=(0,ye.createWriteStream)(e);u.on("error",g=>{if(!i){i=!0;try{_.destroyed||_.destroy(),f.end()}catch{}n(g)}});let d=o(()=>{if(l<4)return;let g=c.join("");c.length=0,a||(g=g.replace("data:application/zip;base64,",""),a=!0);let y=Math.floor(g.length/4)*4,E=g.slice(0,y),w=g.slice(y);if(w.length>0?(c.push(w),l=w.length):l=0,E.length>0){let S=Buffer.from(E,"base64");u.write(S)}},"flushBuffer"),f=new $p.Parser({onopentag:o((g,y)=>{Dp(g)&&y.id==="playwrightReportBase64"&&(s=!0)},"onopentag"),ontext:o(g=>{s&&(c.push(g),l+=g.length,l>1024*1024&&d())},"ontext"),onclosetag:o(g=>{if(Dp(g)&&s&&!i){if(i=!0,l>0){let y=c.join("");if(a||(y=y.replace("data:application/zip;base64,","")),y.length>0){let E=Buffer.from(y,"base64");u.write(E)}}try{_.destroyed||_.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:o(g=>{if(!i){i=!0;try{f.end(),_.destroyed||_.destroy(),u.destroyed||u.destroy()}catch{}n(g)}},"onerror")}),_=(0,ye.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});_.on("data",g=>f.write(g.toString())),_.on("end",()=>{if(f.end(),!i){i=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),_.on("error",g=>{if(!i){i=!0;try{f.end(),u.destroyed||u.destroy()}catch{}n(g)}})})}modifyZipFile(e){let r=new Up.default(e),n=r.getEntries(),s=Cp(),i,a,c=0,l=0,u=0,d="";for(let _ of n){if(_.isDirectory||!_.entryName.endsWith(".json"))continue;let g=_.getData().toString("utf8");if(l+=1,g.length>u&&(u=g.length,d=_.entryName),_.entryName==="report.json")i=JSON.parse(g),a=_;else{let y=this.replaceAttachmentPaths(g);_.setData(Buffer.from(y,"utf8"));try{let E=JSON.parse(y);Op(E)&&!Rp(E,s)&&(c+=1)}catch{c+=1}}}if(!i||!a)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&vp(i,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(i),this.report=i;let f=this.extractStats(i,s);return a.setData(Buffer.from(JSON.stringify(i),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:s.messages.size,errorDetailsTruncated:s.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:s.identityConflictCount,errorDetailsPayloadBudgetOmitted:f}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),s=n.replace(".html",".backup.html");(0,ye.copyFileSync)(n,s);let i=(0,ye.createWriteStream)(n);await new Promise((a,c)=>{i.on("error",c),i.write(r),i.write(Rf+"data:application/zip;base64,");let l=(0,ye.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let f=(typeof u=="string"?Buffer.from(u):u).toString("base64");i.write(f)||l.pause()}),i.on("drain",()=>{l.resume()}),l.on("end",()=>{i.write(Of),i.end(()=>a())}),l.on("error",u=>{try{i.destroyed||i.destroy()}catch{}c(u)}),i.on("error",u=>{try{l.destroyed||l.destroy()}catch{}c(u)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(i=>this.pwTestIdToChecksumTestId[i]===e);if(!n)return!0;let s=o(i=>i.some(a=>a.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let i of this.report.files)for(let a of i.tests)if(a.testId===n&&a.projectName===r&&s(a.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return t.templateCache||(t.templateCache=(0,ye.readFileSync)(cs.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=Ra(eT(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:o(i=>Sp(i,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),s=Lp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=s.stats,s.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,Ht.basename)(e)}`:e}handleReportJSON(e){let r={},n=o(s=>{let i=s.testId,a=this.playwrightIdToMetadata[i];a&&(r[i]=a);let c=us({playwrightTestId:s.testId,filePath:s.location?.file,title:s.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(s.checksumTestId=c),s.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(s=>{s.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};var Ma={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},tT={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},kH=Object.fromEntries(Object.entries(tT).map(t=>t.reverse())),rT={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},PH=Object.fromEntries(Object.entries(rT).map(t=>t.reverse()));var LH={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},DH={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var ys=require("fs"),tm=require("path"),rm=require("stream");var jp=o(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var ka=require("fs");var Hp="\x1B[31m",nT="\x1B[33m",sT="\x1B[32m",iT="\x1B[36m",aT="\x1B[2m",oT="\x1B[1m",Hr="\x1B[0m",cT=o(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),lT=new Set(["severity","message","kind","timestamp","_startedAtMs"]),uT=o(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),dT=o(t=>t==="ERROR"||t==="CRITICAL"?Hp:t==="WARNING"?nT:sT,"colorForSeverity"),fT=o(t=>{let e=String(t.severity??"INFO"),r=`${dT(e)}${e.padEnd(5)}${Hr}`,n=t.kind?`${iT}${t.kind}${Hr}`:"",s=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Hp}${d.type??"Error"}: ${d.message??""}${Hr}`})():"",a=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,f])=>!lT.has(d)&&f!=null&&d!=="error"&&typeof f!="object"),l=o(d=>{let f=a.indexOf(d);return f===-1?a.length:f},"rank"),u=c.sort(([d],[f])=>l(d)-l(f)).slice(0,8).map(([d,f])=>`${aT}${d}=${Hr}${f}`).join(" ");return[r,oT+n+Hr,s,u,i].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),pT=o(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Gp=o(t=>{let e=cT()?fT(t):uT(pT(t));(0,ka.writeSync)(1,e+`
65
+ `)},"emitEvent");var zp=o(t=>{(0,ka.writeSync)(2,t.endsWith(`
5
66
  `)?t:`${t}
6
- `)},"writeStderrLine");var jn=a(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),Kn=a((t,e,r)=>{let n=Date.now(),o={timestamp:new Date().toISOString(),kind:t,...e},c=!1,s={set(l){return Object.assign(o,l),s},emit(l){c||(c=!0,l&&Object.assign(o,l),o.duration_ms===void 0&&(o.duration_ms=Date.now()-n),r(o))}};return s},"startHandle"),zn=a((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??jn,n=t.label??"[wide-event]",o=t.sink??(l=>ur(l)),c=a(l=>{if(!e(l))return;let u={severity:dr(l),message:l.message??r(l),...l};try{o(u)}catch(g){try{fr(`${n} emit failed: ${String(g)}`)}catch{}}},"emit");return{emit:c,emitWideEvent:a((l,u={})=>{c({timestamp:new Date().toISOString(),kind:l,...u})},"emitWideEvent"),wideEvent:a((l,u={})=>Kn(l,u,c),"wideEvent"),configureSink:a(l=>{o=l},"configureSink")}},"createWideEvents"),gr=a(t=>t==="true"||t==="1","truthy"),mr=a(()=>gr(process.env.CHECKSUM_WIDE_EVENTS)||gr(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Qe=zn({decide:a(()=>mr(),"decide")}),et=Qe.configureSink,ie=a((t,e={})=>Qe.wideEvent(t,e),"wideEvent"),ve=a((t,e={})=>{Qe.emitWideEvent(t,e)},"emitWideEvent"),Y=a(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function be(t,e){let r;try{r=await t.json()}catch{r=void 0}return Jn({ok:t.ok,status:t.status,body:r},e)}a(be,"assertOkJson");function Jn(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let o=Yn(r==null?void 0:r.message);throw qn(new Error(`${e.resource} failed (HTTP ${t.status})`+(o?`: ${o}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(o=>!r[o]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}a(Jn,"assertJsonBody");function Yn(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}a(Yn,"extractMessage");function qn(t,e){return Object.assign(t,{status:e})}a(qn,"withStatus");var hr=a(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var Xn=a(t=>{var o;let e=t;if((e==null?void 0:e.name)==="TimeoutError")return"timeout";if((e==null?void 0:e.name)==="AbortError")return"no_progress_abort";let r=(o=e==null?void 0:e.cause)==null?void 0:o.code;if(r==="UND_ERR_CONNECT_TIMEOUT"||r==="UND_ERR_HEADERS_TIMEOUT"||r==="UND_ERR_BODY_TIMEOUT")return"timeout";if(typeof r=="string"&&r.length>0)return`network_error:${r}`;let n=typeof(e==null?void 0:e.message)=="string"?e.message:"";return n.startsWith("Upload failed with status")?"http_error":n.startsWith("get-upload-url")?"signed_url_error":n.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),tt=class tt{constructor(e,r,n,o,c=!1,s={start:a(u=>{},"start"),complete:a(u=>{},"complete"),error:a((u,g)=>{},"error")},l){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=o;this.isolationMode=c;this.reporter=s;this.sessionId=l;this.SIGNED_URL_TIMEOUT_MS=3e4;this.MAX_ATTEMPTS=6;this.BACKOFF_BASE_MS=1e3;this.BACKOFF_CAP_MS=16e3;this.PUT_NO_PROGRESS_ABORT_MS=6e4;this.ASSET_DEADLINE_MS=20*6e4}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(s=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,s({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=Date.now()+this.ASSET_DEADLINE_MS,o=ie("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,yr.basename)(r),test_id:e.info.testId,project:e.info.project}),c=[];try{let l=(0,Ne.statSync)(r).size;e.sizeBytes=l,e.loadedBytes=0,e.lastProgress=Date.now(),o.set({size_bytes:l}),this.reporter.start(r);let u;for(let g=1;g<=this.MAX_ATTEMPTS&&!(Date.now()>=n);g++){let y={attempt:g};try{let T=Date.now();if(await this.getSignedURLForUpload(e),y.signed_url_ms=Date.now()-T,!e.uploadURL)throw new Error("No upload URL returned");let v=Date.now();await this.putWithWatchdog(e,r,l),y.put_ms=Date.now()-v,y.loaded_bytes=e.loadedBytes,c.push(y),this.reporter.complete(r),e.complete=!0,o.emit({outcome:"success",attempt_count:c.length,attempts:c,loaded_bytes:e.loadedBytes});return}catch(T){u=T,y.loaded_bytes=e.loadedBytes,y.failure_reason=Xn(T),y.error=Y(T);let v=hr(T==null?void 0:T.status);if(y.non_retryable=v,c.push(y),delete e.uploadURL,v||g>=this.MAX_ATTEMPTS||Date.now()>=n)break;await this.backoff(g,n)}}this.reporter.error(r,u),e.error=!0,o.emit({outcome:"error",attempt_count:c.length,attempts:c,loaded_bytes:e.loadedBytes,size_bytes:e.sizeBytes,deadline_exceeded:Date.now()>=n,error:Y(u)})}catch(s){this.reporter.error(r,s),e.error=!0,o.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:c.length,attempts:c,error:Y(s)})}}async putWithWatchdog(e,r,n){var p;let o=e.uploadURL;if(!o)throw new Error("No upload URL returned");let c=new AbortController,s=this.uploadTimeout??void 0;e.loadedBytes=0,e.lastProgress=Date.now();let l=0,u=Date.now(),g=setInterval(()=>{let h=e.loadedBytes??0;h>l?(l=h,u=Date.now()):Date.now()-u>this.PUT_NO_PROGRESS_ABORT_MS&&c.abort()},1e4),y=s!==void 0?setTimeout(()=>c.abort(new DOMException("upload attempt timeout","TimeoutError")),s):void 0,T=(0,Ne.createReadStream)(r),v=0,A=new TransformStream({transform(h,E){v+=h.byteLength,v>(e.loadedBytes??0)&&(e.lastProgress=Date.now()),e.loadedBytes=v,e.sizeBytes=n,E.enqueue(h)}}),d=Er.Readable.toWeb(T).pipeThrough(A),f={method:"PUT",headers:{"Content-Type":lr[e.info.type]??""},body:d,duplex:"half",signal:c.signal};try{let h=await fetch(o,f);if(!h.ok)throw await((p=h.body)==null?void 0:p.cancel()),Object.assign(new Error(`Upload failed with status ${h.status}`),{status:h.status});e.loadedBytes=n,e.response=Promise.resolve(await h.text())}finally{clearInterval(g),clearTimeout(y),T.destroy()}}async backoff(e,r){let n=Math.min(this.BACKOFF_CAP_MS,this.BACKOFF_BASE_MS*2**(e-1)),o=n/2+Math.random()*(n/2),c=Math.max(0,Math.min(o,r-Date.now()));c>0&&await new Promise(s=>setTimeout(s,c))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let o=JSON.stringify(e.info),c=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,s={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},l=await fetch(c,{method:"POST",headers:s,body:o,signal:r.signal}),{url:u}=await be(l,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=u}catch(o){throw delete e.uploadURL,o}finally{clearTimeout(n)}}};a(tt,"TestAssetUploader");var we=tt;function Tr(t,e,r=Date.now()){if(t.length===0)return!1;let n=t.reduce((o,c)=>Math.max(o,c.lastProgress??0),0);return n>0&&r-n>e}a(Tr,"isUploadStalled");var nt=class nt{constructor(){}sendToCLI(...e){console.log(`{trm}${e.map(r=>r.toString()).join(`,
7
- `)}{/trm}`)}event(e,r){return new Promise(n=>{let o=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${o}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}};a(nt,"CLIChannel");var rt=nt,ot=class ot{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.MAX_UPLOADS=15;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=600*1e3;this.UPLOAD_STALL_TIMEOUT=600*1e3;this.WATCH_TIMEOUT=120*1e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.reportComplete=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new rt,et(n=>this.channel.wideEvent(n)),this.testAssetUploader=new we(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:a(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:a(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,k.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(o){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,o)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:a((n,o)=>this.channel.trace("Upload Failed",{filename:n,error:o}),"error")},e.sessionId),setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL),this.listenForMessages(),this.startServer()}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,o]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+o),n){case"report":if(this.testRunEndTime=Date.now(),o!=="false")try{let c=Buffer.from(o??"","base64").toString("utf-8"),s=JSON.parse(c);await this.handleReport(s)}catch(c){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(c)),this.reportComplete=!0}else this.reportComplete=!0;this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,Rr.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,V.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=Re.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,_r.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:o,openReportCriteria:c,checksumRoot:s,projectRoot:l,isUploadReport:u,dedupeByChecksumTestId:g}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,V.dirname)(r),u);let y=ie("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!u});try{let T=await this.readMetadataFile(n),v=new Ae(r,this.config.sessionId,this.pwTestIdToChecksumTestId,T,{hosted:!this.isolationMode,...g?{dedupeByChecksumTestId:g}:{}},this.channel,s,l,this.checksumTestIdToUsingPlaceholder),A=this.initAsset({type:"report",path:""});this.reportAsset=A;try{let p=await v.process();A.info.path=v.getProcessedFilePath(),y.set({processed_path:A.info.path,...p}),this.uploadAsset(A)}catch(p){this.channel.debug("Error processing report, "+p.message),A.error=!0,y.set({error:Y(p)})}let d=v.getReportsStats();this.stats=d,y.emit({outcome:A.error?"error":"success",stats:d}),this.channel.debug("Checking watch assets");let f=this.watchAssets.filter(p=>!(p.type!=="trace"||v.testHasTrace(p.testId??"",p.project??"")));f.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(f.map(p=>p.path)))),this.watchAssets=this.watchAssets.filter(p=>p.type!=="trace"||v.testHasTrace(p.testId??"",p.project??""))}catch(T){this.channel.debug("Error processing report, "+this.stringify(T)),this.reportAsset&&(this.reportAsset.error=!0),y.emit({outcome:"error",error:Y(T)})}finally{if((c==="always"||c==="on-failure"&&o)&&await this.serveReport(r),n&&(0,k.existsSync)(n))try{(0,k.unlinkSync)(n)}catch(v){console.error(`Error deleting checksum metadata file ${n}: ${v.message}`)}}}async uploadReportData(e,r){let n=(0,V.join)(e,"data");try{let o=(0,k.readdirSync)(n),c=r?[".webm"]:[".zip",".webm"],s=o.filter(l=>!c.includes((0,V.extname)(l)));this.channel.debug("Preparing to upload report data files,"+s);for(let l of s)this.channel.debug("Uploading report data file,"+l),this.addAsset({type:"report-data-file",fileName:l,path:`${n}/${l}`})}catch(o){this.channel.debug(`Error reading/adding report data files from dir ${n}`+o.message)}}shutdown(){this.channel.debug("Received shutdown message from CLI"),this.server.close(),process.exit(0)}async monitorUploadsCompletion(){var e;if(!this.reportComplete&&this.reportAsset&&(this.reportAsset.complete||this.reportAsset.error)){this.reportComplete=!0;let r="";try{let n=JSON.stringify(this.stats),o=`checksum-stats-${(0,ge.randomBytes)(8).toString("hex")}.json`;r=(0,V.join)((0,vr.tmpdir)(),o),(0,k.writeFileSync)(r,n,"utf-8"),this.channel.debug(`Stats written to temporary file: ${r}`)}catch(n){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${n.message}`)}this.channel.event("report-complete",`${(e=this.reportAsset)!=null&&e.complete?"true":"false"}:${r}`)}if(!this.processingInProgress&&this.reportComplete&&(this.assets.filter(r=>r.complete||r.error).length===this.assets.length||this.isUploadStalled())&&(this.watchAssets.length===0||this.testRunEndTime&&Date.now()-this.testRunEndTime>this.WATCH_TIMEOUT)){let r=Date.now(),n=this.assets.filter(l=>!l.complete&&!l.error);this.assets.forEach(l=>{!l.complete&&!l.error&&(l.error=!0)});let o=this.assets.find(l=>l.error)?"uploads-complete-with-errors":"uploads-complete",c=this.assets.filter(l=>l.error);ve("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:c.length>0?"error":"success",decision:o,total_assets:this.assets.length,completed:this.assets.filter(l=>l.complete).length,errored:c.length,stalled:n.length>0,stalled_count:n.length,watch_remaining:this.watchAssets.length,report_complete:this.reportComplete,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:c.map(l=>this.assetSnapshot(l,r))});let s=o==="uploads-complete"?{}:{uploadErrors:this.assets.filter(l=>l.error).map(l=>{try{return JSON.stringify(l)}catch{return l.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:Date.now()};try{this.cleanUp()}catch(l){this.channel.debug("cleanUp failed (ignored): "+(l==null?void 0:l.message))}this.channel.event(o,JSON.stringify(s));return}await De(1e3),this.monitorUploadsCompletion()}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,V.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,V.dirname)(r.info.path);break}e&&(0,k.rmSync)(e,{recursive:!0,force:!0})}isUploadStalled(){let e=Tr(this.assets,this.UPLOAD_STALL_TIMEOUT);if(e&&(this.channel.log("Uploads are stalled"),!this.stallEventEmitted)){this.stallEventEmitted=!0;let r=Date.now(),n=this.assets.filter(o=>!o.complete&&!o.error);ve("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:n.length,pending_assets:n.map(o=>this.assetSnapshot(o,r))})}return e}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,Cr.createServer)((r,n)=>{let o=a(s=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(s)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let c="";r.on("data",s=>{c+=s.toString()}),r.on("end",()=>{let s;try{s=JSON.parse(c)}catch{o("Invalid body");return}let{type:l,payload:u,watch:g}=s;switch(this.channel.debug(`Server received message, ${l}, ${this.stringify(u)}`),l){case"asset":if(!u.path||!u.type){o("Missing arguments");return}g?this.watchAsset(u):this.processAsset(u);break;case"testInfo":if(!u.pwTestId||!u.checksumTestId){o("Missing arguments");return}this.pwTestIdToChecksumTestId[u.pwTestId]=u.checksumTestId,u.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[u.checksumTestId]=u.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let y=u;if(!y.checksumTestId||!u.data){o("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...y}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(u));break;case"runProgress":this.forwardProgress(u);break;default:o("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(o){this.channel.debug("Failed to send run progress: "+(o==null?void 0:o.message))}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let c=(r/e*100).toFixed(2);this.channel.event("upload-progress",c)}let n=this.assets.filter(c=>!c.uploadStarted);if(n.length===0)return;let o=a(()=>this.assets.filter(c=>c.uploadStarted&&!c.complete&&!c.error).length,"getNumOfActiveUploads");if(!(o()>=this.MAX_UPLOADS))for(;n.length>0&&o()<this.MAX_UPLOADS;){let c=n.pop();if(c===void 0)break;this.uploadAsset(c)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:o})=>n+(o??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:o})=>n+(o??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}async getSignedURLForUpload(e){try{let{apiKey:r,sessionId:n,apiURL:o}=this.config,c=e.info,s=await fetch(`${o}/client-api/test-runs/${n}/get-upload-url`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:r},body:JSON.stringify(c)}),{url:l}=await be(s,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l}catch(r){this.channel.debug("Error getting signed URL for artifact"+this.stringify(r))}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=a(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(o=>o.path!==e.path))},"waitForCompletion");if((0,k.existsSync)(e.path))r();else{let n=(0,V.dirname)(e.path),o=(0,V.basename)(e.path),c=!1,s=(0,k.watch)(n,(l,u)=>{(async()=>{if(!(u!==o||c))try{this.channel.debug("Watched file changed "+e.path),c=!0,await r()}finally{s.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,o=1){return new Promise(c=>{let s=Date.now(),l=0,u=a(()=>{if(!(0,k.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),c(!1);return}let g=(0,k.statSync)(e).size;if(g===l){if(o>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${g}, equalSizeValidationCountLeft: ${o}`),o--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${g}`),c(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${l}, current size: ${g}`),Date.now()-s>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),c(!0);return}l=g,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,ge.createHash)("sha1"),n=(0,k.createReadStream)(e);return await(0,Sr.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await De(1e3),n=ie("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let o=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),o=e.replace(".zip",".actual.zip"),(0,k.renameSync)(e,o);let l="checksum-playwright-trace:"+Date.now().toString()+(0,ge.randomBytes)(1024).toString("hex");(0,k.writeFileSync)(e,l)}let s=await a(async()=>await this.calculateFileSha1Streaming(e)+(0,V.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${s}, sending for upload...`),this.addAsset({type:"report-data-file",path:o,...r!==void 0?{testId:r}:{},fileName:s}),n==null||n.emit({outcome:"success",file_name:s})}catch(o){let c=String(o);this.channel.debug("Error processing trace file"+c),this.channel.trace("Trace Processing Error",{error:c}),n==null||n.emit({outcome:"error",error:Y(o)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=Ar.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let o=n.address().port;n.close(()=>{e(o)})})})}};a(ot,"TestRunMonitor");var xe=ot,br;try{br=JSON.parse(process.argv[2]??"")}catch(t){console.log("Error starting test run monitor",t),process.exit(1)}var Ir;new xe(br,((Ir=process.argv)==null?void 0:Ir[3])==="isolated");0&&(module.exports={TestRunMonitor});
67
+ `)},"writeStderrLine");var mT=o(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),hT=o((t,e,r)=>{let n=Date.now(),s={timestamp:new Date().toISOString(),kind:t,...e},i=!1,a={set(c){return Object.assign(s,c),a},emit(c){i||(i=!0,c&&Object.assign(s,c),s.duration_ms===void 0&&(s.duration_ms=Date.now()-n),r(s))}};return a},"startHandle"),gT=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??mT,n=t.label??"[wide-event]",s=t.sink??(c=>Gp(c)),i=o(c=>{if(!e(c))return;let l={severity:jp(c),message:c.message??r(c),...c};try{s(l)}catch(u){try{zp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:i,emitWideEvent:o((c,l={})=>{i({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:o((c,l={})=>hT(c,l,i),"wideEvent"),configureSink:o(c=>{s=c},"configureSink")}},"createWideEvents"),Vp=o(t=>t==="true"||t==="1","truthy"),qp=o(()=>Vp(process.env.CHECKSUM_WIDE_EVENTS)||Vp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Pa=gT({decide:o(()=>qp(),"decide")}),La=Pa.configureSink,cr=o((t,e={})=>Pa.wideEvent(t,e),"wideEvent"),ms=o((t,e={})=>{Pa.emitWideEvent(t,e)},"emitWideEvent"),yt=o(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function hs(t,e){let r;try{r=await t.json()}catch{r=void 0}return yT({ok:t.ok,status:t.status,body:r},e)}o(hs,"assertOkJson");function yT(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let s=_T(r?.message);throw bT(new Error(`${e.resource} failed (HTTP ${t.status})`+(s?`: ${s}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(s=>!r[s]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}o(yT,"assertJsonBody");function _T(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}o(_T,"extractMessage");function bT(t,e){return Object.assign(t,{status:e})}o(bT,"withStatus");var Wp=o(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var Kp={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:6e4,min:5e3,max:6e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function ET(t,e,r,n){let s=parseInt(t??"",10);return Number.isFinite(s)?Math.min(n,Math.max(r,s)):e}o(ET,"clampInt");function Da(t){let e={};for(let r of Object.keys(Kp)){let n=Kp[r];e[r]=ET(t[n.env],n.fallback,n.min,n.max)}return e}o(Da,"resolveUploadTunables");var Zp=Da({});function Gr(t,e,r,n){t.loadedBytes=e;let s=Math.max(t.committedBytes??0,e);t.committedBytes=s;let i=t.progressAnchorBytes??0;return t.lastProgress===void 0&&s>0||s-i>=r?(t.lastProgress=n,t.progressAnchorBytes=s,!0):!1}o(Gr,"recordProgress");function $a(t){t.loadedBytes=0}o($a,"resetAttemptBytes");var Jp=require("fs"),Yp=require("stream");var Xp=o(t=>t===308,"isResumeIncomplete"),Ua=o(t=>t===200||t===201,"isDone"),wT=o(t=>t===408||t===429||t>=500,"isRetryableStatus"),Qp=o((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),Fa=o(async t=>{let e=t.body;e&&await e.cancel().catch(()=>{})},"drainBody"),_t=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{o(this,"ResumableUploadError")}};async function TT(t,e,r,n){let s=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await Fa(s),!Ua(s.status))throw new _t(`resumable init failed with status ${s.status}`,s.status);let i=s.headers.get("Location");if(!i)throw new _t("resumable init returned no Location");return i}o(TT,"initResumableSession");async function vT(t,e,r,n){let s=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await Fa(s),Ua(s.status))return{done:!0,offset:e};if(!Xp(s.status))throw new _t(`offset query failed with status ${s.status}`,s.status);return{done:!1,offset:Qp(s.headers.get("Range"),0)}}o(vT,"queryCommittedOffset");function ST(t,e,r,n){if(r<=0)return;let s=(0,Jp.createReadStream)(t,{start:e}),i=e,a=new TransformStream({transform(c,l){i+=c.byteLength,n?.(i),l.enqueue(c)},flush(){s.destroy()}});return Yp.Readable.toWeb(s).pipeThrough(a)}o(ST,"buildPutBody");async function IT(t,e,r,n){let{filePath:s,size:i,fetchImpl:a,onProgress:c}=t,l=Math.max(i-1,0),u=ST(s,r,i-r,c),d={method:"PUT",headers:{"Content-Range":`bytes ${r}-${l}/${i}`,"Content-Length":String(i-r)},duplex:"half",signal:n,...u?{body:u}:{}},f=await a(e,d);if(await Fa(f),Ua(f.status))return c?.(i),{done:!0,offset:i};if(Xp(f.status)){let _=Qp(f.headers.get("Range"),r);return c?.(_),{done:!1,offset:_}}throw new _t(`resumable PUT failed with status ${f.status}`,f.status)}o(IT,"putFrom");async function xT(t,e,r,n){let s=r;for(;;){let i=await IT(t,e,s,n);if(i.done)return;if(i.offset<=s)throw new _t("resumable PUT made no progress");s=i.offset}}o(xT,"driveToCompletion");async function AT(t,e,r){if(e)return e;if(!t.target.initUrl)throw new _t("no resumable target provided");return TT(t.target.initUrl,t.contentType,t.fetchImpl,r)}o(AT,"ensureSession");async function CT(t,e,r,n){if(r<=1)return 0;let s=await vT(e,t.size,t.fetchImpl,n);return s.done?void 0:s.offset}o(CT,"resolveStartOffset");var RT=o(t=>{let e=t?.status;return e!==void 0&&!wT(e)},"isPermanent"),OT=o(t=>Math.min(1e3*2**(t-1),16e3)*(.5+Math.random()/2),"backoffMs");async function NT(t,e,r){let n=t.makeSignal(),s=await AT(t,e,n),i=await CT(t,s,r,n);return i===void 0?(t.onProgress?.(t.size),s):(await xT(t,s,i,n),s)}o(NT,"runAttempt");async function em(t){let e=t.target.sessionUrl,r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await NT(t,e,n);return}catch(s){if(r=s,RT(s)||n>=t.maxAttempts)break;e=t.target.sessionUrl,await t.sleep(OT(n))}throw r instanceof Error?r:new _t(`resumable upload failed: ${String(r)}`)}o(em,"uploadResumable");var MT=o(t=>{let e=t;if(e?.name==="TimeoutError")return"timeout";if(e?.name==="AbortError")return"no_progress_abort";let r=e?.cause?.code;if(r==="UND_ERR_CONNECT_TIMEOUT"||r==="UND_ERR_HEADERS_TIMEOUT"||r==="UND_ERR_BODY_TIMEOUT")return"timeout";if(typeof r=="string"&&r.length>0)return`network_error:${r}`;let n=typeof e?.message=="string"?e.message:"";return n.startsWith("Upload failed with status")?"http_error":n.startsWith("get-upload-url")?"signed_url_error":n.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),gs=class{constructor(e,r,n,s,i=!1,a={start:o(u=>{},"start"),complete:o(u=>{},"complete"),error:o((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=s;this.isolationMode=i;this.reporter=a;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.BACKOFF_BASE_MS=1e3;this.BACKOFF_CAP_MS=16e3;this.tunables=l.tunables??Zp,this.fetchImpl=l.fetchImpl??globalThis.fetch,this.now=l.now??Date.now,this.MAX_ATTEMPTS=this.tunables.maxAttempts,this.PUT_NO_PROGRESS_ABORT_MS=this.tunables.noProgressAbortMs,this.ASSET_DEADLINE_MS=this.tunables.assetDeadlineMs,this.MIN_PROGRESS_BYTES=this.tunables.minProgressBytes}static{o(this,"TestAssetUploader")}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(a=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,a({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,s=cr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,tm.basename)(r),test_id:e.info.testId,project:e.info.project}),i=[];try{let c=(0,ys.statSync)(r).size;e.sizeBytes=c,e.loadedBytes=0,e.committedBytes=0,s.set({size_bytes:c}),this.reporter.start(r);let l;for(let u=1;u<=this.MAX_ATTEMPTS&&!(this.now()>=n);u++){let d={attempt:u};try{let f=this.now();if(await this.getSignedURLForUpload(e),d.signed_url_ms=this.now()-f,!e.uploadURL)throw new Error("No upload URL returned");let _=this.now();d.resumable=e.resumable===!0,e.resumable?await this.putResumable(e,r,c,n):await this.putWithWatchdog(e,r,c),d.put_ms=this.now()-_,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,i.push(d),this.reporter.complete(r),e.complete=!0,s.emit({outcome:"success",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes});return}catch(f){l=f,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,d.failure_reason=MT(f),d.error=yt(f);let _=Wp(f?.status);if(d.non_retryable=_,i.push(d),delete e.uploadURL,_||u>=this.MAX_ATTEMPTS||this.now()>=n||e.resumable)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,s.emit({outcome:"error",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:yt(l)})}catch(a){this.reporter.error(r,a),e.error=!0,s.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:i.length,attempts:i,error:yt(a)})}}async putWithWatchdog(e,r,n){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");let i=new AbortController,a=this.uploadTimeout??void 0;$a(e);let c=0,l=Date.now(),u=setInterval(()=>{let I=e.loadedBytes??0;I>c?(c=I,l=Date.now()):Date.now()-l>this.PUT_NO_PROGRESS_ABORT_MS&&i.abort()},1e4),d=a!==void 0?setTimeout(()=>i.abort(new DOMException("upload attempt timeout","TimeoutError")),a):void 0,f=(0,ys.createReadStream)(r),_=0,g=this.MIN_PROGRESS_BYTES,y=this.now,E=new TransformStream({transform(I,m){_+=I.byteLength,e.sizeBytes=n,Gr(e,_,g,y()),m.enqueue(I)}}),w=rm.Readable.toWeb(f).pipeThrough(E),S={method:"PUT",headers:{"Content-Type":Ma[e.info.type]??""},body:w,duplex:"half",signal:i.signal};try{let I=await this.fetchImpl(s,S);if(!I.ok)throw await I.body?.cancel(),Object.assign(new Error(`Upload failed with status ${I.status}`),{status:I.status});Gr(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await I.text())}finally{clearInterval(u),clearTimeout(d),f.destroy()}}async putResumable(e,r,n,s){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");$a(e);let a=this.uploadTimeout??this.tunables.uploadTimeoutMs;await em({target:{initUrl:i},filePath:r,size:n,contentType:Ma[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:o(()=>AbortSignal.timeout(a),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:s,now:this.now,sleep:o(c=>new Promise(l=>setTimeout(l,c)),"sleep"),onProgress:o(c=>Gr(e,c,this.MIN_PROGRESS_BYTES,this.now()),"onProgress")}),Gr(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve("OK")}async backoff(e,r){let n=Math.min(this.BACKOFF_CAP_MS,this.BACKOFF_BASE_MS*2**(e-1)),s=n/2+Math.random()*(n/2),i=Math.max(0,Math.min(s,r-this.now()));i>0&&await new Promise(a=>setTimeout(a,i))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let s=JSON.stringify(e.info),i=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,a={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(i,{method:"POST",headers:a,body:s,signal:r.signal}),{url:l,resumable:u}=await hs(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(s){throw delete e.uploadURL,s}finally{clearTimeout(n)}}};function nm(t,e,r=Date.now()){if(t.length===0)return!1;let n=t.reduce((s,i)=>Math.max(s,i.lastProgress??0),0);return n>0&&r-n>e}o(nm,"isUploadStalled");var sm=require("module");var kT=(0,sm.createRequire)(__filename),zr;function im(t){if(zr)return zr;try{let e=kT("undici"),r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4}),n=e.fetch;zr=o(((s,i)=>n(s,{...i,dispatcher:r})),"cachedFetch")}catch{zr=globalThis.fetch}return zr}o(im,"createMonitorFetch");var Ba=class{static{o(this,"CLIChannel")}constructor(){}sendToCLI(...e){console.log(`{trm}${e.map(r=>r.toString()).join(`,
68
+ `)}{/trm}`)}event(e,r){return new Promise(n=>{let s=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${s}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},_s=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunables=Da(process.env);this.MAX_UPLOADS=this.tunables.maxConcurrentUploads;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=this.tunables.uploadTimeoutMs;this.UPLOAD_STALL_TIMEOUT=this.tunables.stallTimeoutMs;this.WATCH_TIMEOUT=120*1e3;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.reportComplete=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Ba,La(n=>this.channel.wideEvent(n)),this.testAssetUploader=new gs(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:o(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:o(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,oe.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(s){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,s)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:o((n,s)=>this.channel.trace("Upload Failed",{filename:n,error:s}),"error")},e.sessionId,{fetchImpl:im(this.tunables),tunables:this.tunables}),setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL),this.listenForMessages(),this.startServer()}static{o(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,s]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+s),n){case"report":if(this.testRunEndTime=Date.now(),s!=="false")try{let i=Buffer.from(s??"","base64").toString("utf-8"),a=JSON.parse(i);await this.handleReport(a)}catch(i){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(i)),this.reportComplete=!0}else this.reportComplete=!0;this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,om.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,De.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=cs.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,am.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:s,openReportCriteria:i,checksumRoot:a,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,De.dirname)(r),l);let d=cr("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!l});try{let f=await this.readMetadataFile(n),_=new ps(r,this.config.sessionId,this.pwTestIdToChecksumTestId,f,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,a,c,this.checksumTestIdToUsingPlaceholder),g=this.initAsset({type:"report",path:""});this.reportAsset=g;try{let w=await _.process();g.info.path=_.getProcessedFilePath(),d.set({processed_path:g.info.path,...w}),this.uploadAsset(g)}catch(w){this.channel.debug("Error processing report, "+w.message),g.error=!0,d.set({error:yt(w)})}let y=_.getReportsStats();this.stats=y,Af(d,g.error?"error":"success",y),this.channel.debug("Checking watch assets");let E=this.watchAssets.filter(w=>!(w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??"")));E.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(E.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??""))}catch(f){this.channel.debug("Error processing report, "+this.stringify(f)),this.reportAsset&&(this.reportAsset.error=!0),d.emit({outcome:"error",error:yt(f)})}finally{if((i==="always"||i==="on-failure"&&s)&&await this.serveReport(r),n&&(0,oe.existsSync)(n))try{(0,oe.unlinkSync)(n)}catch(_){console.error(`Error deleting checksum metadata file ${n}: ${_.message}`)}}}async uploadReportData(e,r){let n=(0,De.join)(e,"data");try{let s=(0,oe.readdirSync)(n),i=r?[".webm"]:[".zip",".webm"],a=s.filter(c=>!i.includes((0,De.extname)(c)));this.channel.debug("Preparing to upload report data files,"+a);for(let c of a)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(s){this.channel.debug(`Error reading/adding report data files from dir ${n}`+s.message)}}shutdown(){this.channel.debug("Received shutdown message from CLI");try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}setTimeout(()=>process.exit(0),2e3).unref(),process.exit(0)}finalizeBudgetExceeded(){return this.testRunEndTime!==void 0&&Date.now()-this.testRunEndTime>this.FINALIZE_BUDGET}async monitorUploadsCompletion(){let e=this.finalizeBudgetExceeded();if(!this.reportComplete&&(e||this.reportAsset&&(this.reportAsset.complete||this.reportAsset.error))){this.reportComplete=!0;let n="";try{let s=JSON.stringify(this.stats),i=`checksum-stats-${(0,Vr.randomBytes)(8).toString("hex")}.json`;n=(0,De.join)((0,dm.tmpdir)(),i),(0,oe.writeFileSync)(n,s,"utf-8"),this.channel.debug(`Stats written to temporary file: ${n}`)}catch(s){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${s.message}`)}this.channel.event("report-complete",`${this.reportAsset?.complete?"true":"false"}:${n}`)}if(!this.processingInProgress&&this.reportComplete&&(this.assets.filter(n=>n.complete||n.error).length===this.assets.length||this.isUploadStalled())&&(this.watchAssets.length===0||this.testRunEndTime&&Date.now()-this.testRunEndTime>this.WATCH_TIMEOUT)||e){let n=Date.now(),s=this.assets.filter(l=>!l.complete&&!l.error);this.assets.forEach(l=>{!l.complete&&!l.error&&(l.error=!0)});let i=this.assets.some(l=>l.error)?"uploads-complete-with-errors":"uploads-complete",a=this.assets.filter(l=>l.error);ms("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:a.length>0?"error":"success",decision:i,total_assets:this.assets.length,completed:this.assets.filter(l=>l.complete).length,errored:a.length,stalled:s.length>0,stalled_count:s.length,finalize_reason:e?"budget":s.length>0?"stall":"complete",finalize_budget_ms:this.FINALIZE_BUDGET,watch_remaining:this.watchAssets.length,report_complete:this.reportComplete,upload_finalize_ms:this.testRunEndTime?n-this.testRunEndTime:void 0,errored_assets:a.map(l=>this.assetSnapshot(l,n))});let c=i==="uploads-complete"?{}:{uploadErrors:this.assets.filter(l=>l.error).map(l=>{try{return JSON.stringify(l)}catch{return l.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:Date.now()};try{this.cleanUp()}catch(l){this.channel.debug("cleanUp failed (ignored): "+l?.message)}this.channel.event(i,JSON.stringify(c));return}await vs(1e3),this.monitorUploadsCompletion()}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,De.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,De.dirname)(r.info.path);break}e&&(0,oe.rmSync)(e,{recursive:!0,force:!0})}isUploadStalled(){let e=nm(this.assets,this.UPLOAD_STALL_TIMEOUT);if(e&&(this.channel.log("Uploads are stalled"),!this.stallEventEmitted)){this.stallEventEmitted=!0;let r=Date.now(),n=this.assets.filter(s=>!s.complete&&!s.error);ms("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:n.length,pending_assets:n.map(s=>this.assetSnapshot(s,r))})}return e}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,lm.createServer)((r,n)=>{let s=o(a=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(a)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let i="";r.on("data",a=>{i+=a.toString()}),r.on("end",()=>{let a;try{a=JSON.parse(i)}catch{s("Invalid body");return}let{type:c,payload:l,watch:u}=a;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){s("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){s("Missing arguments");return}this.pwTestIdToChecksumTestId[l.pwTestId]=l.checksumTestId,l.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[l.checksumTestId]=l.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let d=l;if(!d.checksumTestId||!l.data){s("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...d}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(l));break;case"runProgress":this.forwardProgress(l);break;default:s("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(s){this.channel.debug("Failed to send run progress: "+s?.message)}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let i=(r/e*100).toFixed(2);this.channel.event("upload-progress",i)}let n=this.assets.filter(i=>!i.uploadStarted);if(n.length===0)return;let s=o(()=>this.assets.filter(i=>i.uploadStarted&&!i.complete&&!i.error).length,"getNumOfActiveUploads");if(!(s()>=this.MAX_UPLOADS))for(;n.length>0&&s()<this.MAX_UPLOADS;){let i=n.pop();if(i===void 0)break;this.uploadAsset(i)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:s})=>n+(s??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:s})=>n+(s??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}async getSignedURLForUpload(e){try{let{apiKey:r,sessionId:n,apiURL:s}=this.config,i=e.info,a=await fetch(`${s}/client-api/test-runs/${n}/get-upload-url`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:r},body:JSON.stringify(i)}),{url:c}=await hs(a,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=c}catch(r){this.channel.debug("Error getting signed URL for artifact"+this.stringify(r))}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=o(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(s=>s.path!==e.path))},"waitForCompletion");if((0,oe.existsSync)(e.path))r();else{let n=(0,De.dirname)(e.path),s=(0,De.basename)(e.path),i=!1,a=(0,oe.watch)(n,(c,l)=>{(async()=>{if(!(l!==s||i))try{this.channel.debug("Watched file changed "+e.path),i=!0,await r()}finally{a.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,s=1){return new Promise(i=>{let a=Date.now(),c=0,l=s,u=o(()=>{if(!(0,oe.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),i(!1);return}let d=(0,oe.statSync)(e).size;if(d===c){if(l>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${d}, equalSizeValidationCountLeft: ${l}`),l--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${d}`),i(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-a>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),i(!0);return}c=d,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,Vr.createHash)("sha1"),n=(0,oe.createReadStream)(e);return await(0,cm.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await vs(1e3),n=cr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let s=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),s=e.replace(".zip",".actual.zip"),(0,oe.renameSync)(e,s);let c="checksum-playwright-trace:"+Date.now().toString()+(0,Vr.randomBytes)(1024).toString("hex");(0,oe.writeFileSync)(e,c)}let a=await o(async()=>await this.calculateFileSha1Streaming(e)+(0,De.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${a}, sending for upload...`),this.addAsset({type:"report-data-file",path:s,...r!==void 0?{testId:r}:{},fileName:a}),n?.emit({outcome:"success",file_name:a})}catch(s){let i=String(s);this.channel.debug("Error processing trace file"+i),this.channel.trace("Trace Processing Error",{error:i}),n?.emit({outcome:"error",error:yt(s)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=um.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let s=n.address().port;n.close(()=>{e(s)})})})}},fm;try{fm=JSON.parse(process.argv[2]??"")}catch(t){console.log("Error starting test run monitor",t),process.exit(1)}new _s(fm,process.argv?.[3]==="isolated");0&&(module.exports={TestRunMonitor});
69
+ /*! Bundled license information:
70
+
71
+ @langchain/core/dist/utils/js-sha256/hash.js:
72
+ (**
73
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
74
+ *
75
+ * @version 0.11.1
76
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
77
+ * @copyright Chen, Yi-Cyuan 2014-2025
78
+ * @license MIT
79
+ *)
80
+
81
+ @langchain/core/dist/utils/fast-json-patch/src/helpers.js:
82
+ (*!
83
+ * https://github.com/Starcounter-Jack/JSON-Patch
84
+ * (c) 2017-2022 Joachim Wester
85
+ * MIT licensed
86
+ *)
87
+
88
+ @langchain/core/dist/utils/fast-json-patch/src/duplex.js:
89
+ (*!
90
+ * https://github.com/Starcounter-Jack/JSON-Patch
91
+ * (c) 2013-2021 Joachim Wester
92
+ * MIT license
93
+ *)
94
+
95
+ @langchain/core/dist/utils/sax-js/sax.js:
96
+ (*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
97
+ */