@checksum-ai/runtime 4.14.0 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/checksum-progress-reporter.js +189 -4
- package/checksumlib.js +73 -73
- package/cli.js +400 -172
- package/index.js +354 -126
- package/package.json +3 -3
- package/test-run-monitor.js +196 -12
package/test-run-monitor.js
CHANGED
|
@@ -1,12 +1,196 @@
|
|
|
1
|
-
"use strict";var Fr=Object.create;var le=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var i=(e,t)=>le(e,"name",{value:t,configurable:!0});var W=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Gr=(e,t)=>{for(var r in t)le(e,r,{get:t[r],enumerable:!0})},st=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hr(t))!$r.call(e,o)&&o!==r&&le(e,o,{get:()=>t[o],enumerable:!(n=Br(t,o))||n.enumerable});return e};var de=(e,t,r)=>(r=e!=null?Fr(Wr(e)):{},st(t||!e||!e.__esModule?le(r,"default",{value:e,enumerable:!0}):r,e)),jr=e=>st(le({},"__esModule",{value:!0}),e);var Pe=W((jo,ut)=>{ut.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 Ee=W(ft=>{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 Kr(e){return function(...t){return t.length&&(e=e.replace(/\{(\d)\}/g,(r,n)=>t[n]||"")),new Error("ADM-ZIP: "+e)}}i(Kr,"E");for(let e of Object.keys(pt))ft[e]=Kr(pt[e])});var Et=W((Ko,yt)=>{var Zr=require("fs"),P=require("path"),gt=Pe(),Jr=Ee(),Yr=typeof process=="object"&&process.platform==="win32",mt=i(e=>typeof e=="object"&&e!==null,"is_Obj"),ht=new Uint32Array(256).map((e,t)=>{for(let r=0;r<8;r++)(t&1)!==0?t=3988292384^t>>>1:t>>>=1;return t>>>0});function L(e){this.sep=P.sep,this.fs=Zr,mt(e)&&mt(e.fs)&&typeof e.fs.statSync=="function"&&(this.fs=e.fs)}i(L,"Utils");yt.exports=L;L.prototype.makeDir=function(e){let t=this;function r(n){let o=n.split(t.sep)[0];n.split(t.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){o+=t.sep+a;var s;try{s=t.fs.statSync(o)}catch(l){if(l.message&&l.message.startsWith("ENOENT"))t.fs.mkdirSync(o);else throw l}if(s&&s.isFile())throw Jr.FILE_IN_THE_WAY(`"${o}"`)}})}i(r,"mkdirSync"),r(e)};L.prototype.writeFileTo=function(e,t,r,n){let o=this;if(o.fs.existsSync(e)){if(!r)return!1;var a=o.fs.statSync(e);if(a.isDirectory())return!1}var s=P.dirname(e);o.fs.existsSync(s)||o.makeDir(s);var l;try{l=o.fs.openSync(e,"w",438)}catch{o.fs.chmodSync(e,438),l=o.fs.openSync(e,"w",438)}if(l)try{o.fs.writeSync(l,t,0,t.length,0)}finally{o.fs.closeSync(l)}return o.fs.chmodSync(e,n||438),!0};L.prototype.writeFileToAsync=function(e,t,r,n,o){typeof n=="function"&&(o=n,n=void 0);let a=this;a.fs.exists(e,function(s){if(s&&!r)return o(!1);a.fs.stat(e,function(l,p){if(s&&p&&p.isDirectory())return o(!1);var m=P.dirname(e);a.fs.exists(m,function(y){if(!y)try{a.makeDir(m)}catch{return o(!1)}let T=i(function(S){a.fs.write(S,t,0,t.length,0,function(C){a.fs.close(S,function(){if(C)return o(!1);a.fs.chmod(e,n||438,function(){o(!0)})})})},"writeToFd");a.fs.open(e,"w",438,function(S,C){S?a.fs.chmod(e,438,function(){a.fs.open(e,"w",438,function(u,f){if(u||!f)return o(!1);T(f)})}):C?T(C):o(!1)})})})})};L.prototype.findFiles=function(e){let t=this;function r(n,o,a,s){typeof o=="boolean"&&(a=o,o=void 0);let l=[];return t.fs.readdirSync(n).forEach(function(p){let m=P.join(n,p),y=t.fs.statSync(m);if((!o||o.test(m))&&l.push(P.normalize(m)+(y.isDirectory()?t.sep:"")),y.isDirectory()&&a){let T=t.fs.realpathSync(m);s.has(T)||(s.add(T),l=l.concat(r(m,o,a,s)))}}),l}return i(r,"findSync"),r(e,void 0,!0,new Set([t.fs.realpathSync(e)]))};L.prototype.findFilesAsync=function(e,t){let r=this,n=[],o=!1,a=i(function(l){o||(o=!0,t(l,l?void 0:n))},"finish"),s=i(function(l,p,m){r.fs.readdir(l,function(y,T){if(y)return m(y);let S=T.length;if(!S)return m();T.forEach(function(C){let u=P.join(l,C);r.fs.stat(u,function(f,d){if(f)return m(f);if(!d){--S||m();return}if(n.push(P.normalize(u)+(d.isDirectory()?r.sep:"")),!d.isDirectory()){--S||m();return}r.fs.realpath(u,function(h,E){if(h)return m(h);if(p.has(E)){--S||m();return}p.add(E),s(u,p,function(c){if(c)return m(c);--S||m()})})})})})},"walk");r.fs.realpath(e,function(l,p){if(l)return a(l);s(e,new Set([p]),a)})};L.prototype.getAttributes=function(){};L.prototype.setAttributes=function(){};L.crc32update=function(e,t){return ht[(e^t)&255]^e>>>8};L.crc32=function(e){typeof e=="string"&&(e=Buffer.from(e,"utf8"));let t=e.length,r=-1;for(let n=0;n<t;)r=L.crc32update(r,e[n++]);return~r>>>0};L.methodToString=function(e){switch(e){case gt.STORED:return"STORED ("+e+")";case gt.DEFLATED:return"DEFLATED ("+e+")";default:return"UNSUPPORTED ("+e+")"}};L.canonical=function(e){if(!e)return"";let t=P.posix.normalize("/"+e.split("\\").join("/"));return P.join(".",t)};L.zipnamefix=function(e){if(!e)return"";let t=P.posix.normalize("/"+e.split("\\").join("/"));return P.posix.join(".",t)};L.findLast=function(e,t){if(!Array.isArray(e))throw new TypeError("arr is not array");let r=e.length>>>0;for(let n=r-1;n>=0;n--)if(t(e[n],n,e))return e[n]};L.sanitize=function(e,t){e=P.resolve(P.normalize(e));for(var r=t.split("/"),n=0,o=r.length;n<o;n++){var a=P.normalize(P.join(e,r.slice(n,o).join(P.sep)));if(a===e||a.startsWith(e+P.sep))return a}return P.normalize(P.join(e,P.basename(t)))};L.toBuffer=i(function(t,r){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):typeof t=="string"?r(t):Buffer.alloc(0)},"toBuffer");L.readBigUInt64LE=function(e,t){let r=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+r};L.writeBigUInt64LE=function(e,t,r){let n=t>>>0,o=Math.floor(t/4294967296)>>>0;e.writeUInt32LE(n,r),e.writeUInt32LE(o,r+4)};L.fromDOS2Date=function(e){return new Date((e>>25&127)+1980,Math.max((e>>21&15)-1,0),Math.max(e>>16&31,1),e>>11&31,e>>5&63,(e&31)<<1)};L.fromDate2DOS=function(e){let t=0,r=0;return e.getFullYear()>1979&&(t=(e.getFullYear()-1980&127)<<9|e.getMonth()+1<<5|e.getDate(),r=e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1),t<<16|r};L.isWin=Yr;L.crcTable=ht});var _t=W((Jo,Tt)=>{var qr=require("path");Tt.exports=function(e,{fs:t}){var r=e||"",n=a(),o=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return i(a,"newAttr"),r&&t.existsSync(r)?(o=t.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=qr.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:i(function(){},"decodeAttributes"),encodeAttributes:i(function(){},"encodeAttributes"),toJSON:i(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:i(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Rt=W((qo,It)=>{It.exports={efs:!0,encode:i(e=>Buffer.from(e,"utf8"),"encode"),decode:i(e=>e.toString("utf8"),"decode")}});var re=W((Qo,te)=>{te.exports=Et();te.exports.Constants=Pe();te.exports.Errors=Ee();te.exports.FileAttr=_t();te.exports.decoder=Rt()});var Ct=W((es,St)=>{var q=re(),_=q.Constants;St.exports=function(){var e=20,t=10,r=0,n=0,o=0,a=0,s=0,l=0,p=0,m=0,y=0,T=0,S=0,C=0,u=0;e|=q.isWin?2560:768,r|=_.FLG_EFS;let f={extraLen:0},d=i(c=>Math.max(0,c)>>>0,"uint32"),h=i(c=>Math.max(0,c)&65535,"uint16"),E=i(c=>Math.max(0,c)&255,"uint8");return o=q.fromDate2DOS(new Date),{get made(){return e},set made(c){e=c},get version(){return t},set version(c){t=c},get flags(){return r},set flags(c){r=c},get flags_efs(){return(r&_.FLG_EFS)>0},set flags_efs(c){c?r|=_.FLG_EFS:r&=~_.FLG_EFS},get flags_desc(){return(r&_.FLG_DESC)>0},set flags_desc(c){c?r|=_.FLG_DESC:r&=~_.FLG_DESC},get method(){return n},set method(c){switch(c){case _.STORED:this.version=10;break;case _.DEFLATED:default:this.version=20}n=c},get time(){return q.fromDOS2Date(this.timeval)},set time(c){c=new Date(c),this.timeval=q.fromDate2DOS(c)},get timeval(){return o},set timeval(c){o=d(c)},get timeHighByte(){return E(o>>>8)},get crc(){return a},set crc(c){a=d(c)},get compressedSize(){return s},set compressedSize(c){s=d(c)},get size(){return l},set size(c){l=d(c)},get fileNameLength(){return p},set fileNameLength(c){p=c},get extraLength(){return m},set extraLength(c){m=c},get extraLocalLength(){return f.extraLen},set extraLocalLength(c){f.extraLen=c},get commentLength(){return y},set commentLength(c){y=c},get diskNumStart(){return T},set diskNumStart(c){T=d(c)},get inAttr(){return S},set inAttr(c){S=d(c)},get attr(){return C},set attr(c){C=d(c)},get fileAttr(){return(C||0)>>16&4095},get offset(){return u},set offset(c){u=d(c)},get encrypted(){return(r&_.FLG_ENC)===_.FLG_ENC},get centralHeaderSize(){return _.CENHDR+p+m+y},get realDataOffset(){return u+_.LOCHDR+f.fnameLen+f.extraLen},get localHeader(){return f},loadLocalHeaderFromBinary:i(function(c){var g=c.slice(u,u+_.LOCHDR);if(g.readUInt32LE(0)!==_.LOCSIG)throw q.Errors.INVALID_LOC();f.version=g.readUInt16LE(_.LOCVER),f.flags=g.readUInt16LE(_.LOCFLG),f.flags_desc=(f.flags&_.FLG_DESC)>0,f.method=g.readUInt16LE(_.LOCHOW),f.time=g.readUInt32LE(_.LOCTIM),f.crc=g.readUInt32LE(_.LOCCRC),f.compressedSize=g.readUInt32LE(_.LOCSIZ),f.size=g.readUInt32LE(_.LOCLEN),f.fnameLen=g.readUInt16LE(_.LOCNAM),f.extraLen=g.readUInt16LE(_.LOCEXT);let R=u+_.LOCHDR+f.fnameLen,A=R+f.extraLen;return c.slice(R,A)},"loadLocalHeaderFromBinary"),loadFromBinary:i(function(c){if(c.length!==_.CENHDR||c.readUInt32LE(0)!==_.CENSIG)throw q.Errors.INVALID_CEN();e=c.readUInt16LE(_.CENVEM),t=c.readUInt16LE(_.CENVER),r=c.readUInt16LE(_.CENFLG),n=c.readUInt16LE(_.CENHOW),o=c.readUInt32LE(_.CENTIM),a=c.readUInt32LE(_.CENCRC),s=c.readUInt32LE(_.CENSIZ),l=c.readUInt32LE(_.CENLEN),p=c.readUInt16LE(_.CENNAM),m=c.readUInt16LE(_.CENEXT),y=c.readUInt16LE(_.CENCOM),T=c.readUInt16LE(_.CENDSK),S=c.readUInt16LE(_.CENATT),C=c.readUInt32LE(_.CENATX),u=c.readUInt32LE(_.CENOFF)},"loadFromBinary"),localHeaderToBinary:i(function(){var c=Buffer.alloc(_.LOCHDR);return c.writeUInt32LE(_.LOCSIG,0),c.writeUInt16LE(t,_.LOCVER),c.writeUInt16LE(r&~_.FLG_DESC,_.LOCFLG),c.writeUInt16LE(n,_.LOCHOW),c.writeUInt32LE(o,_.LOCTIM),c.writeUInt32LE(a,_.LOCCRC),c.writeUInt32LE(s,_.LOCSIZ),c.writeUInt32LE(l,_.LOCLEN),c.writeUInt16LE(p,_.LOCNAM),c.writeUInt16LE(f.extraLen,_.LOCEXT),c},"localHeaderToBinary"),centralHeaderToBinary:i(function(){var c=Buffer.alloc(_.CENHDR+p+m+y);return c.writeUInt32LE(_.CENSIG,0),c.writeUInt16LE(e,_.CENVEM),c.writeUInt16LE(t,_.CENVER),c.writeUInt16LE(r&~_.FLG_DESC,_.CENFLG),c.writeUInt16LE(n,_.CENHOW),c.writeUInt32LE(o,_.CENTIM),c.writeUInt32LE(a,_.CENCRC),c.writeUInt32LE(s,_.CENSIZ),c.writeUInt32LE(l,_.CENLEN),c.writeUInt16LE(p,_.CENNAM),c.writeUInt16LE(m,_.CENEXT),c.writeUInt16LE(y,_.CENCOM),c.writeUInt16LE(T,_.CENDSK),c.writeUInt16LE(S,_.CENATT),c.writeUInt32LE(C,_.CENATX),c.writeUInt32LE(u,_.CENOFF),c},"centralHeaderToBinary"),toJSON:i(function(){let c=i(function(g){return g+" bytes"},"bytes");return{made:e,version:t,flags:r,method:q.methodToString(n),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:c(s),size:c(l),fileNameLength:c(p),extraLength:c(m),commentLength:c(y),diskNumStart:T,inAttr:S,attr:C,offset:u,centralHeaderSize:c(_.CENHDR+p+m+y)}},"toJSON"),toString:i(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var bt=W((rs,At)=>{var K=re(),b=K.Constants;At.exports=function(){var e=0,t=0,r=0,n=0,o=0;let a=i(()=>e>b.EF_ZIP64_OR_16||t>b.EF_ZIP64_OR_16||r>b.EF_ZIP64_OR_32||n>b.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return e},set diskEntries(s){e=t=s},get totalEntries(){return t},set totalEntries(s){t=e=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(a()?b.ZIP64HDR+b.END64HDR:0)+b.ENDHDR+o},loadFromBinary:i(function(s){if((s.length!==b.ENDHDR||s.readUInt32LE(0)!==b.ENDSIG)&&(s.length<b.ZIP64HDR||s.readUInt32LE(0)!==b.ZIP64SIG))throw K.Errors.INVALID_END();s.readUInt32LE(0)===b.ENDSIG?(e=s.readUInt16LE(b.ENDSUB),t=s.readUInt16LE(b.ENDTOT),r=s.readUInt32LE(b.ENDSIZ),n=s.readUInt32LE(b.ENDOFF),o=s.readUInt16LE(b.ENDCOM)):(e=K.readBigUInt64LE(s,b.ZIP64SUB),t=K.readBigUInt64LE(s,b.ZIP64TOT),r=K.readBigUInt64LE(s,b.ZIP64SIZB),n=K.readBigUInt64LE(s,b.ZIP64OFF),o=0)},"loadFromBinary"),toBinary:i(function(){if(!a()){var s=Buffer.alloc(b.ENDHDR+o);return s.writeUInt32LE(b.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(e,b.ENDSUB),s.writeUInt16LE(t,b.ENDTOT),s.writeUInt32LE(r,b.ENDSIZ),s.writeUInt32LE(n,b.ENDOFF),s.writeUInt16LE(o,b.ENDCOM),s.fill(" ",b.ENDHDR),s}var s=Buffer.alloc(this.mainHeaderSize);let l=0;s.writeUInt32LE(b.ZIP64SIG,l),K.writeBigUInt64LE(s,b.ZIP64HDR-b.ZIP64LEAD,l+b.ZIP64SIZE),s.writeUInt16LE(45,l+b.ZIP64VEM),s.writeUInt16LE(45,l+b.ZIP64VER),s.writeUInt32LE(0,l+b.ZIP64DSK),s.writeUInt32LE(0,l+b.ZIP64DSKDIR),K.writeBigUInt64LE(s,e,l+b.ZIP64SUB),K.writeBigUInt64LE(s,t,l+b.ZIP64TOT),K.writeBigUInt64LE(s,r,l+b.ZIP64SIZB),K.writeBigUInt64LE(s,n,l+b.ZIP64OFF);let p=n+r;return l+=b.ZIP64HDR,s.writeUInt32LE(b.END64SIG,l),s.writeUInt32LE(0,l+b.END64START),K.writeBigUInt64LE(s,p,l+b.END64OFF),s.writeUInt32LE(1,l+b.END64NUMDISKS),l+=b.END64HDR,s.writeUInt32LE(b.ENDSIG,l),s.writeUInt32LE(0,l+4),s.writeUInt16LE(Math.min(e,b.EF_ZIP64_OR_16),l+b.ENDSUB),s.writeUInt16LE(Math.min(t,b.EF_ZIP64_OR_16),l+b.ENDTOT),s.writeUInt32LE(Math.min(r,b.EF_ZIP64_OR_32),l+b.ENDSIZ),s.writeUInt32LE(Math.min(n,b.EF_ZIP64_OR_32),l+b.ENDOFF),s.writeUInt16LE(o,l+b.ENDCOM),s.fill(" ",l+b.ENDHDR),s},"toBinary"),toJSON:i(function(){let s=i(function(l,p){let m=l.toString(16).toUpperCase();for(;m.length<p;)m="0"+m;return"0x"+m},"offset");return{diskEntries:e,totalEntries:t,size:r+" bytes",offset:s(n,4),commentLength:o}},"toJSON"),toString:i(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Fe=W(Ue=>{Ue.EntryHeader=Ct();Ue.MainHeader=bt()});var vt=W((ss,wt)=>{wt.exports=function(e){var t=require("zlib"),r={chunkSize:(parseInt(e.length/1024)+1)*1024};return{deflate:i(function(){return t.deflateRawSync(e,r)},"deflate"),deflateAsync:i(function(n){var o=t.createDeflateRaw(r),a=[],s=0;o.on("data",function(l){a.push(l),s+=l.length}),o.on("end",function(){var l=Buffer.alloc(s),p=0;l.fill(0);for(var m=0;m<a.length;m++){var y=a[m];y.copy(l,p),p+=y.length}n&&n(l)}),o.end(e)},"deflateAsync")}}});var xt=W((as,Dt)=>{var Xr=+(process?.versions?.node??"").split(".")[0]||0;Dt.exports=function(e,t){var r=require("zlib");let n=Xr>=15&&t>0?{maxOutputLength:t}:{};return{inflate:i(function(){return r.inflateRawSync(e,n)},"inflate"),inflateAsync:i(function(o){var a=r.createInflateRaw(n),s=[],l=0;a.on("data",function(p){s.push(p),l+=p.length}),a.on("end",function(){var p=Buffer.alloc(l),m=0;p.fill(0);for(var y=0;y<s.length;y++){var T=s[y];T.copy(p,m),m+=T.length}o&&o(p)}),a.end(e)},"inflateAsync")}}});var kt=W((ls,Mt)=>{"use strict";var{randomFillSync:Nt}=require("crypto"),Qr=Ee(),en=new Uint32Array(256).map((e,t)=>{for(let r=0;r<8;r++)(t&1)!==0?t=t>>>1^3988292384:t>>>=1;return t>>>0}),Ot=i((e,t)=>Math.imul(e,t)>>>0,"uMul"),Lt=i((e,t)=>en[(e^t)&255]^e>>>8,"crc32update"),ue=i(()=>typeof Nt=="function"?Nt(Buffer.alloc(12)):ue.node(),"genSalt");ue.node=()=>{let e=Buffer.alloc(12),t=e.length;for(let r=0;r<t;r++)e[r]=Math.random()*256&255;return e};var Te={genSalt:ue};function _e(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<t.length;r++)this.updateKeys(t[r])}i(_e,"Initkeys");_e.prototype.updateKeys=function(e){let t=this.keys;return t[0]=Lt(t[0],e),t[1]+=t[0]&255,t[1]=Ot(t[1],134775813)+1,t[2]=Lt(t[2],t[1]>>>24),e};_e.prototype.next=function(){let e=(this.keys[2]|2)>>>0;return Ot(e,e^1)>>8&255};function tn(e){let t=new _e(e);return function(r){let n=Buffer.alloc(r.length),o=0;for(let a of r)n[o++]=t.updateKeys(a^t.next());return n}}i(tn,"make_decrypter");function rn(e){let t=new _e(e);return function(r,n,o=0){n||(n=Buffer.alloc(r.length));for(let a of r){let s=t.next();n[o++]=a^s,t.updateKeys(a)}return n}}i(rn,"make_encrypter");function nn(e,t,r){if(!e||!Buffer.isBuffer(e)||e.length<12)return Buffer.alloc(0);let n=tn(r),o=n(e.slice(0,12)),a=(t.flags&8)===8?t.timeHighByte:t.crc>>>24;if(o[11]!==a)throw Qr.WRONG_PASSWORD();return n(e.slice(12))}i(nn,"decrypt");function on(e){Buffer.isBuffer(e)&&e.length>=12?Te.genSalt=function(){return e.slice(0,12)}:e==="node"?Te.genSalt=ue.node:Te.genSalt=ue}i(on,"_salter");function sn(e,t,r,n=!1){e==null&&(e=Buffer.alloc(0)),Buffer.isBuffer(e)||(e=Buffer.from(e.toString()));let o=rn(r),a=Te.genSalt();a[11]=t.crc>>>24&255,n&&(a[10]=t.crc>>>16&255);let s=Buffer.alloc(e.length+12);return o(a,s),o(e,s,12)}i(sn,"encrypt");Mt.exports={decrypt:nn,encrypt:sn,_salter:on}});var Pt=W(Ie=>{Ie.Deflater=vt();Ie.Inflater=xt();Ie.ZipCrypto=kt()});var He=W((ps,Ut)=>{var N=re(),an=Fe(),z=N.Constants,Be=Pt();Ut.exports=function(e,t){var r=new an.EntryHeader,n=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,s=null,l=Buffer.alloc(0),p=Buffer.alloc(0),m=!0;let y=e,T=typeof y.decoder=="object"?y.decoder:N.decoder;m=T.hasOwnProperty("efs")?T.efs:!1;function S(){return!t||!(t instanceof Uint8Array)?Buffer.alloc(0):(p=r.loadLocalHeaderFromBinary(t),t.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}i(S,"getCompressedDataFromZip");function C(c){let g=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return N.crc32(c)===g}i(C,"crc32OK");function u(c,g,R){if(typeof g>"u"&&typeof c=="string"&&(R=c,c=void 0),a)return c&&g&&g(Buffer.alloc(0),N.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var A=S();if(A.length===0)return c&&g&&g(A),A;if(r.encrypted){if(typeof R!="string"&&!Buffer.isBuffer(R))throw N.Errors.INVALID_PASS_PARAM();A=Be.ZipCrypto.decrypt(A,r,R)}var I;switch(r.method){case N.Constants.STORED:if(I=Buffer.alloc(A.length),A.copy(I),C(I))return c&&g&&g(I),I;throw c&&g&&g(I,N.Errors.BAD_CRC()),N.Errors.BAD_CRC();case N.Constants.DEFLATED:var w=new Be.Inflater(A,r.size);if(c)w.inflateAsync(function(v){g&&(C(v)?g(v):g(v,N.Errors.BAD_CRC()))});else{if(I=w.inflate(),!C(I))throw N.Errors.BAD_CRC(`"${T.decode(n)}"`);return I}break;default:throw c&&g&&g(Buffer.alloc(0),N.Errors.UNKNOWN_METHOD()),N.Errors.UNKNOWN_METHOD()}}i(u,"decompress");function f(c,g){if((!s||!s.length)&&Buffer.isBuffer(t))return c&&g&&g(S()),S();if(s.length&&!a){var R;switch(r.method){case N.Constants.STORED:return r.compressedSize=r.size,R=Buffer.alloc(s.length),s.copy(R),c&&g&&g(R),R;default:case N.Constants.DEFLATED:var A=new Be.Deflater(s);if(c)A.deflateAsync(function(w){R=Buffer.alloc(w.length),r.compressedSize=w.length,w.copy(R),g&&g(R)});else{var I=A.deflate();return r.compressedSize=I.length,I}A=null;break}}else if(c&&g)g(Buffer.alloc(0));else return Buffer.alloc(0)}i(f,"compress");function d(c,g){return N.readBigUInt64LE(c,g)}i(d,"readUInt64LE");function h(c){try{for(var g=0,R,A,I;g+4<c.length;)R=c.readUInt16LE(g),g+=2,A=c.readUInt16LE(g),g+=2,I=c.slice(g,g+A),g+=A,z.ID_ZIP64===R&&E(I)}catch{throw N.Errors.EXTRA_FIELD_PARSE_ERROR()}}i(h,"parseExtra");function E(c){var g,R,A,I;c.length>=z.EF_ZIP64_SCOMP&&(g=d(c,z.EF_ZIP64_SUNCOMP),r.size===z.EF_ZIP64_OR_32&&(r.size=g)),c.length>=z.EF_ZIP64_RHO&&(R=d(c,z.EF_ZIP64_SCOMP),r.compressedSize===z.EF_ZIP64_OR_32&&(r.compressedSize=R)),c.length>=z.EF_ZIP64_DSN&&(A=d(c,z.EF_ZIP64_RHO),r.offset===z.EF_ZIP64_OR_32&&(r.offset=A)),c.length>=z.EF_ZIP64_DSN+4&&(I=c.readUInt32LE(z.EF_ZIP64_DSN),r.diskNumStart===z.EF_ZIP64_OR_16&&(r.diskNumStart=I))}return i(E,"parseZip64ExtendedInformation"),{get entryName(){return T.decode(n)},get rawEntryName(){return n},set entryName(c){n=N.toBuffer(c,T.encode);var g=n[n.length-1];a=g===47||g===92,r.fileNameLength=n.length},get efs(){return typeof m=="function"?m(this.entryName):m},get extra(){return l},set extra(c){l=c,r.extraLength=c.length,h(c)},get comment(){return T.decode(o)},set comment(c){if(o=N.toBuffer(c,T.encode),r.commentLength=o.length,o.length>65535)throw N.Errors.COMMENT_TOO_LONG()},get name(){let c=T.decode(n);return a?c.replace(/[/\\]$/,"").split("/").pop():c.split("/").pop()},get isDirectory(){return a},getCompressedData:i(function(){return f(!1,null)},"getCompressedData"),getCompressedDataAsync:i(function(c){f(!0,c)},"getCompressedDataAsync"),setData:i(function(c){s=N.toBuffer(c,N.decoder.encode),!a&&s.length?(r.size=s.length,r.method=N.Constants.DEFLATED,r.crc=N.crc32(c),r.changed=!0):r.method=N.Constants.STORED},"setData"),getData:i(function(c){return r.changed?s:u(!1,null,c)},"getData"),getDataAsync:i(function(c,g){r.changed?c(s):u(!0,c,g)},"getDataAsync"),set attr(c){r.attr=c},get attr(){return r.attr},set header(c){r.loadFromBinary(c)},get header(){return r},packCentralHeader:i(function(){r.flags_efs=this.efs,r.extraLength=l.length;var c=r.centralHeaderToBinary(),g=N.Constants.CENHDR;return n.copy(c,g),g+=n.length,l.copy(c,g),g+=r.extraLength,o.copy(c,g),c},"packCentralHeader"),packLocalHeader:i(function(){let c=0;r.flags_efs=this.efs,r.extraLocalLength=p.length;let g=r.localHeaderToBinary(),R=Buffer.alloc(g.length+n.length+r.extraLocalLength);return g.copy(R,c),c+=g.length,n.copy(R,c),c+=n.length,p.copy(R,c),c+=p.length,R},"packLocalHeader"),toJSON:i(function(){let c=i(function(g){return"<"+(g&&g.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:c(t),data:c(s)}},"toJSON"),toString:i(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Ht=W((gs,Bt)=>{var Ft=He(),cn=Fe(),G=re();Bt.exports=function(e,t){var r=[],n=Object.create(null),o=Buffer.alloc(0),a=new cn.MainHeader,s=!1,l=null;let p=new Set,m=t,{noSort:y,decoder:T}=m;e?u(m.readEntries):s=!0;function S(){let d=new Set;for(let h of Object.keys(n)){let E=h.split("/");if(E.pop(),!!E.length)for(let c=0;c<E.length;c++){let g=E.slice(0,c+1).join("/")+"/";d.add(g)}}for(let h of d)if(!(h in n)){let E=new Ft(m);E.entryName=h,E.attr=16,E.temporary=!0,r.push(E),n[E.entryName]=E,p.add(E)}}i(S,"makeTemporaryFolders");function C(){if(s=!0,n=Object.create(null),a.diskEntries>(e.length-a.offset)/G.Constants.CENHDR)throw G.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(a.diskEntries);for(var d=a.offset,h=0;h<r.length;h++){var E=d,c=new Ft(m,e);c.header=e.slice(E,E+=G.Constants.CENHDR),c.entryName=e.slice(E,E+=c.header.fileNameLength),c.header.extraLength&&(c.extra=e.slice(E,E+=c.header.extraLength)),c.header.commentLength&&(c.comment=e.slice(E,E+c.header.commentLength)),d+=c.header.centralHeaderSize,r[h]=c,n[c.entryName]=c}p.clear(),S()}i(C,"readEntries");function u(d){var h=e.length-G.Constants.ENDHDR,E=Math.max(0,h-65535),c=E,g=e.length,R=-1,A=0;for(typeof m.trailingSpace=="boolean"&&m.trailingSpace&&(E=0),h;h>=c;h--)if(e[h]===80){if(e.readUInt32LE(h)===G.Constants.ENDSIG){R=h,A=h,g=h+G.Constants.ENDHDR,c=h-G.Constants.END64HDR;continue}if(e.readUInt32LE(h)===G.Constants.END64SIG){c=E;continue}if(e.readUInt32LE(h)===G.Constants.ZIP64SIG){R=h,g=h+G.readBigUInt64LE(e,h+G.Constants.ZIP64SIZE)+G.Constants.ZIP64LEAD;break}}if(R==-1)throw G.Errors.INVALID_FORMAT();a.loadFromBinary(e.slice(R,g)),a.commentLength&&(o=e.slice(A+G.Constants.ENDHDR)),d&&C()}i(u,"readMainHeader");function f(){r.length>1&&!y&&(r=r.map(d=>({entry:d,key:d.entryName.toLowerCase()})).sort((d,h)=>d.key.localeCompare(h.key)).map(d=>d.entry))}return i(f,"sortEntries"),{get entries(){return s||C(),r.filter(d=>!p.has(d))},get comment(){return T.decode(o)},set comment(d){o=G.toBuffer(d,T.encode),a.commentLength=o.length},getEntryCount:i(function(){return s?r.length:a.diskEntries},"getEntryCount"),forEach:i(function(d){this.entries.forEach(d)},"forEach"),getEntry:i(function(d){return s||C(),n[d]||null},"getEntry"),setEntry:i(function(d){s||C(),r.push(d),n[d.entryName]=d,a.totalEntries=r.length},"setEntry"),deleteFile:i(function(d,h=!0){s||C();let E=n[d];this.getEntryChildren(E,h).map(g=>g.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:i(function(d){s||C();let h=n[d],E=r.indexOf(h);E>=0&&(r.splice(E,1),delete n[d],a.totalEntries=r.length)},"deleteEntry"),getEntryChildren:i(function(d,h=!0){if(s||C(),typeof d=="object")if(d.isDirectory&&h){let E=[],c=d.entryName;for(let g of r)g.entryName.startsWith(c)&&E.push(g);return E}else return[d];return[]},"getEntryChildren"),getChildCount:i(function(d){if(d&&d.isDirectory){let h=this.getEntryChildren(d);return h.includes(d)?h.length-1:h.length}return 0},"getChildCount"),compressToBuffer:i(function(){s||C(),f();let d=[],h=[],E=0,c=0;a.size=0,a.offset=0;let g=0;for(let I of this.entries){let w=I.getCompressedData();I.header.offset=c;let v=I.packLocalHeader(),D=v.length+w.length;c+=D,d.push(v),d.push(w);let x=I.packCentralHeader();h.push(x),a.size+=x.length,E+=D+x.length,g++}E+=a.mainHeaderSize,a.offset=c,a.totalEntries=g,c=0;let R=Buffer.alloc(E);for(let I of d)I.copy(R,c),c+=I.length;for(let I of h)I.copy(R,c),c+=I.length;let A=a.toBinary();return o&&o.copy(A,A.length-o.length),A.copy(R,c),e=R,s=!1,R},"compressToBuffer"),toAsyncBuffer:i(function(d,h,E,c){try{s||C(),f();let g=[],R=[],A=0,I=0,w=0;a.size=0,a.offset=0;let v=i(function(D){if(D.length>0){let x=D.shift(),H=x.entryName+x.extra.toString();E&&E(H),x.getCompressedDataAsync(function($){c&&c(H),x.header.offset=I;let X=x.packLocalHeader(),ye=X.length+$.length;I+=ye,g.push(X),g.push($);let ce=x.packCentralHeader();R.push(ce),a.size+=ce.length,A+=ye+ce.length,w++,v(D)})}else{A+=a.mainHeaderSize,a.offset=I,a.totalEntries=w,I=0;let x=Buffer.alloc(A);g.forEach(function($){$.copy(x,I),I+=$.length}),R.forEach(function($){$.copy(x,I),I+=$.length});let H=a.toBinary();o&&o.copy(H,H.length-o.length),H.copy(x,I),e=x,s=!1,d(x)}},"compress2Buffer");v(Array.from(this.entries))}catch(g){h(g)}},"toAsyncBuffer")}}});var Gt=W((hs,$t)=>{var M=re(),O=require("path"),ln=He(),dn=Ht(),Q=i((...e)=>M.findLast(e,t=>typeof t=="boolean"),"get_Bool"),Wt=i((...e)=>M.findLast(e,t=>typeof t=="string"),"get_Str"),un=i((...e)=>M.findLast(e,t=>typeof t=="function"),"get_Fun"),pn={noSort:!1,readEntries:!1,method:M.Constants.NONE,fs:null};$t.exports=function(e,t){let r=null,n=Object.assign(Object.create(null),pn);e&&typeof e=="object"&&(e instanceof Uint8Array||(Object.assign(n,e),e=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(e)&&(r=e,n.method=M.Constants.BUFFER,e=void 0)),Object.assign(n,t);let o=new M(n),a=i(u=>{u.filter(f=>f.attr).sort((f,d)=>d.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),e&&typeof e=="string")if(o.fs.existsSync(e))n.method=M.Constants.FILE,n.filename=e,r=o.fs.readFileSync(e);else throw M.Errors.INVALID_FILENAME();let s=new dn(r,n),{canonical:l,sanitize:p,zipnamefix:m}=M;function y(u){if(u&&s){var f;if(typeof u=="string"&&(f=s.getEntry(O.posix.normalize(u))),typeof u=="object"&&typeof u.entryName<"u"&&typeof u.header<"u"&&(f=s.getEntry(u.entryName)),f)return f}return null}i(y,"getEntry");function T(u){let{join:f,normalize:d,sep:h}=O.posix;return f(O.isAbsolute(u)?"/":".",d(h+u.split("\\").join(h)+h))}i(T,"fixPath");function S(u){return u instanceof RegExp?(function(f){return function(d){return f.test(d)}})(u):typeof u!="function"?()=>!0:u}i(S,"filenameFilter");let C=i((u,f)=>{let d=f.slice(-1);return d=d===o.sep?o.sep:"",O.relative(u,f)+d},"relativePath");return{readFile:i(function(u,f){var d=y(u);return d&&d.getData(f)||null},"readFile"),childCount:i(function(u){let f=y(u);if(f)return s.getChildCount(f)},"childCount"),readFileAsync:i(function(u,f){var d=y(u);d?d.getDataAsync(f):f(null,"getEntry failed for:"+u)},"readFileAsync"),readAsText:i(function(u,f){var d=y(u);if(d){var h=d.getData();if(h&&h.length)return h.toString(f||"utf8")}return""},"readAsText"),readAsTextAsync:i(function(u,f,d){var h=y(u);h?h.getDataAsync(function(E,c){if(c){f(E,c);return}E&&E.length?f(E.toString(d||"utf8")):f("")}):f("")},"readAsTextAsync"),deleteFile:i(function(u,f=!0){var d=y(u);d&&s.deleteFile(d.entryName,f)},"deleteFile"),deleteEntry:i(function(u){var f=y(u);f&&s.deleteEntry(f.entryName)},"deleteEntry"),addZipComment:i(function(u){s.comment=u},"addZipComment"),getZipComment:i(function(){return s.comment||""},"getZipComment"),addZipEntryComment:i(function(u,f){var d=y(u);d&&(d.comment=f)},"addZipEntryComment"),getZipEntryComment:i(function(u){var f=y(u);return f&&f.comment||""},"getZipEntryComment"),updateFile:i(function(u,f){var d=y(u);d&&d.setData(f)},"updateFile"),addLocalFile:i(function(u,f,d,h){if(o.fs.existsSync(u)){f=f?T(f):"";let E=O.win32.basename(O.win32.normalize(u));f+=d||E;let c=o.fs.statSync(u),g=c.isFile()?o.fs.readFileSync(u):Buffer.alloc(0);c.isDirectory()&&(f+=o.sep),this.addFile(f,g,h,c)}else throw M.Errors.FILE_NOT_FOUND(u)},"addLocalFile"),addLocalFileAsync:i(function(u,f){u=typeof u=="object"?u:{localPath:u};let d=O.resolve(u.localPath),{comment:h}=u,{zipPath:E,zipName:c}=u,g=this;o.fs.stat(d,function(R,A){if(R)return f(R,!1);E=E?T(E):"";let I=O.win32.basename(O.win32.normalize(d));if(E+=c||I,A.isFile())o.fs.readFile(d,function(w,v){return w?f(w,!1):(g.addFile(E,v,h,A),setImmediate(f,void 0,!0))});else if(A.isDirectory())return E+=o.sep,g.addFile(E,Buffer.alloc(0),h,A),setImmediate(f,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:i(function(u,f,d){if(d=S(d),f=f?T(f):"",u=O.normalize(u),o.fs.existsSync(u)){let h=o.findFiles(u),E=this;if(h.length)for(let c of h){let g=O.join(f,C(u,c));d(g)&&E.addLocalFile(c,O.dirname(g))}}else throw M.Errors.FILE_NOT_FOUND(u)},"addLocalFolder"),addLocalFolderAsync:i(function(u,f,d,h){h=S(h),d=d?T(d):"",u=O.normalize(u);var E=this;o.fs.open(u,"r",function(c){if(c&&c.code==="ENOENT")f(void 0,M.Errors.FILE_NOT_FOUND(u));else if(c)f(void 0,c);else{var g=o.findFiles(u),R=-1,A=i(function(){if(R+=1,R<g.length){var I=g[R],w=C(u,I).split("\\").join("/");w=w.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),h(w)?o.fs.stat(I,function(v,D){v&&f(void 0,v),D.isFile()?o.fs.readFile(I,function(x,H){x?f(void 0,x):(E.addFile(d+w,H,"",D),A())}):(E.addFile(d+w+"/",Buffer.alloc(0),"",D),A())}):process.nextTick(()=>{A()})}else f(!0,void 0)},"next");A()}})},"addLocalFolderAsync"),addLocalFolderAsync2:i(function(u,f){let d=this;u=typeof u=="object"?u:{localPath:u};let h=O.resolve(T(u.localPath)),{zipPath:E,filter:c,namefix:g}=u;c instanceof RegExp?c=(function(I){return function(w){return I.test(w)}})(c):typeof c!="function"&&(c=i(function(){return!0},"filter")),E=E?T(E):"",g==="latin1"&&(g=i(I=>I.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof g!="function"&&(g=i(I=>I,"namefix"));let R=i(I=>O.join(E,g(C(h,I))),"relPathFix"),A=i(I=>O.win32.basename(O.win32.normalize(g(I))),"fileNameFix");o.fs.open(h,"r",function(I){I&&I.code==="ENOENT"?f(void 0,M.Errors.FILE_NOT_FOUND(h)):I?f(void 0,I):o.findFilesAsync(h,function(w,v){if(w)return f(w);v=v.filter(D=>c(R(D))),v.length||f(void 0,!1),setImmediate(v.reverse().reduce(function(D,x){return function(H,$){if(H||$===!1)return setImmediate(D,H,!1);d.addLocalFileAsync({localPath:x,zipPath:O.dirname(R(x)),zipName:A(x)},D)}},f))})})},"addLocalFolderAsync2"),addLocalFolderPromise:i(function(u,f){return new Promise((d,h)=>{this.addLocalFolderAsync2(Object.assign({localPath:u},f),(E,c)=>{E&&h(E),c&&d(this)})})},"addLocalFolderPromise"),addFile:i(function(u,f,d,h){u=m(u);let E=y(u),c=E!=null;c||(E=new ln(n),E.entryName=u),E.comment=d||"";let g=typeof h=="object"&&h instanceof o.fs.Stats;g&&(E.header.time=h.mtime);var R=E.isDirectory?16:0;let A=E.isDirectory?16384:32768;return g?A|=4095&h.mode:typeof h=="number"?A|=4095&h:A|=E.isDirectory?493:420,R=(R|A<<16)>>>0,E.attr=R,E.setData(f),c||s.setEntry(E),E},"addFile"),getEntries:i(function(u){return s.password=u,s?s.entries:[]},"getEntries"),getEntry:i(function(u){return y(u)},"getEntry"),getEntryCount:i(function(){return s.getEntryCount()},"getEntryCount"),forEach:i(function(u){return s.forEach(u)},"forEach"),extractEntryTo:i(function(u,f,d,h,E,c){h=Q(!1,h),E=Q(!1,E),d=Q(!0,d),c=Wt(E,c);var g=y(u);if(!g)throw M.Errors.NO_ENTRY();var R=l(g.entryName),A=p(f,c&&!g.isDirectory?l(c):d?R:O.basename(R));if(g.isDirectory){var I=s.getEntryChildren(g);return I.forEach(function(D){if(D.isDirectory)return;var x=D.getData();if(!x)throw M.Errors.CANT_EXTRACT_FILE();var H=l(d?D.entryName:D.entryName.substring(g.entryName.length)),$=p(f,H);let X=E?D.header.fileAttr:void 0;o.writeFileTo($,x,h,X)}),!0}var w=g.getData(s.password);if(!w)throw M.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(A)&&!h)throw M.Errors.CANT_OVERRIDE();let v=E?u.header.fileAttr:void 0;return o.writeFileTo(A,w,h,v),!0},"extractEntryTo"),test:i(function(u){if(!s)return!1;for(var f of s.entries)try{if(f.isDirectory)continue;var d=f.getData(u);if(!d)return!1}catch{return!1}return!0},"test"),extractAllTo:i(function(u,f,d,h){if(d=Q(!1,d),h=Wt(d,h),f=Q(!1,f),!s)throw M.Errors.NO_ZIP();let E=[];s.entries.forEach(function(c){var g=p(u,l(c.entryName));if(c.isDirectory){o.makeDir(g),d&&E.push({path:g,attr:c.header.fileAttr});return}var R=c.getData(h);if(!R)throw M.Errors.CANT_EXTRACT_FILE();let A=d?c.header.fileAttr:void 0;o.writeFileTo(g,R,f,A);try{o.fs.utimesSync(g,c.header.time,c.header.time)}catch{}}),a(E)},"extractAllTo"),extractAllToAsync:i(function(u,f,d,h){if(h=un(f,d,h),d=Q(!1,d),f=Q(!1,f),!h)return new Promise((w,v)=>{this.extractAllToAsync(u,f,d,function(D){D?v(D):w(this)})});if(!s){h(M.Errors.NO_ZIP());return}u=O.resolve(u);let E=i(w=>p(u,O.normalize(l(w.entryName))),"getPath"),c=i((w,v)=>new Error(w+': "'+v+'"'),"getError"),g=[],R=[];s.entries.forEach(w=>{w.isDirectory?g.push(w):R.push(w)});let A=[];for(let w of g){let v=E(w),D=d?w.header.fileAttr:void 0;try{o.makeDir(v)}catch{h(c("Unable to create folder",v));continue}D&&A.push({path:v,attr:D});try{o.fs.utimesSync(v,w.header.time,w.header.time)}catch{}}let I=i(w=>{if(!w)try{a(A)}catch(v){return h(c("Unable to set folder permissions",v.path||""))}h(w)},"done");R.reverse().reduce(function(w,v){return function(D){if(D)w(D);else{let x=O.normalize(l(v.entryName)),H=p(u,x);v.getDataAsync(function($,X){if(X)w(X);else if(!$)w(M.Errors.CANT_EXTRACT_FILE());else{let ye=d?v.header.fileAttr:void 0;o.writeFileToAsync(H,$,f,ye,function(ce){if(!ce)return w(c("Unable to write file",H));o.fs.utimes(H,v.header.time,v.header.time,function(){w()})})}})}}},I)()},"extractAllToAsync"),writeZip:i(function(u,f){if(arguments.length===1&&typeof u=="function"&&(f=u,u=""),!u&&n.filename&&(u=n.filename),!!u){var d=s.compressToBuffer();if(d){var h=o.writeFileTo(u,d,!0);typeof f=="function"&&f(h?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:i(function(u,f){let{overwrite:d,perm:h}=Object.assign({overwrite:!0},f);return new Promise((E,c)=>{!u&&n.filename&&(u=n.filename),u||c("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(g=>{let R=i(A=>A?E(A):c("ADM-ZIP: Wasn't able to write zip file"),"ret");o.writeFileToAsync(u,g,d,h,R)},c)})},"writeZipPromise"),toBufferPromise:i(function(){return new Promise((u,f)=>{s.toAsyncBuffer(u,f)})},"toBufferPromise"),toBuffer:i(function(u,f,d,h){return typeof u=="function"?(s.toAsyncBuffer(u,f,d,h),null):s.compressToBuffer()},"toBuffer")}}});var Yt=W((_s,Z)=>{var $e=require("fs"),Se=require("path"),gn=require("os"),mn=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 hn(){return Vt[Math.floor(Math.random()*Vt.length)]}i(hn,"_getRandomTip");function ne(e){return typeof e=="string"?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}i(ne,"parseBoolean");function yn(){return process.stdout.isTTY}i(yn,"supportsAnsi");function En(e){return yn()?`\x1B[2m${e}\x1B[0m`:e}i(En,"dim");var Tn=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function _n(e){let t={},r=e.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
-
`);let n;for(;(n=
|
|
3
|
-
`),a=a.replace(/\\r/g,"\r")),t[o]=a}return t}i(_n,"parse");function In(e){e=e||{};let t=Jt(e);e.path=t;let r=U.configDotenv(e);if(!r.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=Zt(e).split(","),o=n.length,a;for(let s=0;s<o;s++)try{let l=n[s].trim(),p=Sn(r,l);a=U.decrypt(p.ciphertext,p.key);break}catch(l){if(s+1>=o)throw l}return U.parse(a)}i(In,"_parseVault");function Rn(e){console.error(`\u26A0 ${e}`)}i(Rn,"_warn");function pe(e){console.log(`\u2506 ${e}`)}i(pe,"_debug");function Kt(e){console.log(`\u25C7 ${e}`)}i(Kt,"_log");function Zt(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}i(Zt,"_dotenvKey");function Sn(e,t){let r;try{r=new URL(t)}catch(l){if(l.code==="ERR_INVALID_URL"){let p=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 p.code="INVALID_DOTENV_KEY",p}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 a=`DOTENV_VAULT_${o.toUpperCase()}`,s=e.parsed[a];if(!s){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:s,key:n}}i(Sn,"_instructions");function Jt(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)$e.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=Se.resolve(process.cwd(),".env.vault");return $e.existsSync(t)?t:null}i(Jt,"_vaultPath");function zt(e){return e[0]==="~"?Se.join(gn.homedir(),e.slice(1)):e}i(zt,"_resolveHome");function Cn(e){let t=ne(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),r=ne(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!r)&&Kt("loading env from encrypted .env.vault");let n=U._parseVault(e),o=process.env;return e&&e.processEnv!=null&&(o=e.processEnv),U.populate(o,n,e),{parsed:n}}i(Cn,"_configVault");function An(e){let t=Se.resolve(process.cwd(),".env"),r="utf8",n=process.env;e&&e.processEnv!=null&&(n=e.processEnv);let o=ne(n.DOTENV_CONFIG_DEBUG||e&&e.debug),a=ne(n.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:o&&pe("no encoding is specified (UTF-8 is used by default)");let s=[t];if(e&&e.path)if(!Array.isArray(e.path))s=[zt(e.path)];else{s=[];for(let y of e.path)s.push(zt(y))}let l,p={};for(let y of s)try{let T=U.parse($e.readFileSync(y,{encoding:r}));U.populate(p,T,e)}catch(T){o&&pe(`failed to load ${y} ${T.message}`),l=T}let m=U.populate(n,p,e);if(o=ne(n.DOTENV_CONFIG_DEBUG||o),a=ne(n.DOTENV_CONFIG_QUIET||a),o||!a){let y=Object.keys(m).length,T=[];for(let S of s)try{let C=Se.relative(process.cwd(),S);T.push(C)}catch(C){o&&pe(`failed to load ${S} ${C.message}`),l=C}Kt(`injected env (${y}) from ${T.join(",")} ${En(`// tip: ${hn()}`)}`)}return l?{parsed:p,error:l}:{parsed:p}}i(An,"configDotenv");function bn(e){if(Zt(e).length===0)return U.configDotenv(e);let t=Jt(e);return t?U._configVault(e):(Rn(`you set DOTENV_KEY but you are missing a .env.vault file at ${t}`),U.configDotenv(e))}i(bn,"config");function wn(e,t){let r=Buffer.from(t.slice(-64),"hex"),n=Buffer.from(e,"base64"),o=n.subarray(0,12),a=n.subarray(-16);n=n.subarray(12,-16);try{let s=mn.createDecipheriv("aes-256-gcm",r,o);return s.setAuthTag(a),`${s.update(n)}${s.final()}`}catch(s){let l=s instanceof RangeError,p=s.message==="Invalid key length",m=s.message==="Unsupported state or unable to authenticate data";if(l||p){let y=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw y.code="INVALID_DOTENV_KEY",y}else if(m){let y=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw y.code="DECRYPTION_FAILED",y}else throw s}}i(wn,"decrypt");function vn(e,t,r={}){let n=!!(r&&r.debug),o=!!(r&&r.override),a={};if(typeof t!="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(t))Object.prototype.hasOwnProperty.call(e,s)?(o===!0&&(e[s]=t[s],a[s]=t[s]),n&&pe(o===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):(e[s]=t[s],a[s]=t[s]);return a}i(vn,"populate");var U={configDotenv:An,_configVault:Cn,_parseVault:In,config:bn,decrypt:wn,parse:_n,populate:vn};Z.exports.configDotenv=U.configDotenv;Z.exports._configVault=U._configVault;Z.exports._parseVault=U._parseVault;Z.exports.config=U.config;Z.exports.decrypt=U.decrypt;Z.exports.parse=U.parse;Z.exports.populate=U.populate;Z.exports=U});var Ao={};Gr(Ao,{TestRunMonitor:()=>Me});module.exports=jr(Ao);var ke=i(e=>new Promise(t=>setTimeout(t,e)),"awaitSleep");var Nr=require("child_process"),he=require("crypto"),k=require("fs"),Lr=require("fs/promises"),Or=require("stream/promises"),Mr=require("http"),kr=de(require("net")),Pr=require("os"),V=require("path");function zr(e){if(e)return{...e,...e.tests?{tests:e.tests.map(t=>{let{errorMessage:r,...n}=t;return n})}:{}}}i(zr,"projectReportStatsForTelemetry");function at(e,t,r){e.emit({outcome:t,stats:zr(r)})}i(at,"emitReportProcessingStatsTelemetry");var ct=["script","template"],lt='<script id="playwrightReportBase64" type="application/zip">',dt="</script>";var hr=require("htmlparser2"),yr=de(Gt()),B=require("node:fs"),ee=require("node:path"),Er=require("node:os"),Tr=require("node:crypto");var J=de(require("path")),je=require("fs");var We=require("path"),Re=require("fs");function fn(e,t,r=10){let n=e;for(let o=0;o<r;o++){let a=(0,We.join)(n,"package.json");if((0,Re.existsSync)(a))try{if(JSON.parse((0,Re.readFileSync)(a,"utf8")).name===t)return n}catch{}n=(0,We.join)(n,"..")}}i(fn,"findRepositoryRoot");function jt(e,t=10){return fn(e,"checksum-customer-engineering-workspace",t)}i(jt,"findCustomerEngineeringRoot");var Ve=de(Yt());var j=i((e,t)=>{if(e==null||e==="")return t?.default??!1;let r=e.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:t?.default??!1},"parseBoolean");function qt(e){if(e===void 0||e.trim()==="")return 5e7;let t=Number(e);return!Number.isInteger(t)||t<0?5e7:t}i(qt,"resolveMaxRRwebBytes");var Dn=__dirname,Xt=J.join(__dirname,".."),er=(0,je.existsSync)(Xt)?Xt:Dn;(0,Ve.config)({path:J.resolve(er,".env")});var Qt=j(process.env.CHECKSUM_RUNTIME_DEV_MODE);function xn(){let e=__dirname;for(;!(0,je.existsSync)(J.join(e,"package.json"));)e=J.join(e,"..");return e}i(xn,"findRoot");var fe=xn(),Nn=jt(fe,10);(0,Ve.config)({path:[er,Nn].filter(e=>!!e).map(e=>J.resolve(e,".env")),override:!1});var Ge=j(process.env.CHECKSUM_RUNTIME_REPO_MODE),Ln=Ge?J.join(fe,"package","pw-report-template.html"):J.join(fe,"pw-report-template.html"),On=j(process.env.CHECKSUM_DEBUG_ANALYTICS),Mn=j(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),kn=qt(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),Ce={isDevMode:Qt,isRepoMode:Ge,CI:!!process.env.CI,checksumRootFolderBypass:Ge&&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:fe+"/checksumlib.js"},runtimeRoot:fe,playwrightReporter:{htmlReportTemplatePath:Ln},bypassProxyForLocalhost:j(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:j(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:j(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!j(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:j(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:kn},monitoring:{debugAnalytics:On,logToConsole:Mn,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:j(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:j(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:j(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:j(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:j(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 Js=require("@playwright/test/reporter");var oe=require("path");var ze=i((e,t,r)=>`v2:${Pn(e)}::${JSON.stringify([...t,r])}`,"computeVariantKey"),Pn=i(e=>(e??"").replace(/\\/g,"/"),"normalizeFilePath");var Ae=require("fs"),F=de(require("typescript"));var Un=/^[0-9a-zA-Z]+$/,Fn=5;function tr(e){return e?e.length===Fn&&Un.test(e):!1}i(tr,"isValidChecksumTestId");var Ke=class{static{i(this,"FileNameExtractionStrategy")}extract(t,r){if(!t)return;let n=t.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}},Ze=class{static{i(this,"FileContentExtractionStrategy")}extract(t,r){if(!(!t||!(0,Ae.existsSync)(t)))try{let n=(0,Ae.readFileSync)(t,"utf-8"),o=F.createSourceFile(t,n,F.ScriptTarget.Latest,!0),a=new Map,s=i(l=>{if(F.isCallExpression(l)){let p=l;if(this.isTestCall(p.expression)){let m=p.arguments[0];if(m&&F.isCallExpression(m)&&F.isIdentifier(m.expression)&&m.expression.text==="defineChecksumTest"){let y=this.extractDefineChecksumTestArgs(m);y&&tr(y.checksumTestId)&&a.set(y.testTitle,y.checksumTestId)}}}F.forEachChild(l,s)},"visit");return s(o),r&&a.has(r)?a.get(r):a.size>0?Array.from(a.values())[0]:void 0}catch{return}}isTestCall(t){return F.isIdentifier(t)&&t.text==="test"?!0:F.isPropertyAccessExpression(t)?F.isIdentifier(t.expression)&&t.expression.text==="test":!1}extractDefineChecksumTestArgs(t){let r=t.arguments;if(r.length<2)return;let n=r[0],o=r[1];if(!n||!o)return;let a=this.extractStringLiteral(n),s=this.extractStringLiteral(o);if(a&&s)return{testTitle:a,checksumTestId:s}}extractStringLiteral(t){if(F.isStringLiteral(t)||F.isNoSubstitutionTemplateLiteral(t))return t.text}},Je=class{static{i(this,"ChecksumTestIdExtractor")}constructor(t){this.strategies=t??[new Ze,new Ke]}extract(t,r){for(let n of this.strategies){let o=n.extract(t,r);if(o)return o}}};var rr=new Je;function be(e,t){return t.pwTestIdToChecksumTestId[e.playwrightTestId]||(e.filePath!==void 0?rr.extract(e.filePath,e.title):void 0)}i(be,"resolveChecksumTestId");var qe=i((e,t)=>Object.values(t[e]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),Ye=i(e=>typeof e=="number"&&!isNaN(e)?e:0,"getStat");function Xe(e,t,r){let n=[],o=0,a=0,s=Ye(t.expected)+Ye(t.flaky),l=Ye(t.unexpected);for(let p of e){let m=Bn(p,r);n.push(m),m.recovered&&a++,m.bug&&(o++,m.outcome==="expected"||m.outcome==="flaky"?s--:m.outcome==="unexpected"&&l--)}return{passed:s,failed:l,bug:o,recovered:a,tests:n}}i(Xe,"computeReportStats");function Bn(e,t){let r=be({playwrightTestId:e.playwrightTestId,filePath:e.filePath,title:e.title},t),n=Hn(e),o=Wn(e.annotations),a=qe(e.playwrightTestId,t.playwrightIdToMetadata),s=$n(r,e,t),l=t.toRelativeFilePath(e.filePath);return{checksumTestId:r,playwrightTestId:e.playwrightTestId,success:e.ok,recovered:a,bug:n,annotations:o,tags:e.tags,outcome:e.outcome,variantKey:ze(e.filePath,e.titlePath,e.title),...e.filePath!==void 0?{filePath:e.filePath}:{},...l!==void 0?{relativeFilePath:l}:{},...e.projectName?{project:e.projectName}:{},...e.errorMessage?{errorMessage:e.errorMessage}:{},...s!==void 0?{usingChecksumTestIdPlaceholder:s}:{}}}i(Bn,"rowToTestWithMetadata");function nr(e,t){let r=e.files,n=i(l=>{let m=be({playwrightTestId:l.testId,filePath:l.location.file,title:l.title},t)??`${l.location.file}::${l.title}`,y=ze(l.location.file,l.path??[],l.title);return`${m}::${l.projectName}::${y}`},"keyFor"),o=new Map;for(let l of r)for(let p of l.tests)o.set(n(p),p);let a=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(p=>a.has(p));for(let p of l.tests)s.total++,p.outcome==="expected"?s.expected++:p.outcome==="unexpected"?s.unexpected++:p.outcome==="flaky"?s.flaky++:s.skipped++}e.files=r.filter(l=>l.tests.length>0),e.stats={...e.stats,...s}}i(nr,"dedupeReportByChecksumTestId");var Hn=i(e=>e.tags.includes("bug")||e.annotations.some(t=>t.type==="bug")||e.title.includes("@bug"),"detectBug"),Wn=i(e=>e.filter(t=>!!t?.type).map(t=>({type:t.type,description:t.description||""})),"normalizeAnnotations"),$n=i((e,t,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[t.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[e]||!1},"computeUsingPlaceholder");var or=i((e,t,r)=>{if(!e)return;let n=r||t,o;if((0,oe.isAbsolute)(e))o=e;else{let a=(0,oe.dirname)(t);o=(0,oe.resolve)(a,e)}return o.replace(n+"/","")},"toRelativeFilePath");var sr=require("node:util");var se=8*1024,ge=`
|
|
4
|
-
\u2026 [truncated]`,Gn=/[\u001b\u0080-\u009f]/g;function Qe(e){let t=e.replaceAll("\0","");return jn((0,sr.stripVTControlCharacters)(t))}i(Qe,"sanitizeTestErrorMessage");function jn(e){return e.replace(Gn,"")}i(jn,"removeResidualVTControls");function we(e){let t=Qe(e);if(Buffer.byteLength(t,"utf8")<=se)return{value:t,truncated:!1};let r=se-Buffer.byteLength(ge,"utf8"),n="",o=0;for(let a of t){let s=Buffer.byteLength(a,"utf8");if(o+s>r)break;n+=a,o+=s}return{value:n+ge,truncated:!0}}i(we,"boundTestErrorMessage");var ar=require("node:crypto");var Vn=new Set(["failed","timedOut","interrupted"]),et=new WeakMap;function cr(){let e={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return et.set(e,new Map),e}i(cr,"createErrorDetailIndex");function lr(e,t){try{let r=zn(e);if(!r||Kn(r.tests))return!1;for(let n of r.tests){if(!ie(n))continue;let o=gr(n.projectName),a=n.testId;if(o===void 0||!ve(a))continue;let s=Zn(n);if(!s)continue;let l=Yn(s);l.truncated&&(t.truncatedCount+=1),Qn(t,fr(r.fileId,o,a),l.value,Xn(s))}return!0}catch{return!1}}i(lr,"addTestFileErrorDetails");function dr(e){return ie(e)&&Object.prototype.hasOwnProperty.call(e,"fileId")&&Object.prototype.hasOwnProperty.call(e,"tests")}i(dr,"isTestFileErrorDetailCandidate");function ur(e,t,r,n){let o=gr(r);if(!ve(t)||o===void 0||!ve(n))return;let a=fr(t,o,n);if(!e.ambiguousKeys.has(a))return e.messages.get(a)}i(ur,"getTestErrorMessage");function zn(e){if(!ie(e))return;let t=e.fileId,r=e.tests;if(!(!ve(t)||!Array.isArray(r)))return{fileId:t,tests:r}}i(zn,"parseTestFile");function Kn(e){return e.length>0&&!e.some(ie)}i(Kn,"hasOnlyMalformedTests");function Zn(e){let t=e.results;if(!Array.isArray(t))return;let r=t.at(-1);if(!ie(r))return;let n=r.status;if(typeof n!="string"||!Vn.has(n))return;let o=r.errors;if(Array.isArray(o))for(let a of o){let s=Jn(a);if(s)return s}}i(Zn,"extractFinalErrorDetail");function Jn(e){if(typeof e=="string"){let n=pr(e);return n?{message:n}:void 0}if(!ie(e))return;let t=ir(e.message,e.value),r=ir(e.codeframe,e.snippet);return t?!r||t.includes(r)?{message:t}:{message:t,frame:r}:r?{frame:r}:void 0}i(Jn,"normalizeError");function Yn(e){let{message:t,frame:r}=e;if(!t)return we(r??"");if(!r)return we(t);let n=Buffer.byteLength(t,"utf8");if(n>se)return we(t);let o=`
|
|
5
|
-
|
|
6
|
-
`,
|
|
7
|
-
|
|
8
|
-
`,"utf8"),e.frame&&t.update(e.frame,"utf8"),t.digest("hex")}i(Xn,"digestNormalizedErrorDetail");function pr(e){let t=Qe(e);return t.trim().length===0?"":t.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}i(pr,"normalizeErrorText");function Qn(e,t,r,n){if(e.ambiguousKeys.has(t))return;let o=et.get(e);if(o||(o=new Map,et.set(e,o)),e.messages.get(t)===void 0){e.messages.set(t,r),o.set(t,n);return}o.get(t)!==n&&(e.messages.delete(t),o.delete(t),e.ambiguousKeys.add(t),e.identityConflictCount+=1)}i(Qn,"addErrorDetail");function fr(e,t,r){return JSON.stringify([e,t,r])}i(fr,"createIdentityKey");function ir(...e){for(let t of e){if(typeof t!="string")continue;let r=pr(t);if(r)return r}}i(ir,"firstMeaningfulString");function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ie,"isRecord");function gr(e){return e==null||e===""?"":typeof e=="string"?e:void 0}i(gr,"normalizeProjectName");function ve(e){return typeof e=="string"&&e.length>0}i(ve,"isNonEmptyString");var eo=i(e=>Number.isSafeInteger(e)&&e>=0?Math.min(e,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),to=i(e=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(e)}`,"utf8"),"serializedErrorMessagePropertyBytes");function mr(e,t=8388608){let r=eo(t),n=0,o=e.tests?.map(a=>{if(a.errorMessage===void 0)return a;let s=to(a.errorMessage);if(s<=r)return r-=s,a;n+=1;let l={...a};return delete l.errorMessage,l});return{stats:{...e,...o!==void 0?{tests:o}:{}},omittedCount:n}}i(mr,"applyErrorDetailsPayloadBudget");var no=i((e,t)=>e.files.flatMap(r=>r.tests.map(n=>{let o=t?ur(t,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??[],...o?{errorMessage:o}:{}}})),"htmlReportToRows"),De=class e{constructor(t,r,n,o={},a={},s,l,p,m={}){this.reportHTMLFilePath=t;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=o;this.channel=s;this.checksumTestIdToUsingPlaceholder=m;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...a},this.checksumRoot=l||(0,ee.dirname)((0,ee.dirname)(t)),this.projectRoot=p||this.checksumRoot}static{i(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let t=0;try{t=(0,B.statSync)(this.reportHTMLFilePath)?.size||0,this.channel.debug(`Report HTML file size approximately ${t} bytes`)}catch(a){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,a)}let r=(0,ee.join)((0,Er.tmpdir)(),`pw-report-${(0,Tr.randomUUID)()}.zip`),n=i(()=>{try{(0,B.existsSync)(r)&&(0,B.unlinkSync)(r)}catch{}},"cleanupFile"),o={sigterm:i(()=>{n(),process.exit(143)},"sigterm"),sigint:i(()=>{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 a=Date.now();await this.extractBase64ToFile(r);let s=Date.now()-a;this.channel.debug("Modifying ZIP file...");let l=Date.now(),p=this.modifyZipFile(r),m=Date.now()-l;this.channel.debug("Writing output HTML...");let y=Date.now();await this.writeOutputWithStreamedZip(r);let T=Date.now()-y;return{report_html_bytes:t,extract_ms:s,modify_ms:m,write_ms:T,entry_count:p.entryCount,json_entry_count:p.jsonEntryCount,largest_entry_bytes:p.largestEntryBytes,largest_entry_name:p.largestEntryName,error_details_extracted:p.errorDetailsExtracted,error_details_truncated:p.errorDetailsTruncated,error_detail_parse_failures:p.errorDetailParseFailures,error_detail_identity_conflicts:p.errorDetailIdentityConflicts,error_details_payload_budget_omitted:p.errorDetailsPayloadBudgetOmitted}}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(t){return new Promise((r,n)=>{let o=!1,a=!1,s=!1,l=[],p=0,m=(0,B.createWriteStream)(t);m.on("error",u=>{if(!a){a=!0;try{C.destroyed||C.destroy(),S.end()}catch{}n(u)}});let y=i(()=>{if(p<4)return;let u=l.join("");l.length=0,s||(u=u.replace("data:application/zip;base64,",""),s=!0);let f=Math.floor(u.length/4)*4,d=u.slice(0,f),h=u.slice(f);if(h.length>0?(l.push(h),p=h.length):p=0,d.length>0){let E=Buffer.from(d,"base64");m.write(E)}},"flushBuffer"),T=i(u=>ct.includes(u),"isPayloadTag"),S=new hr.Parser({onopentag:i((u,f)=>{T(u)&&f.id==="playwrightReportBase64"&&(o=!0)},"onopentag"),ontext:i(u=>{o&&(l.push(u),p+=u.length,p>1024*1024&&y())},"ontext"),onclosetag:i(u=>{if(T(u)&&o&&!a){if(a=!0,p>0){let f=l.join("");if(s||(f=f.replace("data:application/zip;base64,","")),f.length>0){let d=Buffer.from(f,"base64");m.write(d)}}try{C.destroyed||C.destroy()}catch{}m.end(()=>r())}},"onclosetag"),onerror:i(u=>{if(!a){a=!0;try{S.end(),C.destroyed||C.destroy(),m.destroyed||m.destroy()}catch{}n(u)}},"onerror")}),C=(0,B.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});C.on("data",u=>S.write(u.toString())),C.on("end",()=>{if(S.end(),!a){a=!0;try{m.destroyed||m.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),C.on("error",u=>{if(!a){a=!0;try{S.end(),m.destroyed||m.destroy()}catch{}n(u)}})})}modifyZipFile(t){let r=new yr.default(t),n=r.getEntries(),o=cr(),a,s,l=0,p=0,m=0,y="";for(let S of n){if(S.isDirectory||!S.entryName.endsWith(".json"))continue;let C=S.getData().toString("utf8");if(p+=1,C.length>m&&(m=C.length,y=S.entryName),S.entryName==="report.json")a=JSON.parse(C),s=S;else{let u=this.replaceAttachmentPaths(C);S.setData(Buffer.from(u,"utf8"));try{let f=JSON.parse(u);dr(f)&&!lr(f,o)&&(l+=1)}catch{l+=1}}}if(!a||!s)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&nr(a,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(a),this.report=a;let T=this.extractStats(a,o);return s.setData(Buffer.from(JSON.stringify(a),"utf8")),r.writeZip(t),{entryCount:n.length,jsonEntryCount:p,largestEntryBytes:m,largestEntryName:y,errorDetailsExtracted:o.messages.size,errorDetailsTruncated:o.truncatedCount,errorDetailParseFailures:l,errorDetailIdentityConflicts:o.identityConflictCount,errorDetailsPayloadBudgetOmitted:T}}replaceAttachmentPaths(t){return t.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(t){let r=this.getTemplate(),n=this.getProcessedFilePath(),o=n.replace(".html",".backup.html");(0,B.copyFileSync)(n,o);let a=(0,B.createWriteStream)(n);await new Promise((s,l)=>{a.on("error",l),a.write(r),a.write(lt+"data:application/zip;base64,");let p=(0,B.createReadStream)(t,{highWaterMark:3*1024*1024});p.on("data",m=>{let T=(typeof m=="string"?Buffer.from(m):m).toString("base64");a.write(T)||p.pause()}),a.on("drain",()=>{p.resume()}),p.on("end",()=>{a.write(dt),a.end(()=>s())}),p.on("error",m=>{try{a.destroyed||a.destroy()}catch{}l(m)}),a.on("error",m=>{try{p.destroyed||p.destroy()}catch{}l(m)})})}testHasTrace(t,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(a=>this.pwTestIdToChecksumTestId[a]===t);if(!n)return!0;let o=i(a=>a.some(s=>s.attachments?.some(l=>l.name==="trace")),"hasTrace");for(let a of this.report.files)for(let s of a.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 e.templateCache||(e.templateCache=(0,B.readFileSync)(Ce.playwrightReporter.htmlReportTemplatePath,"utf-8")),e.templateCache}getReportsStats(){return this.stats}extractStats(t,r){if(!t.stats)return 0;let n=Xe(no(t,r),t.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:i(a=>or(a,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),o=mr(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=o.stats,o.omittedCount}makeAttachmentPath(t){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,ee.basename)(t)}`:t}handleReportJSON(t){let r={},n=i(o=>{let a=o.testId,s=this.playwrightIdToMetadata[a];s&&(r[a]=s);let l=be({playwrightTestId:o.testId,filePath:o.location?.file,title:o.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});l!==void 0&&(o.checksumTestId=l),o.results.forEach(p=>{this.processAttachments(p.attachments)})},"getChecksumMetadataForPWTestId");t.files.forEach(o=>{o.tests.forEach(n)}),t.checksumMetadata=r}processAttachments(t){if(t.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=t.findIndex(n=>n.name==="video");r!==-1&&t.splice(r,1)}}updateAttachment(t){t.path&&(t.path=this.makeAttachmentPath(t.path))}};var _r={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},oo={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},Ti=Object.fromEntries(Object.entries(oo).map(e=>e.reverse())),so={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"},_i=Object.fromEntries(Object.entries(so).map(e=>e.reverse()));var Ii={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]},Ri={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 Oe=require("fs"),vr=require("path"),Dr=require("stream");var Ir=i(e=>{if(e.error!=null)return"ERROR";let t=e.status_code;if(typeof t=="number"&&t>=500)return"ERROR";let r=e.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var tt=require("fs");var Rr="\x1B[31m",io="\x1B[33m",ao="\x1B[32m",co="\x1B[36m",lo="\x1B[2m",uo="\x1B[1m",me="\x1B[0m",po=i(()=>{let e=process.env.WIDE_EVENT_PRETTY;return e==="true"||e==="1"?!0:e==="false"||e==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),fo=new Set(["severity","message","kind","timestamp","_startedAtMs"]),go=i(e=>{let t=new WeakSet;return JSON.stringify(e,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},"safeStringify"),mo=i(e=>e==="ERROR"||e==="CRITICAL"?Rr:e==="WARNING"?io:ao,"colorForSeverity"),ho=i(e=>{let t=String(e.severity??"INFO"),r=`${mo(t)}${t.padEnd(5)}${me}`,n=e.kind?`${co}${e.kind}${me}`:"",o=String(e.message??""),a=e.error&&typeof e.error=="object"?(()=>{let y=e.error;return` ${Rr}${y.type??"Error"}: ${y.message??""}${me}`})():"",s=["outcome","test_suite_run_id","status"],l=Object.entries(e).filter(([y,T])=>!fo.has(y)&&T!=null&&y!=="error"&&typeof T!="object"),p=i(y=>{let T=s.indexOf(y);return T===-1?s.length:T},"rank"),m=l.sort(([y],[T])=>p(y)-p(T)).slice(0,8).map(([y,T])=>`${lo}${y}=${me}${T}`).join(" ");return[r,uo+n+me,o,m,a].filter(y=>y&&y.trim()!=="").join(" ")},"formatPretty"),yo=i(e=>{let t=e.trace_id;if(typeof t!="string"||t==="")return e;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...e,"logging.googleapis.com/trace":`projects/${r}/traces/${t}`}:e},"withGcpTraceField"),Sr=i(e=>{let t=po()?ho(e):go(yo(e));(0,tt.writeSync)(1,t+`
|
|
9
|
-
`)},"emitEvent");var Cr=i(e=>{(0,tt.writeSync)(2,e.endsWith(`
|
|
10
|
-
`
|
|
11
|
-
`)}
|
|
12
|
-
`)}{/trm}`)}event(t,r){return new Promise(n=>{let o=r?`${t}=${r}`:t;setTimeout(()=>{this.sendToCLI(`monitor:${o}`),n(!0)},100)})}trace(t,r){let n=r?`${t}=${JSON.stringify(r)}`:t;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(t){return this.event("log",t)}debug(...t){this.sendToCLI(t)}wideEvent(t){let r=Buffer.from(JSON.stringify(t),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},Me=class{constructor(t,r=!1){this.config=t;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 ot,nt(n=>this.channel.wideEvent(n)),this.testAssetUploader=new Le(t.apiURL,t.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:i(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:i(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:i((n,o)=>this.channel.trace("Upload Failed",{filename:n,error:o}),"error")},t.sessionId),setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL),this.listenForMessages(),this.startServer()}static{i(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",t=>{(async()=>{let r=t.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 a=Buffer.from(o??"","base64").toString("utf-8"),s=JSON.parse(a);await this.handleReport(s)}catch(a){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(a)),this.reportComplete=!0}else this.reportComplete=!0;this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(t){try{let r=await(0,Lr.readFile)(t,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${t}: ${r.message}`),{}}}async serveReport(t){try{let r=(0,V.dirname)(t);await this.channel.log("Serving report in browser: "+r);let n=Ce.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,Nr.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(t){let{reportPath:r,pathToChecksumMetadata:n,didFail:o,openReportCriteria:a,checksumRoot:s,projectRoot:l,isUploadReport:p,dedupeByChecksumTestId:m}=t;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,V.dirname)(r),p);let y=ae("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!p});try{let T=await this.readMetadataFile(n),S=new De(r,this.config.sessionId,this.pwTestIdToChecksumTestId,T,{hosted:!this.isolationMode,...m?{dedupeByChecksumTestId:m}:{}},this.channel,s,l,this.checksumTestIdToUsingPlaceholder),C=this.initAsset({type:"report",path:""});this.reportAsset=C;try{let d=await S.process();C.info.path=S.getProcessedFilePath(),y.set({processed_path:C.info.path,...d}),this.uploadAsset(C)}catch(d){this.channel.debug("Error processing report, "+d.message),C.error=!0,y.set({error:Y(d)})}let u=S.getReportsStats();this.stats=u,at(y,C.error?"error":"success",u),this.channel.debug("Checking watch assets");let f=this.watchAssets.filter(d=>!(d.type!=="trace"||S.testHasTrace(d.testId??"",d.project??"")));f.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(f.map(d=>d.path)))),this.watchAssets=this.watchAssets.filter(d=>d.type!=="trace"||S.testHasTrace(d.testId??"",d.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((a==="always"||a==="on-failure"&&o)&&await this.serveReport(r),n&&(0,k.existsSync)(n))try{(0,k.unlinkSync)(n)}catch(S){console.error(`Error deleting checksum metadata file ${n}: ${S.message}`)}}}async uploadReportData(t,r){let n=(0,V.join)(t,"data");try{let o=(0,k.readdirSync)(n),a=r?[".webm"]:[".zip",".webm"],s=o.filter(l=>!a.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(){if(!this.reportComplete&&this.reportAsset&&(this.reportAsset.complete||this.reportAsset.error)){this.reportComplete=!0;let t="";try{let r=JSON.stringify(this.stats),n=`checksum-stats-${(0,he.randomBytes)(8).toString("hex")}.json`;t=(0,V.join)((0,Pr.tmpdir)(),n),(0,k.writeFileSync)(t,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${t}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportAsset?.complete?"true":"false"}:${t}`)}if(!this.processingInProgress&&this.reportComplete&&(this.assets.filter(t=>t.complete||t.error).length===this.assets.length||this.isUploadStalled())&&(this.watchAssets.length===0||this.testRunEndTime&&Date.now()-this.testRunEndTime>this.WATCH_TIMEOUT)){let t=Date.now(),r=this.assets.filter(s=>!s.complete&&!s.error);this.assets.forEach(s=>{!s.complete&&!s.error&&(s.error=!0)});let n=this.assets.find(s=>s.error)?"uploads-complete-with-errors":"uploads-complete",o=this.assets.filter(s=>s.error);xe("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:o.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(s=>s.complete).length,errored:o.length,stalled:r.length>0,stalled_count:r.length,watch_remaining:this.watchAssets.length,report_complete:this.reportComplete,upload_finalize_ms:this.testRunEndTime?t-this.testRunEndTime:void 0,errored_assets:o.map(s=>this.assetSnapshot(s,t))});let a=n==="uploads-complete"?{}:{uploadErrors:this.assets.filter(s=>s.error).map(s=>{try{return JSON.stringify(s)}catch{return s.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:Date.now()};try{this.cleanUp()}catch(s){this.channel.debug("cleanUp failed (ignored): "+s?.message)}this.channel.event(n,JSON.stringify(a));return}await ke(1e3),this.monitorUploadsCompletion()}assetSnapshot(t,r){return{file_name:t.info.fileName??(0,V.basename)(t.info.path),asset_type:t.info.type,test_id:t.info.testId,loaded_bytes:t.loadedBytes,size_bytes:t.sizeBytes,last_progress_age_ms:t.lastProgress?r-t.lastProgress:void 0}}cleanUp(){let t;for(let r of this.assets)if(r.info.type==="rrweb-recording"){t=(0,V.dirname)(r.info.path);break}t&&(0,k.rmSync)(t,{recursive:!0,force:!0})}isUploadStalled(){let t=xr(this.assets,this.UPLOAD_STALL_TIMEOUT);if(t&&(this.channel.log("Uploads are stalled"),!this.stallEventEmitted)){this.stallEventEmitted=!0;let r=Date.now(),n=this.assets.filter(o=>!o.complete&&!o.error);xe("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 t}async startServer(){let t=await this.acquirePortNumber();this.channel.event("port",t.toString()),this.server=(0,Mr.createServer)((r,n)=>{let o=i(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 a="";r.on("data",s=>{a+=s.toString()}),r.on("end",()=>{let s;try{s=JSON.parse(a)}catch{o("Invalid body");return}let{type:l,payload:p,watch:m}=s;switch(this.channel.debug(`Server received message, ${l}, ${this.stringify(p)}`),l){case"asset":if(!p.path||!p.type){o("Missing arguments");return}m?this.watchAsset(p):this.processAsset(p);break;case"testInfo":if(!p.pwTestId||!p.checksumTestId){o("Missing arguments");return}this.pwTestIdToChecksumTestId[p.pwTestId]=p.checksumTestId,p.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[p.checksumTestId]=p.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let y=p;if(!y.checksumTestId||!p.data){o("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...y}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(p));break;case"runProgress":this.forwardProgress(p);break;default:o("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(t)}forwardProgress(t){this.latestProgress=t,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let t=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(t)}}finally{this.progressFlushInFlight=!1}}async patchProgress(t){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:t}),signal:r.signal})}catch(o){this.channel.debug("Failed to send run progress: "+o?.message)}finally{clearTimeout(n)}}stringify(t){try{return JSON.stringify(t)}catch{return"message"in t?t.message:t}}monitorUploads(){let{totalSizeBytes:t,totalUploadedBytes:r}=this.calculateUploadProgress();if(t>0&&!this.isolationMode){let a=(r/t*100).toFixed(2);this.channel.event("upload-progress",a)}let n=this.assets.filter(a=>!a.uploadStarted);if(n.length===0)return;let o=i(()=>this.assets.filter(a=>a.uploadStarted&&!a.complete&&!a.error).length,"getNumOfActiveUploads");if(!(o()>=this.MAX_UPLOADS))for(;n.length>0&&o()<this.MAX_UPLOADS;){let a=n.pop();if(a===void 0)break;this.uploadAsset(a)}}calculateUploadProgress(){let t=this.assets.reduce((n,{sizeBytes:o})=>n+(o??0),0),r=Math.min(t,this.assets.reduce((n,{loadedBytes:o})=>n+(o??0),0));return{totalSizeBytes:t,totalUploadedBytes:r}}getUploadLogMessage(t){switch(t.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${t.info.testId}`;case"trace":return`Uploading trace file for test ${t.info.testId}`;case"esra":return`Uploading metadata file for test ${t.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${t.info.path}`;default:return}}async uploadAsset(t){try{t.uploadStarted=!0;let r=this.getUploadLogMessage(t);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(t)}catch(r){t.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:t.info.fileName,error:String(r)})}}async getSignedURLForUpload(t){try{let{apiKey:r,sessionId:n,apiURL:o}=this.config,a=t.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(a)}),{url:l}=await Ne(s,{resource:"get-upload-url",requiredFields:["url"]});t.uploadURL=l}catch(r){this.channel.debug("Error getting signed URL for artifact"+this.stringify(r))}}watchAsset(t){if(this.watchAssets.some(n=>n.path===t.path)){this.channel.debug(`Already watching file ${t.path}, skipping duplicate`);return}this.channel.debug("Watching file "+t.path),this.watchAssets.push({...t,addedAt:Date.now()});let r=i(async()=>{await this.waitForFileComplete(t.path)&&(this.processAsset(t),this.watchAssets=this.watchAssets.filter(o=>o.path!==t.path))},"waitForCompletion");if((0,k.existsSync)(t.path))r();else{let n=(0,V.dirname)(t.path),o=(0,V.basename)(t.path),a=!1,s=(0,k.watch)(n,(l,p)=>{(async()=>{if(!(p!==o||a))try{this.channel.debug("Watched file changed "+t.path),a=!0,await r()}finally{s.close()}})()})}}waitForFileComplete(t,r=1e3,n=6e4,o=1){return new Promise(a=>{let s=Date.now(),l=0,p=i(()=>{if(!(0,k.existsSync)(t)){this.channel.debug(`Asset required for upload doesn't exist anymore ${t}`),a(!1);return}let m=(0,k.statSync)(t).size;if(m===l){if(o>0){this.channel.debug(`File size has not changed, verifying stabilization, ${t}, size: ${m}, equalSizeValidationCountLeft: ${o}`),o--,setTimeout(p,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${t}, size: ${m}`),a(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${t}, previous size: ${l}, current size: ${m}`),Date.now()-s>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${t}`),a(!0);return}l=m,setTimeout(p,r)},"checkFile");p()})}processAsset(t){switch(t.type){case"trace":return this.processTrace(t.path,t.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(t);default:return}}async processHar(){}async calculateFileSha1Streaming(t){let r=(0,he.createHash)("sha1"),n=(0,k.createReadStream)(t);return await(0,Or.pipeline)(n,r),r.digest("hex")}async processTrace(t,r){if(this.processingPaths.has(t)){this.channel.debug(`Trace file ${t} already being processed, skipping`);return}this.processingPaths.add(t);let n;try{this.processingInProgress=!0,await ke(1e3),n=ae("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let o=t;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),o=t.replace(".zip",".actual.zip"),(0,k.renameSync)(t,o);let l="checksum-playwright-trace:"+Date.now().toString()+(0,he.randomBytes)(1024).toString("hex");(0,k.writeFileSync)(t,l)}let s=await i(async()=>await this.calculateFileSha1Streaming(t)+(0,V.extname)(t),"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?.emit({outcome:"success",file_name:s})}catch(o){let a=String(o);this.channel.debug("Error processing trace file"+a),this.channel.trace("Trace Processing Error",{error:a}),n?.emit({outcome:"error",error:Y(o)})}finally{this.processingPaths.delete(t),this.processingInProgress=!1}}addAsset(t){this.channel.debug("Adding file "+t.path);let r=this.initAsset(t);return this.assets.push(r),r}initAsset(t){return{complete:!1,error:!1,info:t,removeAfterUpload:t.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((t,r)=>{let n=kr.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let o=n.address().port;n.close(()=>{t(o)})})})}},Ur;try{Ur=JSON.parse(process.argv[2]??"")}catch(e){console.log("Error starting test run monitor",e),process.exit(1)}new Me(Ur,process.argv?.[3]==="isolated");0&&(module.exports={TestRunMonitor});
|
|
1
|
+
"use strict";var sm=Object.create;var Yr=Object.defineProperty;var am=Object.getOwnPropertyDescriptor;var om=Object.getOwnPropertyNames;var cm=Object.getPrototypeOf,lm=Object.prototype.hasOwnProperty;var a=(t,e)=>Yr(t,"name",{value:e,configurable:!0});var re=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},um=(t,e)=>{for(var r in e)Yr(t,r,{get:e[r],enumerable:!0})},jo=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of om(e))!lm.call(t,i)&&i!==r&&Yr(t,i,{get:()=>e[i],enumerable:!(n=am(e,i))||n.enumerable});return t};var He=(t,e,r)=>(r=t!=null?sm(cm(t)):{},jo(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t)),dm=t=>jo(Yr({},"__esModule",{value:!0}),t);var $c=re((sS,gs)=>{"use strict";var Zm=Object.prototype.hasOwnProperty,ke="~";function Qr(){}a(Qr,"Events");Object.create&&(Qr.prototype=Object.create(null),new Qr().__proto__||(ke=!1));function Ym(t,e,r){this.fn=t,this.context=e,this.once=r||!1}a(Ym,"EE");function Uc(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new Ym(r,n||t,i),o=ke?ke+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}a(Uc,"addListener");function $n(t,e){--t._eventsCount===0?t._events=new Qr:delete t._events[e]}a($n,"clearEvent");function Ie(){this._events=new Qr,this._eventsCount=0}a(Ie,"EventEmitter");Ie.prototype.eventNames=a(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Zm.call(r,n)&&e.push(ke?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");Ie.prototype.listeners=a(function(e){var r=ke?ke+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o},"listeners");Ie.prototype.listenerCount=a(function(e){var r=ke?ke+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");Ie.prototype.emit=a(function(e,r,n,i,s,o){var c=ke?ke+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,i),!0;case 5:return l.fn.call(l.context,r,n,i,s),!0;case 6:return l.fn.call(l.context,r,n,i,s,o),!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 y=l.length,h;for(f=0;f<y;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,i);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];l[f].fn.apply(l[f].context,d)}}return!0},"emit");Ie.prototype.on=a(function(e,r,n){return Uc(this,e,r,n,!1)},"on");Ie.prototype.once=a(function(e,r,n){return Uc(this,e,r,n,!0)},"once");Ie.prototype.removeListener=a(function(e,r,n,i){var s=ke?ke+e:e;if(!this._events[s])return this;if(!r)return $n(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&$n(this,s);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==r||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[s]=l.length===1?l[0]:l:$n(this,s)}return this},"removeListener");Ie.prototype.removeAllListeners=a(function(e){var r;return e?(r=ke?ke+e:e,this._events[r]&&$n(this,r)):(this._events=new Qr,this._eventsCount=0),this},"removeAllListeners");Ie.prototype.off=Ie.prototype.removeListener;Ie.prototype.addListener=Ie.prototype.on;Ie.prefixed=ke;Ie.EventEmitter=Ie;typeof gs<"u"&&(gs.exports=Ie)});var Bc=re((oS,Fc)=>{"use strict";Fc.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 Hc=re((cS,Bn)=>{"use strict";var Xm=Bc(),Fn=class extends Error{static{a(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},jc=a((t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){i(l)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new Fn(o);typeof t.cancel=="function"&&t.cancel(),i(c)},e);Xm(t.then(n,i),()=>{clearTimeout(s)})}),"pTimeout");Bn.exports=jc;Bn.exports.default=jc;Bn.exports.TimeoutError=Fn});var zc=re(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});function Qm(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}a(Qm,"lowerBound");ys.default=Qm});var Gc=re(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var eh=zc(),_s=class{static{a(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 i=eh.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,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}};bs.default=_s});var Hn=re(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var th=$c(),Vc=Hc(),rh=Gc(),jn=a(()=>{},"empty"),nh=new Vc.TimeoutError,ws=class extends th{static{a(this,"PQueue")}constructor(e){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=jn,this._resolveIdle=jn,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:rh.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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${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=jn,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=jn,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,i)=>{let s=a(async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():Vc.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(nh)});n(await o)}catch(o){i(o)}this._next()},"run");this._queue.enqueue(s,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}};Es.default=ws});var Yd=re(Ni=>{"use strict";Ni.byteLength=K_;Ni.toByteArray=Z_;Ni.fromByteArray=Q_;var mt=[],Ke=[],q_=typeof Uint8Array<"u"?Uint8Array:Array,Ja="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(dr=0,Jd=Ja.length;dr<Jd;++dr)mt[dr]=Ja[dr],Ke[Ja.charCodeAt(dr)]=dr;var dr,Jd;Ke[45]=62;Ke[95]=63;function Zd(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]}a(Zd,"getLens");function K_(t){var e=Zd(t),r=e[0],n=e[1];return(r+n)*3/4-n}a(K_,"byteLength");function J_(t,e,r){return(e+r)*3/4-r}a(J_,"_byteLength");function Z_(t){var e,r=Zd(t),n=r[0],i=r[1],s=new q_(J_(t,n,i)),o=0,c=i>0?n-4:n,l;for(l=0;l<c;l+=4)e=Ke[t.charCodeAt(l)]<<18|Ke[t.charCodeAt(l+1)]<<12|Ke[t.charCodeAt(l+2)]<<6|Ke[t.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Ke[t.charCodeAt(l)]<<2|Ke[t.charCodeAt(l+1)]>>4,s[o++]=e&255),i===1&&(e=Ke[t.charCodeAt(l)]<<10|Ke[t.charCodeAt(l+1)]<<4|Ke[t.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}a(Z_,"toByteArray");function Y_(t){return mt[t>>18&63]+mt[t>>12&63]+mt[t>>6&63]+mt[t&63]}a(Y_,"tripletToBase64");function X_(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Y_(n));return i.join("")}a(X_,"encodeChunk");function Q_(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,c=r-n;o<c;o+=s)i.push(X_(t,o,o+s>c?c:o+s));return n===1?(e=t[r-1],i.push(mt[e>>2]+mt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(mt[e>>10]+mt[e>>4&63]+mt[e<<2&63]+"=")),i.join("")}a(Q_,"fromByteArray")});var no=re((e3,Tt)=>{var ro=require("fs"),Di=require("path"),vb=require("os"),Sb=require("crypto"),df=["\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 xb(){return df[Math.floor(Math.random()*df.length)]}a(xb,"_getRandomTip");function zr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}a(zr,"parseBoolean");function Ib(){return process.stdout.isTTY}a(Ib,"supportsAnsi");function Ab(t){return Ib()?`\x1B[2m${t}\x1B[0m`:t}a(Ab,"dim");var Cb=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Rb(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
+
`);let n;for(;(n=Cb.exec(r))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
|
|
3
|
+
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}a(Rb,"parse");function Ob(t){t=t||{};let e=hf(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=mf(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let c=n[o].trim(),l=Mb(r,c);s=me.decrypt(l.ciphertext,l.key);break}catch(c){if(o+1>=i)throw c}return me.parse(s)}a(Ob,"_parseVault");function kb(t){console.error(`\u26A0 ${t}`)}a(kb,"_warn");function En(t){console.log(`\u2506 ${t}`)}a(En,"_debug");function pf(t){console.log(`\u25C7 ${t}`)}a(pf,"_log");function mf(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(mf,"_dotenvKey");function Mb(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 i=r.searchParams.get("environment");if(!i){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let s=`DOTENV_VAULT_${i.toUpperCase()}`,o=t.parsed[s];if(!o){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:o,key:n}}a(Mb,"_instructions");function hf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)ro.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=Di.resolve(process.cwd(),".env.vault");return ro.existsSync(e)?e:null}a(hf,"_vaultPath");function ff(t){return t[0]==="~"?Di.join(vb.homedir(),t.slice(1)):t}a(ff,"_resolveHome");function Pb(t){let e=zr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=zr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&pf("loading env from encrypted .env.vault");let n=me._parseVault(t),i=process.env;return t&&t.processEnv!=null&&(i=t.processEnv),me.populate(i,n,t),{parsed:n}}a(Pb,"_configVault");function Nb(t){let e=Di.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let i=zr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),s=zr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:i&&En("no encoding is specified (UTF-8 is used by default)");let o=[e];if(t&&t.path)if(!Array.isArray(t.path))o=[ff(t.path)];else{o=[];for(let d of t.path)o.push(ff(d))}let c,l={};for(let d of o)try{let f=me.parse(ro.readFileSync(d,{encoding:r}));me.populate(l,f,t)}catch(f){i&&En(`failed to load ${d} ${f.message}`),c=f}let u=me.populate(n,l,t);if(i=zr(n.DOTENV_CONFIG_DEBUG||i),s=zr(n.DOTENV_CONFIG_QUIET||s),i||!s){let d=Object.keys(u).length,f=[];for(let y of o)try{let h=Di.relative(process.cwd(),y);f.push(h)}catch(h){i&&En(`failed to load ${y} ${h.message}`),c=h}pf(`injected env (${d}) from ${f.join(",")} ${Ab(`// tip: ${xb()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}a(Nb,"configDotenv");function Lb(t){if(mf(t).length===0)return me.configDotenv(t);let e=hf(t);return e?me._configVault(t):(kb(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}a(Lb,"config");function Db(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=Sb.createDecipheriv("aes-256-gcm",r,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let c=o instanceof RangeError,l=o.message==="Invalid key length",u=o.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 o}}a(Db,"decrypt");function Ub(t,e,r={}){let n=!!(r&&r.debug),i=!!(r&&r.override),s={};if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(t,o)?(i===!0&&(t[o]=e[o],s[o]=e[o]),n&&En(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(t[o]=e[o],s[o]=e[o]);return s}a(Ub,"populate");var me={configDotenv:Nb,_configVault:Pb,_parseVault:Ob,config:Lb,decrypt:Db,parse:Rb,populate:Ub};Tt.exports.configDotenv=me.configDotenv;Tt.exports._configVault=me._configVault;Tt.exports._parseVault=me._parseVault;Tt.exports.config=me.config;Tt.exports.decrypt=me.decrypt;Tt.exports.parse=me.parse;Tt.exports.populate=me.populate;Tt.exports=me});var io=re((R3,Ef)=>{Ef.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 Ui=re(vf=>{var Tf={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 Hb(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}a(Hb,"E");for(let t of Object.keys(Tf))vf[t]=Hb(Tf[t])});var Cf=re((M3,Af)=>{var zb=require("fs"),de=require("path"),Sf=io(),Gb=Ui(),Vb=typeof process=="object"&&process.platform==="win32",xf=a(t=>typeof t=="object"&&t!==null,"is_Obj"),If=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 ie(t){this.sep=de.sep,this.fs=zb,xf(t)&&xf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}a(ie,"Utils");Af.exports=ie;ie.prototype.makeDir=function(t){let e=this;function r(n){let i=n.split(e.sep)[0];n.split(e.sep).forEach(function(s){if(!(!s||s.substr(-1,1)===":")){i+=e.sep+s;var o;try{o=e.fs.statSync(i)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(i);else throw c}if(o&&o.isFile())throw Gb.FILE_IN_THE_WAY(`"${i}"`)}})}a(r,"mkdirSync"),r(t)};ie.prototype.writeFileTo=function(t,e,r,n){let i=this;if(i.fs.existsSync(t)){if(!r)return!1;var s=i.fs.statSync(t);if(s.isDirectory())return!1}var o=de.dirname(t);i.fs.existsSync(o)||i.makeDir(o);var c;try{c=i.fs.openSync(t,"w",438)}catch{i.fs.chmodSync(t,438),c=i.fs.openSync(t,"w",438)}if(c)try{i.fs.writeSync(c,e,0,e.length,0)}finally{i.fs.closeSync(c)}return i.fs.chmodSync(t,n||438),!0};ie.prototype.writeFileToAsync=function(t,e,r,n,i){typeof n=="function"&&(i=n,n=void 0);let s=this;s.fs.exists(t,function(o){if(o&&!r)return i(!1);s.fs.stat(t,function(c,l){if(o&&l&&l.isDirectory())return i(!1);var u=de.dirname(t);s.fs.exists(u,function(d){if(!d)try{s.makeDir(u)}catch{return i(!1)}let f=a(function(y){s.fs.write(y,e,0,e.length,0,function(h){s.fs.close(y,function(){if(h)return i(!1);s.fs.chmod(t,n||438,function(){i(!0)})})})},"writeToFd");s.fs.open(t,"w",438,function(y,h){y?s.fs.chmod(t,438,function(){s.fs.open(t,"w",438,function(g,b){if(g||!b)return i(!1);f(b)})}):h?f(h):i(!1)})})})})};ie.prototype.findFiles=function(t){let e=this;function r(n,i,s,o){typeof i=="boolean"&&(s=i,i=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!i||i.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&s){let f=e.fs.realpathSync(u);o.has(f)||(o.add(f),c=c.concat(r(u,i,s,o)))}}),c}return a(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ie.prototype.findFilesAsync=function(t,e){let r=this,n=[],i=!1,s=a(function(c){i||(i=!0,e(c,c?void 0:n))},"finish"),o=a(function(c,l,u){r.fs.readdir(c,function(d,f){if(d)return u(d);let y=f.length;if(!y)return u();f.forEach(function(h){let g=de.join(c,h);r.fs.stat(g,function(b,w){if(b)return u(b);if(!w){--y||u();return}if(n.push(de.normalize(g)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--y||u();return}r.fs.realpath(g,function(v,S){if(v)return u(v);if(l.has(S)){--y||u();return}l.add(S),o(g,l,function(p){if(p)return u(p);--y||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return s(c);o(t,new Set([l]),s)})};ie.prototype.getAttributes=function(){};ie.prototype.setAttributes=function(){};ie.crc32update=function(t,e){return If[(t^e)&255]^t>>>8};ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ie.crc32update(r,t[n++]);return~r>>>0};ie.methodToString=function(t){switch(t){case Sf.STORED:return"STORED ("+t+")";case Sf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ie.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ie.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ie.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]};ie.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,i=r.length;n<i;n++){var s=de.normalize(de.join(t,r.slice(n,i).join(de.sep)));if(s===t||s.startsWith(t+de.sep))return s}return de.normalize(de.join(t,de.basename(e)))};ie.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");ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ie.writeBigUInt64LE=function(t,e,r){let n=e>>>0,i=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(i,r+4)};ie.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)};ie.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};ie.isWin=Vb;ie.crcTable=If});var Of=re((N3,Rf)=>{var Wb=require("path");Rf.exports=function(t,{fs:e}){var r=t||"",n=s(),i=null;function s(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return a(s,"newAttr"),r&&e.existsSync(r)?(i=e.statSync(r),n.directory=i.isDirectory(),n.mtime=i.mtime,n.atime=i.atime,n.executable=(73&i.mode)!==0,n.readonly=(128&i.mode)===0,n.hidden=Wb.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 Mf=re((D3,kf)=>{kf.exports={efs:!0,encode:a(t=>Buffer.from(t,"utf8"),"encode"),decode:a(t=>t.toString("utf8"),"decode")}});var Vr=re(($3,Gr)=>{Gr.exports=Cf();Gr.exports.Constants=io();Gr.exports.Errors=Ui();Gr.exports.FileAttr=Of();Gr.exports.decoder=Mf()});var Nf=re((F3,Pf)=>{var Dt=Vr(),M=Dt.Constants;Pf.exports=function(){var t=20,e=10,r=0,n=0,i=0,s=0,o=0,c=0,l=0,u=0,d=0,f=0,y=0,h=0,g=0;t|=Dt.isWin?2560:768,r|=M.FLG_EFS;let b={extraLen:0},w=a(p=>Math.max(0,p)>>>0,"uint32"),v=a(p=>Math.max(0,p)&65535,"uint16"),S=a(p=>Math.max(0,p)&255,"uint8");return i=Dt.fromDate2DOS(new Date),{get made(){return t},set made(p){t=p},get version(){return e},set version(p){e=p},get flags(){return r},set flags(p){r=p},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(p){p?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(p){p?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(p){switch(p){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=p},get time(){return Dt.fromDOS2Date(this.timeval)},set time(p){p=new Date(p),this.timeval=Dt.fromDate2DOS(p)},get timeval(){return i},set timeval(p){i=w(p)},get timeHighByte(){return S(i>>>8)},get crc(){return s},set crc(p){s=w(p)},get compressedSize(){return o},set compressedSize(p){o=w(p)},get size(){return c},set size(p){c=w(p)},get fileNameLength(){return l},set fileNameLength(p){l=p},get extraLength(){return u},set extraLength(p){u=p},get extraLocalLength(){return b.extraLen},set extraLocalLength(p){b.extraLen=p},get commentLength(){return d},set commentLength(p){d=p},get diskNumStart(){return f},set diskNumStart(p){f=w(p)},get inAttr(){return y},set inAttr(p){y=w(p)},get attr(){return h},set attr(p){h=w(p)},get fileAttr(){return(h||0)>>16&4095},get offset(){return g},set offset(p){g=w(p)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return g+M.LOCHDR+b.fnameLen+b.extraLen},get localHeader(){return b},loadLocalHeaderFromBinary:a(function(p){var T=p.slice(g,g+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw Dt.Errors.INVALID_LOC();b.version=T.readUInt16LE(M.LOCVER),b.flags=T.readUInt16LE(M.LOCFLG),b.flags_desc=(b.flags&M.FLG_DESC)>0,b.method=T.readUInt16LE(M.LOCHOW),b.time=T.readUInt32LE(M.LOCTIM),b.crc=T.readUInt32LE(M.LOCCRC),b.compressedSize=T.readUInt32LE(M.LOCSIZ),b.size=T.readUInt32LE(M.LOCLEN),b.fnameLen=T.readUInt16LE(M.LOCNAM),b.extraLen=T.readUInt16LE(M.LOCEXT);let I=g+M.LOCHDR+b.fnameLen,C=I+b.extraLen;return p.slice(I,C)},"loadLocalHeaderFromBinary"),loadFromBinary:a(function(p){if(p.length!==M.CENHDR||p.readUInt32LE(0)!==M.CENSIG)throw Dt.Errors.INVALID_CEN();t=p.readUInt16LE(M.CENVEM),e=p.readUInt16LE(M.CENVER),r=p.readUInt16LE(M.CENFLG),n=p.readUInt16LE(M.CENHOW),i=p.readUInt32LE(M.CENTIM),s=p.readUInt32LE(M.CENCRC),o=p.readUInt32LE(M.CENSIZ),c=p.readUInt32LE(M.CENLEN),l=p.readUInt16LE(M.CENNAM),u=p.readUInt16LE(M.CENEXT),d=p.readUInt16LE(M.CENCOM),f=p.readUInt16LE(M.CENDSK),y=p.readUInt16LE(M.CENATT),h=p.readUInt32LE(M.CENATX),g=p.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:a(function(){var p=Buffer.alloc(M.LOCHDR);return p.writeUInt32LE(M.LOCSIG,0),p.writeUInt16LE(e,M.LOCVER),p.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),p.writeUInt16LE(n,M.LOCHOW),p.writeUInt32LE(i,M.LOCTIM),p.writeUInt32LE(s,M.LOCCRC),p.writeUInt32LE(o,M.LOCSIZ),p.writeUInt32LE(c,M.LOCLEN),p.writeUInt16LE(l,M.LOCNAM),p.writeUInt16LE(b.extraLen,M.LOCEXT),p},"localHeaderToBinary"),centralHeaderToBinary:a(function(){var p=Buffer.alloc(M.CENHDR+l+u+d);return p.writeUInt32LE(M.CENSIG,0),p.writeUInt16LE(t,M.CENVEM),p.writeUInt16LE(e,M.CENVER),p.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),p.writeUInt16LE(n,M.CENHOW),p.writeUInt32LE(i,M.CENTIM),p.writeUInt32LE(s,M.CENCRC),p.writeUInt32LE(o,M.CENSIZ),p.writeUInt32LE(c,M.CENLEN),p.writeUInt16LE(l,M.CENNAM),p.writeUInt16LE(u,M.CENEXT),p.writeUInt16LE(d,M.CENCOM),p.writeUInt16LE(f,M.CENDSK),p.writeUInt16LE(y,M.CENATT),p.writeUInt32LE(h,M.CENATX),p.writeUInt32LE(g,M.CENOFF),p},"centralHeaderToBinary"),toJSON:a(function(){let p=a(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:Dt.methodToString(n),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:p(o),size:p(c),fileNameLength:p(l),extraLength:p(u),commentLength:p(d),diskNumStart:f,inAttr:y,attr:h,offset:g,centralHeaderSize:p(M.CENHDR+l+u+d)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Df=re((j3,Lf)=>{var Je=Vr(),j=Je.Constants;Lf.exports=function(){var t=0,e=0,r=0,n=0,i=0;let s=a(()=>t>j.EF_ZIP64_OR_16||e>j.EF_ZIP64_OR_16||r>j.EF_ZIP64_OR_32||n>j.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(o){t=e=o},get totalEntries(){return e},set totalEntries(o){e=t=o},get size(){return r},set size(o){r=o},get offset(){return n},set offset(o){n=o},get commentLength(){return i},set commentLength(o){i=o},get mainHeaderSize(){return(s()?j.ZIP64HDR+j.END64HDR:0)+j.ENDHDR+i},loadFromBinary:a(function(o){if((o.length!==j.ENDHDR||o.readUInt32LE(0)!==j.ENDSIG)&&(o.length<j.ZIP64HDR||o.readUInt32LE(0)!==j.ZIP64SIG))throw Je.Errors.INVALID_END();o.readUInt32LE(0)===j.ENDSIG?(t=o.readUInt16LE(j.ENDSUB),e=o.readUInt16LE(j.ENDTOT),r=o.readUInt32LE(j.ENDSIZ),n=o.readUInt32LE(j.ENDOFF),i=o.readUInt16LE(j.ENDCOM)):(t=Je.readBigUInt64LE(o,j.ZIP64SUB),e=Je.readBigUInt64LE(o,j.ZIP64TOT),r=Je.readBigUInt64LE(o,j.ZIP64SIZB),n=Je.readBigUInt64LE(o,j.ZIP64OFF),i=0)},"loadFromBinary"),toBinary:a(function(){if(!s()){var o=Buffer.alloc(j.ENDHDR+i);return o.writeUInt32LE(j.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(t,j.ENDSUB),o.writeUInt16LE(e,j.ENDTOT),o.writeUInt32LE(r,j.ENDSIZ),o.writeUInt32LE(n,j.ENDOFF),o.writeUInt16LE(i,j.ENDCOM),o.fill(" ",j.ENDHDR),o}var o=Buffer.alloc(this.mainHeaderSize);let c=0;o.writeUInt32LE(j.ZIP64SIG,c),Je.writeBigUInt64LE(o,j.ZIP64HDR-j.ZIP64LEAD,c+j.ZIP64SIZE),o.writeUInt16LE(45,c+j.ZIP64VEM),o.writeUInt16LE(45,c+j.ZIP64VER),o.writeUInt32LE(0,c+j.ZIP64DSK),o.writeUInt32LE(0,c+j.ZIP64DSKDIR),Je.writeBigUInt64LE(o,t,c+j.ZIP64SUB),Je.writeBigUInt64LE(o,e,c+j.ZIP64TOT),Je.writeBigUInt64LE(o,r,c+j.ZIP64SIZB),Je.writeBigUInt64LE(o,n,c+j.ZIP64OFF);let l=n+r;return c+=j.ZIP64HDR,o.writeUInt32LE(j.END64SIG,c),o.writeUInt32LE(0,c+j.END64START),Je.writeBigUInt64LE(o,l,c+j.END64OFF),o.writeUInt32LE(1,c+j.END64NUMDISKS),c+=j.END64HDR,o.writeUInt32LE(j.ENDSIG,c),o.writeUInt32LE(0,c+4),o.writeUInt16LE(Math.min(t,j.EF_ZIP64_OR_16),c+j.ENDSUB),o.writeUInt16LE(Math.min(e,j.EF_ZIP64_OR_16),c+j.ENDTOT),o.writeUInt32LE(Math.min(r,j.EF_ZIP64_OR_32),c+j.ENDSIZ),o.writeUInt32LE(Math.min(n,j.EF_ZIP64_OR_32),c+j.ENDOFF),o.writeUInt16LE(i,c+j.ENDCOM),o.fill(" ",c+j.ENDHDR),o},"toBinary"),toJSON:a(function(){let o=a(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:o(n,4),commentLength:i}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ao=re(so=>{so.EntryHeader=Nf();so.MainHeader=Df()});var $f=re((G3,Uf)=>{Uf.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 i=e.createDeflateRaw(r),s=[],o=0;i.on("data",function(c){s.push(c),o+=c.length}),i.on("end",function(){var c=Buffer.alloc(o),l=0;c.fill(0);for(var u=0;u<s.length;u++){var d=s[u];d.copy(c,l),l+=d.length}n&&n(c)}),i.end(t)},"deflateAsync")}}});var Bf=re((W3,Ff)=>{var qb=+(process?.versions?.node??"").split(".")[0]||0;Ff.exports=function(t,e){var r=require("zlib");let n=qb>=15&&e>0?{maxOutputLength:e}:{};return{inflate:a(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:a(function(i){var s=r.createInflateRaw(n),o=[],c=0;s.on("data",function(l){o.push(l),c+=l.length}),s.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<o.length;d++){var f=o[d];f.copy(l,u),u+=f.length}i&&i(l)}),s.end(t)},"inflateAsync")}}});var Vf=re((K3,Gf)=>{"use strict";var{randomFillSync:jf}=require("crypto"),Kb=Ui(),Jb=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}),zf=a((t,e)=>Math.imul(t,e)>>>0,"uMul"),Hf=a((t,e)=>Jb[(t^e)&255]^t>>>8,"crc32update"),Tn=a(()=>typeof jf=="function"?jf(Buffer.alloc(12)):Tn.node(),"genSalt");Tn.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 $i={genSalt:Tn};function Fi(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(Fi,"Initkeys");Fi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Hf(e[0],t),e[1]+=e[0]&255,e[1]=zf(e[1],134775813)+1,e[2]=Hf(e[2],e[1]>>>24),t};Fi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return zf(t,t^1)>>8&255};function Zb(t){let e=new Fi(t);return function(r){let n=Buffer.alloc(r.length),i=0;for(let s of r)n[i++]=e.updateKeys(s^e.next());return n}}a(Zb,"make_decrypter");function Yb(t){let e=new Fi(t);return function(r,n,i=0){n||(n=Buffer.alloc(r.length));for(let s of r){let o=e.next();n[i++]=s^o,e.updateKeys(s)}return n}}a(Yb,"make_encrypter");function Xb(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Zb(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw Kb.WRONG_PASSWORD();return n(t.slice(12))}a(Xb,"decrypt");function Qb(t){Buffer.isBuffer(t)&&t.length>=12?$i.genSalt=function(){return t.slice(0,12)}:t==="node"?$i.genSalt=Tn.node:$i.genSalt=Tn}a(Qb,"_salter");function ew(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Yb(r),s=$i.genSalt();s[11]=e.crc>>>24&255,n&&(s[10]=e.crc>>>16&255);let o=Buffer.alloc(t.length+12);return i(s,o),i(t,o,12)}a(ew,"encrypt");Gf.exports={decrypt:Xb,encrypt:ew,_salter:Qb}});var Wf=re(Bi=>{Bi.Deflater=$f();Bi.Inflater=Bf();Bi.ZipCrypto=Vf()});var co=re((Y3,qf)=>{var X=Vr(),tw=ao(),Ve=X.Constants,oo=Wf();qf.exports=function(t,e){var r=new tw.EntryHeader,n=Buffer.alloc(0),i=Buffer.alloc(0),s=!1,o=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 y(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}a(y,"getCompressedDataFromZip");function h(p){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(p)===T}a(h,"crc32OK");function g(p,T,I){if(typeof T>"u"&&typeof p=="string"&&(I=p,p=void 0),s)return p&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var C=y();if(C.length===0)return p&&T&&T(C),C;if(r.encrypted){if(typeof I!="string"&&!Buffer.isBuffer(I))throw X.Errors.INVALID_PASS_PARAM();C=oo.ZipCrypto.decrypt(C,r,I)}var k;switch(r.method){case X.Constants.STORED:if(k=Buffer.alloc(C.length),C.copy(k),h(k))return p&&T&&T(k),k;throw p&&T&&T(k,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var E=new oo.Inflater(C,r.size);if(p)E.inflateAsync(function(U){T&&(h(U)?T(U):T(U,X.Errors.BAD_CRC()))});else{if(k=E.inflate(),!h(k))throw X.Errors.BAD_CRC(`"${f.decode(n)}"`);return k}break;default:throw p&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}a(g,"decompress");function b(p,T){if((!o||!o.length)&&Buffer.isBuffer(e))return p&&T&&T(y()),y();if(o.length&&!s){var I;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,I=Buffer.alloc(o.length),o.copy(I),p&&T&&T(I),I;default:case X.Constants.DEFLATED:var C=new oo.Deflater(o);if(p)C.deflateAsync(function(E){I=Buffer.alloc(E.length),r.compressedSize=E.length,E.copy(I),T&&T(I)});else{var k=C.deflate();return r.compressedSize=k.length,k}C=null;break}}else if(p&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}a(b,"compress");function w(p,T){return X.readBigUInt64LE(p,T)}a(w,"readUInt64LE");function v(p){try{for(var T=0,I,C,k;T+4<p.length;)I=p.readUInt16LE(T),T+=2,C=p.readUInt16LE(T),T+=2,k=p.slice(T,T+C),T+=C,Ve.ID_ZIP64===I&&S(k)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}a(v,"parseExtra");function S(p){var T,I,C,k;p.length>=Ve.EF_ZIP64_SCOMP&&(T=w(p,Ve.EF_ZIP64_SUNCOMP),r.size===Ve.EF_ZIP64_OR_32&&(r.size=T)),p.length>=Ve.EF_ZIP64_RHO&&(I=w(p,Ve.EF_ZIP64_SCOMP),r.compressedSize===Ve.EF_ZIP64_OR_32&&(r.compressedSize=I)),p.length>=Ve.EF_ZIP64_DSN&&(C=w(p,Ve.EF_ZIP64_RHO),r.offset===Ve.EF_ZIP64_OR_32&&(r.offset=C)),p.length>=Ve.EF_ZIP64_DSN+4&&(k=p.readUInt32LE(Ve.EF_ZIP64_DSN),r.diskNumStart===Ve.EF_ZIP64_OR_16&&(r.diskNumStart=k))}return a(S,"parseZip64ExtendedInformation"),{get entryName(){return f.decode(n)},get rawEntryName(){return n},set entryName(p){n=X.toBuffer(p,f.encode);var T=n[n.length-1];s=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(p){c=p,r.extraLength=p.length,v(p)},get comment(){return f.decode(i)},set comment(p){if(i=X.toBuffer(p,f.encode),r.commentLength=i.length,i.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let p=f.decode(n);return s?p.replace(/[/\\]$/,"").split("/").pop():p.split("/").pop()},get isDirectory(){return s},getCompressedData:a(function(){return b(!1,null)},"getCompressedData"),getCompressedDataAsync:a(function(p){b(!0,p)},"getCompressedDataAsync"),setData:a(function(p){o=X.toBuffer(p,X.decoder.encode),!s&&o.length?(r.size=o.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(p),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:a(function(p){return r.changed?o:g(!1,null,p)},"getData"),getDataAsync:a(function(p,T){r.changed?p(o):g(!0,p,T)},"getDataAsync"),set attr(p){r.attr=p},get attr(){return r.attr},set header(p){r.loadFromBinary(p)},get header(){return r},packCentralHeader:a(function(){r.flags_efs=this.efs,r.extraLength=c.length;var p=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(p,T),T+=n.length,c.copy(p,T),T+=r.extraLength,i.copy(p,T),p},"packCentralHeader"),packLocalHeader:a(function(){let p=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),I=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(I,p),p+=T.length,n.copy(I,p),p+=n.length,l.copy(I,p),p+=l.length,I},"packLocalHeader"),toJSON:a(function(){let p=a(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:p(e),data:p(o)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Zf=re((Q3,Jf)=>{var Kf=co(),rw=ao(),Ne=Vr();Jf.exports=function(t,e){var r=[],n=Object.create(null),i=Buffer.alloc(0),s=new rw.MainHeader,o=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:f}=u;t?g(u.readEntries):o=!0;function y(){let w=new Set;for(let v of Object.keys(n)){let S=v.split("/");if(S.pop(),!!S.length)for(let p=0;p<S.length;p++){let T=S.slice(0,p+1).join("/")+"/";w.add(T)}}for(let v of w)if(!(v in n)){let S=new Kf(u);S.entryName=v,S.attr=16,S.temporary=!0,r.push(S),n[S.entryName]=S,l.add(S)}}a(y,"makeTemporaryFolders");function h(){if(o=!0,n=Object.create(null),s.diskEntries>(t.length-s.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(s.diskEntries);for(var w=s.offset,v=0;v<r.length;v++){var S=w,p=new Kf(u,t);p.header=t.slice(S,S+=Ne.Constants.CENHDR),p.entryName=t.slice(S,S+=p.header.fileNameLength),p.header.extraLength&&(p.extra=t.slice(S,S+=p.header.extraLength)),p.header.commentLength&&(p.comment=t.slice(S,S+p.header.commentLength)),w+=p.header.centralHeaderSize,r[v]=p,n[p.entryName]=p}l.clear(),y()}a(h,"readEntries");function g(w){var v=t.length-Ne.Constants.ENDHDR,S=Math.max(0,v-65535),p=S,T=t.length,I=-1,C=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(S=0),v;v>=p;v--)if(t[v]===80){if(t.readUInt32LE(v)===Ne.Constants.ENDSIG){I=v,C=v,T=v+Ne.Constants.ENDHDR,p=v-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(v)===Ne.Constants.END64SIG){p=S;continue}if(t.readUInt32LE(v)===Ne.Constants.ZIP64SIG){I=v,T=v+Ne.readBigUInt64LE(t,v+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(I==-1)throw Ne.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(I,T)),s.commentLength&&(i=t.slice(C+Ne.Constants.ENDHDR)),w&&h()}a(g,"readMainHeader");function b(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,v)=>w.key.localeCompare(v.key)).map(w=>w.entry))}return a(b,"sortEntries"),{get entries(){return o||h(),r.filter(w=>!l.has(w))},get comment(){return f.decode(i)},set comment(w){i=Ne.toBuffer(w,f.encode),s.commentLength=i.length},getEntryCount:a(function(){return o?r.length:s.diskEntries},"getEntryCount"),forEach:a(function(w){this.entries.forEach(w)},"forEach"),getEntry:a(function(w){return o||h(),n[w]||null},"getEntry"),setEntry:a(function(w){o||h(),r.push(w),n[w.entryName]=w,s.totalEntries=r.length},"setEntry"),deleteFile:a(function(w,v=!0){o||h();let S=n[w];this.getEntryChildren(S,v).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:a(function(w){o||h();let v=n[w],S=r.indexOf(v);S>=0&&(r.splice(S,1),delete n[w],s.totalEntries=r.length)},"deleteEntry"),getEntryChildren:a(function(w,v=!0){if(o||h(),typeof w=="object")if(w.isDirectory&&v){let S=[],p=w.entryName;for(let T of r)T.entryName.startsWith(p)&&S.push(T);return S}else return[w];return[]},"getEntryChildren"),getChildCount:a(function(w){if(w&&w.isDirectory){let v=this.getEntryChildren(w);return v.includes(w)?v.length-1:v.length}return 0},"getChildCount"),compressToBuffer:a(function(){o||h(),b();let w=[],v=[],S=0,p=0;s.size=0,s.offset=0;let T=0;for(let k of this.entries){let E=k.getCompressedData();k.header.offset=p;let U=k.packLocalHeader(),D=U.length+E.length;p+=D,w.push(U),w.push(E);let N=k.packCentralHeader();v.push(N),s.size+=N.length,S+=D+N.length,T++}S+=s.mainHeaderSize,s.offset=p,s.totalEntries=T,p=0;let I=Buffer.alloc(S);for(let k of w)k.copy(I,p),p+=k.length;for(let k of v)k.copy(I,p),p+=k.length;let C=s.toBinary();return i&&i.copy(C,C.length-i.length),C.copy(I,p),t=I,o=!1,I},"compressToBuffer"),toAsyncBuffer:a(function(w,v,S,p){try{o||h(),b();let T=[],I=[],C=0,k=0,E=0;s.size=0,s.offset=0;let U=a(function(D){if(D.length>0){let N=D.shift(),W=N.entryName+N.extra.toString();S&&S(W),N.getCompressedDataAsync(function(te){p&&p(W),N.header.offset=k;let Se=N.packLocalHeader(),nt=Se.length+te.length;k+=nt,T.push(Se),T.push(te);let q=N.packCentralHeader();I.push(q),s.size+=q.length,C+=nt+q.length,E++,U(D)})}else{C+=s.mainHeaderSize,s.offset=k,s.totalEntries=E,k=0;let N=Buffer.alloc(C);T.forEach(function(te){te.copy(N,k),k+=te.length}),I.forEach(function(te){te.copy(N,k),k+=te.length});let W=s.toBinary();i&&i.copy(W,W.length-i.length),W.copy(N,k),t=N,o=!1,w(N)}},"compress2Buffer");U(Array.from(this.entries))}catch(T){v(T)}},"toAsyncBuffer")}}});var Qf=re((t5,Xf)=>{var oe=Vr(),ae=require("path"),nw=co(),iw=Zf(),fr=a((...t)=>oe.findLast(t,e=>typeof e=="boolean"),"get_Bool"),Yf=a((...t)=>oe.findLast(t,e=>typeof e=="string"),"get_Str"),sw=a((...t)=>oe.findLast(t,e=>typeof e=="function"),"get_Fun"),aw={noSort:!1,readEntries:!1,method:oe.Constants.NONE,fs:null};Xf.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),aw);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=oe.Constants.BUFFER,t=void 0)),Object.assign(n,e);let i=new oe(n),s=a(g=>{g.filter(b=>b.attr).sort((b,w)=>w.path.length-b.path.length).forEach(b=>i.fs.chmodSync(b.path,b.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=oe.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))n.method=oe.Constants.FILE,n.filename=t,r=i.fs.readFileSync(t);else throw oe.Errors.INVALID_FILENAME();let o=new iw(r,n),{canonical:c,sanitize:l,zipnamefix:u}=oe;function d(g){if(g&&o){var b;if(typeof g=="string"&&(b=o.getEntry(ae.posix.normalize(g))),typeof g=="object"&&typeof g.entryName<"u"&&typeof g.header<"u"&&(b=o.getEntry(g.entryName)),b)return b}return null}a(d,"getEntry");function f(g){let{join:b,normalize:w,sep:v}=ae.posix;return b(ae.isAbsolute(g)?"/":".",w(v+g.split("\\").join(v)+v))}a(f,"fixPath");function y(g){return g instanceof RegExp?(function(b){return function(w){return b.test(w)}})(g):typeof g!="function"?()=>!0:g}a(y,"filenameFilter");let h=a((g,b)=>{let w=b.slice(-1);return w=w===i.sep?i.sep:"",ae.relative(g,b)+w},"relativePath");return{readFile:a(function(g,b){var w=d(g);return w&&w.getData(b)||null},"readFile"),childCount:a(function(g){let b=d(g);if(b)return o.getChildCount(b)},"childCount"),readFileAsync:a(function(g,b){var w=d(g);w?w.getDataAsync(b):b(null,"getEntry failed for:"+g)},"readFileAsync"),readAsText:a(function(g,b){var w=d(g);if(w){var v=w.getData();if(v&&v.length)return v.toString(b||"utf8")}return""},"readAsText"),readAsTextAsync:a(function(g,b,w){var v=d(g);v?v.getDataAsync(function(S,p){if(p){b(S,p);return}S&&S.length?b(S.toString(w||"utf8")):b("")}):b("")},"readAsTextAsync"),deleteFile:a(function(g,b=!0){var w=d(g);w&&o.deleteFile(w.entryName,b)},"deleteFile"),deleteEntry:a(function(g){var b=d(g);b&&o.deleteEntry(b.entryName)},"deleteEntry"),addZipComment:a(function(g){o.comment=g},"addZipComment"),getZipComment:a(function(){return o.comment||""},"getZipComment"),addZipEntryComment:a(function(g,b){var w=d(g);w&&(w.comment=b)},"addZipEntryComment"),getZipEntryComment:a(function(g){var b=d(g);return b&&b.comment||""},"getZipEntryComment"),updateFile:a(function(g,b){var w=d(g);w&&w.setData(b)},"updateFile"),addLocalFile:a(function(g,b,w,v){if(i.fs.existsSync(g)){b=b?f(b):"";let S=ae.win32.basename(ae.win32.normalize(g));b+=w||S;let p=i.fs.statSync(g),T=p.isFile()?i.fs.readFileSync(g):Buffer.alloc(0);p.isDirectory()&&(b+=i.sep),this.addFile(b,T,v,p)}else throw oe.Errors.FILE_NOT_FOUND(g)},"addLocalFile"),addLocalFileAsync:a(function(g,b){g=typeof g=="object"?g:{localPath:g};let w=ae.resolve(g.localPath),{comment:v}=g,{zipPath:S,zipName:p}=g,T=this;i.fs.stat(w,function(I,C){if(I)return b(I,!1);S=S?f(S):"";let k=ae.win32.basename(ae.win32.normalize(w));if(S+=p||k,C.isFile())i.fs.readFile(w,function(E,U){return E?b(E,!1):(T.addFile(S,U,v,C),setImmediate(b,void 0,!0))});else if(C.isDirectory())return S+=i.sep,T.addFile(S,Buffer.alloc(0),v,C),setImmediate(b,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:a(function(g,b,w){if(w=y(w),b=b?f(b):"",g=ae.normalize(g),i.fs.existsSync(g)){let v=i.findFiles(g),S=this;if(v.length)for(let p of v){let T=ae.join(b,h(g,p));w(T)&&S.addLocalFile(p,ae.dirname(T))}}else throw oe.Errors.FILE_NOT_FOUND(g)},"addLocalFolder"),addLocalFolderAsync:a(function(g,b,w,v){v=y(v),w=w?f(w):"",g=ae.normalize(g);var S=this;i.fs.open(g,"r",function(p){if(p&&p.code==="ENOENT")b(void 0,oe.Errors.FILE_NOT_FOUND(g));else if(p)b(void 0,p);else{var T=i.findFiles(g),I=-1,C=a(function(){if(I+=1,I<T.length){var k=T[I],E=h(g,k).split("\\").join("/");E=E.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),v(E)?i.fs.stat(k,function(U,D){U&&b(void 0,U),D.isFile()?i.fs.readFile(k,function(N,W){N?b(void 0,N):(S.addFile(w+E,W,"",D),C())}):(S.addFile(w+E+"/",Buffer.alloc(0),"",D),C())}):process.nextTick(()=>{C()})}else b(!0,void 0)},"next");C()}})},"addLocalFolderAsync"),addLocalFolderAsync2:a(function(g,b){let w=this;g=typeof g=="object"?g:{localPath:g};let v=ae.resolve(f(g.localPath)),{zipPath:S,filter:p,namefix:T}=g;p instanceof RegExp?p=(function(k){return function(E){return k.test(E)}})(p):typeof p!="function"&&(p=a(function(){return!0},"filter")),S=S?f(S):"",T==="latin1"&&(T=a(k=>k.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=a(k=>k,"namefix"));let I=a(k=>ae.join(S,T(h(v,k))),"relPathFix"),C=a(k=>ae.win32.basename(ae.win32.normalize(T(k))),"fileNameFix");i.fs.open(v,"r",function(k){k&&k.code==="ENOENT"?b(void 0,oe.Errors.FILE_NOT_FOUND(v)):k?b(void 0,k):i.findFilesAsync(v,function(E,U){if(E)return b(E);U=U.filter(D=>p(I(D))),U.length||b(void 0,!1),setImmediate(U.reverse().reduce(function(D,N){return function(W,te){if(W||te===!1)return setImmediate(D,W,!1);w.addLocalFileAsync({localPath:N,zipPath:ae.dirname(I(N)),zipName:C(N)},D)}},b))})})},"addLocalFolderAsync2"),addLocalFolderPromise:a(function(g,b){return new Promise((w,v)=>{this.addLocalFolderAsync2(Object.assign({localPath:g},b),(S,p)=>{S&&v(S),p&&w(this)})})},"addLocalFolderPromise"),addFile:a(function(g,b,w,v){g=u(g);let S=d(g),p=S!=null;p||(S=new nw(n),S.entryName=g),S.comment=w||"";let T=typeof v=="object"&&v instanceof i.fs.Stats;T&&(S.header.time=v.mtime);var I=S.isDirectory?16:0;let C=S.isDirectory?16384:32768;return T?C|=4095&v.mode:typeof v=="number"?C|=4095&v:C|=S.isDirectory?493:420,I=(I|C<<16)>>>0,S.attr=I,S.setData(b),p||o.setEntry(S),S},"addFile"),getEntries:a(function(g){return o.password=g,o?o.entries:[]},"getEntries"),getEntry:a(function(g){return d(g)},"getEntry"),getEntryCount:a(function(){return o.getEntryCount()},"getEntryCount"),forEach:a(function(g){return o.forEach(g)},"forEach"),extractEntryTo:a(function(g,b,w,v,S,p){v=fr(!1,v),S=fr(!1,S),w=fr(!0,w),p=Yf(S,p);var T=d(g);if(!T)throw oe.Errors.NO_ENTRY();var I=c(T.entryName),C=l(b,p&&!T.isDirectory?c(p):w?I:ae.basename(I));if(T.isDirectory){var k=o.getEntryChildren(T);return k.forEach(function(D){if(D.isDirectory)return;var N=D.getData();if(!N)throw oe.Errors.CANT_EXTRACT_FILE();var W=c(w?D.entryName:D.entryName.substring(T.entryName.length)),te=l(b,W);let Se=S?D.header.fileAttr:void 0;i.writeFileTo(te,N,v,Se)}),!0}var E=T.getData(o.password);if(!E)throw oe.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(C)&&!v)throw oe.Errors.CANT_OVERRIDE();let U=S?g.header.fileAttr:void 0;return i.writeFileTo(C,E,v,U),!0},"extractEntryTo"),test:a(function(g){if(!o)return!1;for(var b of o.entries)try{if(b.isDirectory)continue;var w=b.getData(g);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:a(function(g,b,w,v){if(w=fr(!1,w),v=Yf(w,v),b=fr(!1,b),!o)throw oe.Errors.NO_ZIP();let S=[];o.entries.forEach(function(p){var T=l(g,c(p.entryName));if(p.isDirectory){i.makeDir(T),w&&S.push({path:T,attr:p.header.fileAttr});return}var I=p.getData(v);if(!I)throw oe.Errors.CANT_EXTRACT_FILE();let C=w?p.header.fileAttr:void 0;i.writeFileTo(T,I,b,C);try{i.fs.utimesSync(T,p.header.time,p.header.time)}catch{}}),s(S)},"extractAllTo"),extractAllToAsync:a(function(g,b,w,v){if(v=sw(b,w,v),w=fr(!1,w),b=fr(!1,b),!v)return new Promise((E,U)=>{this.extractAllToAsync(g,b,w,function(D){D?U(D):E(this)})});if(!o){v(oe.Errors.NO_ZIP());return}g=ae.resolve(g);let S=a(E=>l(g,ae.normalize(c(E.entryName))),"getPath"),p=a((E,U)=>new Error(E+': "'+U+'"'),"getError"),T=[],I=[];o.entries.forEach(E=>{E.isDirectory?T.push(E):I.push(E)});let C=[];for(let E of T){let U=S(E),D=w?E.header.fileAttr:void 0;try{i.makeDir(U)}catch{v(p("Unable to create folder",U));continue}D&&C.push({path:U,attr:D});try{i.fs.utimesSync(U,E.header.time,E.header.time)}catch{}}let k=a(E=>{if(!E)try{s(C)}catch(U){return v(p("Unable to set folder permissions",U.path||""))}v(E)},"done");I.reverse().reduce(function(E,U){return function(D){if(D)E(D);else{let N=ae.normalize(c(U.entryName)),W=l(g,N);U.getDataAsync(function(te,Se){if(Se)E(Se);else if(!te)E(oe.Errors.CANT_EXTRACT_FILE());else{let nt=w?U.header.fileAttr:void 0;i.writeFileToAsync(W,te,b,nt,function(q){if(!q)return E(p("Unable to write file",W));i.fs.utimes(W,U.header.time,U.header.time,function(){E()})})}})}}},k)()},"extractAllToAsync"),writeZip:a(function(g,b){if(arguments.length===1&&typeof g=="function"&&(b=g,g=""),!g&&n.filename&&(g=n.filename),!!g){var w=o.compressToBuffer();if(w){var v=i.writeFileTo(g,w,!0);typeof b=="function"&&b(v?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:a(function(g,b){let{overwrite:w,perm:v}=Object.assign({overwrite:!0},b);return new Promise((S,p)=>{!g&&n.filename&&(g=n.filename),g||p("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let I=a(C=>C?S(C):p("ADM-ZIP: Wasn't able to write zip file"),"ret");i.writeFileToAsync(g,T,w,v,I)},p)})},"writeZipPromise"),toBufferPromise:a(function(){return new Promise((g,b)=>{o.toAsyncBuffer(g,b)})},"toBufferPromise"),toBuffer:a(function(g,b,w,v){return typeof g=="function"?(o.toAsyncBuffer(g,b,w,v),null):o.compressToBuffer()},"toBuffer")}}});var S0={};um(S0,{TestRunMonitor:()=>rs});module.exports=dm(S0);var os=a(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var h3=require("@playwright/test");var U6=require("@playwright/test");var oE=require("@playwright/test");var nE=require("@playwright/test");var Ho=Object.defineProperty,V=a((t,e)=>{let r={};for(var n in t)Ho(r,n,{get:t[n],enumerable:!0});return e||Ho(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function zo(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;class s extends r{static{a(this,"_Branded")}[i]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&i in c&&c[i]===!0}}return Object.defineProperty(s,"name",{value:r.name}),s},sub(r){return zo(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}a(zo,"createNamespace");var Go=zo("langchain");var cs=Go.sub("error"),Vo=class extends cs.brand(Error){static{a(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},pm=class extends cs.brand(Vo,"model-abort"){static{a(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},yE=class Wo extends cs.brand(Vo,"context-overflow"){static{a(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new Wo(e.message);return r.cause=e,r}};var mm=/([A-Z]+)([A-Z][a-z0-9]+)/g,hm=/([a-z0-9])([A-Z])/g,gm=/[-_\s]+/g;function ym(t){return t.replace(mm,"$1_$2").replace(hm,"$1_$2").replace(gm,"_").toLowerCase()}a(ym,"snakeCase");function qo(t,e){return e?.[t]||ym(t)}a(qo,"keyToJson");function Ko(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}a(Ko,"mapKeys");var _m="__lc_escaped__";function bm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}a(bm,"needsEscaping");function wm(t){return{[_m]:t}}a(wm,"escapeObject");function Em(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}a(Em,"isSerializableLike");function Tm(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}}a(Tm,"createNotImplemented");function An(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Tm(t);if(Em(t))return t;e.add(t);let r=t;if(bm(r))return e.delete(t),wm(r);let n={};for(let[i,s]of Object.entries(r))n[i]=An(s,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>An(r,e)):t}a(An,"escapeIfNeeded");function Jo(t){return Array.isArray(t)?[...t]:{...t}}a(Jo,"shallowCopy");function vm(t,e){let r=Jo(t);for(let[n,i]of Object.entries(e)){let[s,...o]=n.split(".").reverse(),c=r;for(let l of o.reverse()){if(c[l]===void 0)break;c[l]=Jo(c[l]),c=c[l]}c[s]!==void 0&&(c[s]={lc:1,type:"secret",id:[i]})}return r}a(vm,"replaceSecrets");function ls(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}a(ls,"get_lc_unique_name");var Bt=class Zo{static{a(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ls(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 Zo||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 y of f.reverse()){if(!(y in l)||l[y]===void 0)return;(!(y in u)||u[y]===void 0)&&(typeof l[y]=="object"&&l[y]!=null?u[y]={}:Array.isArray(l[y])&&(u[y]=[])),l=l[y],u=u[y]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let i={},s=new WeakSet;s.add(this);for(let[c,l]of Object.entries(n))i[c]=An(l,s);let o=Ko(Object.keys(r).length?vm(i,r):i,qo,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Xr(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")}a(Xr,"isDataContentBlock");function Cn(t){return Xr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}a(Cn,"isURLContentBlock");function Rn(t){return Xr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}a(Rn,"isBase64ContentBlock");function us(t){return Xr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}a(us,"isIDContentBlock");function On({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 i=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}a(On,"parseBase64DataUrl");function P(t,e){return B(t)&&t.type===e}a(P,"_isContentBlock");function B(t){return typeof t=="object"&&t!==null}a(B,"_isObject");function fe(t){return Array.isArray(t)}a(fe,"_isArray");function A(t){return typeof t=="string"}a(A,"_isString");function ze(t){return typeof t=="number"}a(ze,"_isNumber");function kn(t){return t instanceof Uint8Array}a(kn,"_isBytesArray");function ds(t){try{return JSON.parse(t)}catch{return}}a(ds,"safeParseJson");var Ge=a(t=>t(),"iife");function Sm(t){if(t.type==="char_location"&&A(t.document_title)&&ze(t.start_char_index)&&ze(t.end_char_index)&&A(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&A(t.document_title)&&ze(t.start_page_number)&&ze(t.end_page_number)&&A(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&A(t.document_title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&A(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&A(t.url)&&A(t.title)&&A(t.encrypted_index)&&A(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&A(t.source)&&A(t.title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&A(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:s,...o}=t;return{...o,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}a(Sm,"convertAnthropicAnnotation");function Xo(t){if(P(t,"document")&&B(t.source)&&"type"in t.source){if(t.source.type==="base64"&&A(t.source.media_type)&&A(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&A(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&A(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&A(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(P(t,"image")&&B(t.source)&&"type"in t.source){if(t.source.type==="base64"&&A(t.source.media_type)&&A(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&A(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&A(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}a(Xo,"convertToV1FromAnthropicContentBlock");function Qo(t){function*e(){for(let r of t){let n=Xo(r);n?yield n:yield r}}return a(e,"iterateContent"),Array.from(e())}a(Qo,"convertToV1FromAnthropicInput");function Yo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"text")&&A(n.text)){let{text:i,citations:s,...o}=n;if(fe(s)&&s.length){let c=s.reduce((l,u)=>{let d=Sm(u);return d?[...l,d]:l},[]);yield{...o,type:"text",text:i,annotations:c};continue}else{yield{...o,type:"text",text:i};continue}}else if(P(n,"thinking")&&A(n.thinking)){let{thinking:i,signature:s,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:s};continue}else if(P(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(P(n,"tool_use")&&A(n.name)&&A(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(P(n,"input_json_delta")){if(xm(t)&&t.tool_call_chunks?.length){let i=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(P(n,"server_tool_use")&&A(n.name)&&A(n.id)){let{name:i,id:s}=n;if(i==="web_search"){yield{id:s,type:"server_tool_call",name:"web_search",args:{query:Ge(()=>{if(typeof n.input=="string")return n.input;if(B(n.input)&&A(n.input.query))return n.input.query;if(A(n.partial_json)){let o=ds(n.partial_json);if(o?.query)return o.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:Ge(()=>{if(typeof n.input=="string")return n.input;if(B(n.input)&&A(n.input.code))return n.input.code;if(A(n.partial_json)){let o=ds(n.partial_json);if(o?.code)return o.code}return""})}};continue}}else if(P(n,"web_search_tool_result")&&A(n.tool_use_id)&&fe(n.content)){let{content:i,tool_use_id:s}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i.reduce((o,c)=>P(c,"web_search_result")?[...o,c.url]:o,[])}};continue}else if(P(n,"code_execution_tool_result")&&A(n.tool_use_id)&&B(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(P(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(P(n,"mcp_tool_result")&&A(n.tool_use_id)&&B(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(P(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(P(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(P(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Xo(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(Yo,"convertToV1FromAnthropicMessage");var ec={translateContent:Yo,translateContentChunk:Yo};function xm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}a(xm,"_isAIMessageChunk");function Im(t){return Cn(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Rn(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:us(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}a(Im,"convertToV1FromDataContentBlock");function tc(t){return t.map(Im)}a(tc,"convertToV1FromDataContent");function rc(t){return!!(P(t,"image_url")&&B(t.image_url)||P(t,"input_audio")&&B(t.input_audio)||P(t,"file")&&B(t.file))}a(rc,"isOpenAIDataBlock");function nc(t){if(P(t,"image_url")&&B(t.image_url)&&A(t.image_url.url)){let e=On({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(P(t,"input_audio")&&B(t.input_audio)&&A(t.input_audio.data)&&A(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(P(t,"file")&&B(t.file)&&A(t.file.data)){let e=On({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(A(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}a(nc,"convertToV1FromOpenAIDataBlock");function Am(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Mn(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}a(Am,"convertToV1FromChatCompletions");function Cm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Mn(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}a(Cm,"convertToV1FromChatCompletionsChunk");function Mn(t){let e=[];for(let r of t)rc(r)?e.push(nc(r)):e.push(r);return e}a(Mn,"convertToV1FromChatCompletionsInput");function Rm(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:i}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:i}}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}a(Rm,"convertResponsesAnnotation");function ic(t){function*e(){B(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,i)=>B(i)&&A(i.text)?`${n}${i.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(P(n,"text")){let{text:i,annotations:s,phase:o,extras:c,...l}=n,u=B(c)?{...c}:{};A(o)&&(u.phase=o);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(s)?yield{...l,...d,type:"text",text:String(i),annotations:s.map(Rm)}:yield{...l,...d,type:"text",text:String(i)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(B(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(P(n,"web_search_call")){let i={};if(B(n.action)&&A(n.action.query)&&(i.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:i},n.status==="completed"||n.status==="failed"){let s={};B(n.action)&&(s.action=n.action),yield{type:"server_tool_call_result",toolCallId:A(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:s}}continue}else if(P(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:A(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(P(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(P(n,"code_interpreter_call")){if(A(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let i=Ge(()=>{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 s of n.outputs)if(P(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(s.logs),stdout:[0,void 0].includes(i)?String(s.logs):void 0}};continue}}continue}else if(P(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(P(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(P(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(P(n,"tool_search_call")){let i={};B(n.arguments)&&Object.assign(i,n.arguments);let s={};A(n.execution)&&(s.execution=n.execution),A(n.status)&&(s.status=n.status),A(n.call_id)&&(s.call_id=n.call_id),yield{id:A(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:i,...Object.keys(s).length>0?{extras:s}:{}};continue}else if(P(n,"tool_search_output")){let i={name:"tool_search"};A(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:A(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:i};continue}else if(P(n,"image_generation_call")){A(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:A(n.id)?n.id:void 0,metadata:{status:A(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}B(n)&&(yield{type:"non_standard",value:n})}}return a(e,"iterateContent"),Array.from(e())}a(ic,"convertToV1FromResponses");function Om(t){function*e(){yield*ic(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return a(e,"iterateContent"),Array.from(e())}a(Om,"convertToV1FromResponsesChunk");var sc={translateContent:a(t=>typeof t.content=="string"?Am(t):ic(t),"translateContent"),translateContentChunk:a(t=>typeof t.content=="string"?Cm(t):Om(t),"translateContentChunk")};function fs(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}a(fs,"isMessage");function ac(t,e="pretty"){return e==="pretty"?km(t):JSON.stringify(t)}a(ac,"convertToFormattedString");function km(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${s}`),t.type==="ai"){let o=t;if(o.tool_calls&&o.tool_calls.length>0){e.push("Tool Calls:");for(let c of o.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 o=t;o.name&&e.push(`Name: ${o.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
4
|
+
`)}a(km,"convertToPrettyString");var ps=Symbol.for("langchain.message");function Mm(t,e){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(o=>r(o,i+1));let s={};for(let o of Object.keys(n))s[o]=r(n[o],i+1);return s}return a(r,"helper"),JSON.stringify(r(t,0),null,2)}a(Mm,"stringifyWithDepthLimit");var ht=class extends Bt{static{a(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ps]=!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[tc,Mn,Qo].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&&ps in t&&t[ps]===!0&&fs(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=Mm(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return ac(this,t)}};function ms(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments);e.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}a(ms,"defaultToolCallParser");function hs(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"}}a(hs,"convertFileFormatToMimeType");function Lm(t){if(B(t.document)&&B(t.document.source)){let e=hs(B(t.document)&&A(t.document.format)?t.document.format:"");if(B(t.document.source)){if(B(t.document.source.s3Location)&&A(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(kn(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(A(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)=>B(n)&&A(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}a(Lm,"convertConverseDocumentBlock");function Dm(t){if(P(t,"image")&&B(t.image)){let e=hs(B(t.image)&&A(t.image.format)?t.image.format:"");if(B(t.image.source)){if(B(t.image.source.s3Location)&&A(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(kn(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}a(Dm,"convertConverseImageBlock");function Um(t){if(P(t,"video")&&B(t.video)){let e=hs(B(t.video)&&A(t.video.format)?t.video.format:"");if(B(t.video.source)){if(B(t.video.source.s3Location)&&A(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(kn(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}a(Um,"convertConverseVideoBlock");function oc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(P(n,"citations_content")&&B(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((i,s)=>B(s)&&A(s.text)?i+s.text:i,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,s)=>{if(B(s)){let o=fe(s.sourceContent)?s.sourceContent.reduce((l,u)=>B(u)&&A(u.text)?l+u.text:l,""):"",c=Ge(()=>{if(B(s.location)){let l=s.location.documentChar||s.location.documentPage||s.location.documentChunk;if(B(l))return{source:ze(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:ze(l.start)?l.start:void 0,endIndex:ze(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:o,...c})}return i},[]):[]};continue}else if(P(n,"document")&&B(n.document)){yield Lm(n);continue}else if(P(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(P(n,"image")&&B(n.image)){yield Dm(n);continue}else if(P(n,"reasoning_content")&&A(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(P(n,"tool_call"))continue;if(P(n,"video")&&B(n.video)){yield Um(n);continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(oc,"convertToV1FromChatBedrockConverseMessage");var cc={translateContent:oc,translateContentChunk:oc};function lc(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(A(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&&A(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}a(lc,"convertToV1FromDeepSeekMessage");var uc={translateContent:lc,translateContentChunk:lc};function dc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"thinking")&&A(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(P(n,"inlineData")&&B(n.inlineData)&&A(n.inlineData.mimeType)&&A(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(P(n,"functionCall")&&B(n.functionCall)&&A(n.functionCall.name)&&B(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(P(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(P(n,"fileData")&&B(n.fileData)&&A(n.fileData.mimeType)&&A(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(P(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(P(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(dc,"convertToV1FromChatGoogleMessage");var fc={translateContent:dc,translateContentChunk:dc};function pc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"reasoning")&&A(n.reasoning)){let i=Ge(()=>{let s=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});A(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(P(n,"thinking")&&A(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"image_url")){if(A(n.image_url))if(n.image_url.startsWith("data:")){let i=n.image_url.match(/^data:([^;]+);base64,(.+)$/);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(P(n,"media")&&A(n.mimeType)&&A(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(pc,"convertToV1FromChatVertexMessage");var mc={translateContent:pc,translateContentChunk:pc};function hc(t){let e=[],r=t.additional_kwargs?.reasoning;if(A(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),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&&A(n.text)){let i=n.text,s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){let o=s[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}a(hc,"convertToV1FromGroqMessage");var gc={translateContent:hc,translateContentChunk:hc};function yc(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(A(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&&A(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}a(yc,"convertToV1FromOllamaMessage");var _c={translateContent:yc,translateContentChunk:yc};function bc(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let i of r){if(i==null||typeof i!="object")continue;let s=i.type;if(s==="reasoning.summary"){let o=i.summary;A(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}else if(s==="reasoning.text"){let o=i.text;A(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}}if(!n){let i=t.additional_kwargs?.reasoning_content;A(i)&&i.length>0&&e.push({type:"reasoning",reasoning:i})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&A(i.text)&&e.push({type:"text",text:i.text});for(let i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}a(bc,"convertToV1FromOpenRouterMessage");var wc={translateContent:bc,translateContentChunk:bc};function Ec(t){let e=[];if(B(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let i=n.summary.reduce((s,o)=>B(o)&&A(o.text)?`${s}${o.text}`:s,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(A(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&&A(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}a(Ec,"convertToV1FromXAIMessage");var Tc={translateContent:Ec,translateContentChunk:Ec};function vc(t){function*e(){let r=Ge(()=>{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(i=>"thoughtSignature"in i)){let i=[...t.content];for(let s=i.length-1;s>=0;s--){let o=i[s];if(o.type==="text"&&!o.thought)return o.thoughtSignature=n.thoughtSignature,i}}return t.content}});for(let n of r){let i=Ge(()=>P(n,"text")&&A(n.text)?{type:"text",text:n.text}:P(n,"inlineData")&&B(n.inlineData)&&A(n.inlineData.mimeType)&&A(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:P(n,"functionCall")&&B(n.functionCall)&&A(n.functionCall.name)&&B(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:P(n,"functionResponse")?{type:"non_standard",value:n}:P(n,"fileData")&&B(n.fileData)&&A(n.fileData.mimeType)&&A(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:P(n,"executableCode")?{type:"non_standard",value:n}:P(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),s=Ge(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:i.type==="text"?i.text:"",reasoningContentBlock:i}:i),o={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...s};for(let c in o)o[c]===void 0&&delete o[c];yield o}}return a(e,"iterateContent"),Array.from(e())}a(vc,"convertToV1FromChatGoogleMessage");var Sc={translateContent:vc,translateContentChunk:vc};globalThis.lc_block_translators_registry??=new Map([["anthropic",ec],["bedrock-converse",cc],["deepseek",uc],["google",Sc],["google-genai",fc],["google-vertexai",mc],["groq",gc],["ollama",_c],["openai",sc],["openrouter",wc],["xai",Tc]]);function xc(t){return globalThis.lc_block_translators_registry.get(t)}a(xc,"getTranslator");function Ic(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}a(Ic,"mergeModalitiesTokenDetails");function $m(t,e){let r={...Ic(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}a($m,"mergeInputTokenDetails");function Fm(t,e){let r={...Ic(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}a(Fm,"mergeOutputTokenDetails");function Pn(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:$m(t?.input_token_details,e?.input_token_details),output_token_details:Fm(t?.output_token_details,e?.output_token_details)}}a(Pn,"mergeUsageMetadata");var St=class extends ht{static{a(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.
|
|
5
|
+
|
|
6
|
+
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[i,s]=ms(r);e.tool_calls=i??[],e.invalid_tool_calls=s??[]}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 s=e.tool_calls.filter(o=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===o.id&&c.name===o.name));e.contentBlocks.push(...s.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}let i=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(o=>o.id===s.id&&o.name===s.name));i.length>0&&(e.tool_calls=[...e.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.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=xc(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 Wm(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}]`:""}}a(Wm,"_contentBlockToString");function Dn(t,e="Human",r="AI"){let n=[];for(let i of t){let s;if(i.type==="human")s=e;else if(i.type==="ai")s=r;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",c=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(Wm).filter(Boolean).join(""):"",l=`${s}: ${o}${c}`;if(i.type==="ai"){let u=i;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(`
|
|
7
|
+
`)}a(Dn,"getBufferString");var $="0123456789abcdef".split(""),qm=[-2147483648,8388608,32768,128],Ye=[24,16,8,0],Un=[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 it(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}a(it,"Sha256");it.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,i=0,s,o=t.length,c=this.blocks;i<o;){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(s=this.start;i<o&&s<64;++i)c[s>>>2]|=t[i]<<Ye[s++&3];else for(s=this.start;i<o&&s<64;++i)n=t.charCodeAt(i),n<128?c[s>>>2]|=n<<Ye[s++&3]:n<2048?(c[s>>>2]|=(192|n>>>6)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]):n<55296||n>=57344?(c[s>>>2]|=(224|n>>>12)<<Ye[s++&3],c[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++i)&1023),c[s>>>2]|=(240|n>>>18)<<Ye[s++&3],c[s>>>2]|=(128|n>>>12&63)<<Ye[s++&3],c[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=c[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};it.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=qm[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()}};it.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,c=this.h7,l=this.blocks,u,d,f,y,h,g,b,w,v,S,p;for(u=16;u<64;++u)h=l[u-15],d=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=l[u-2],f=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,l[u]=l[u-16]+d+l[u-7]+f<<0;for(p=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,h=l[0]-1413257819,c=h-150054599<<0,n=h+24177077<<0):(w=704751109,h=l[0]-210244248,c=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),f=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),w=t&e,y=w^t&r^p,b=i&s^~i&o,h=c+f+b+Un[u]+l[u],g=d+y,c=n+h<<0,n=h+g<<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),v=n&t,y=v^n&e^w,b=o&c^~o&i,h=s+f+b+Un[u+1]+l[u+1],g=d+y,o=r+h<<0,r=h+g<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),f=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),S=r&n,y=S^r&t^v,b=s&o^~s&c,h=i+f+b+Un[u+2]+l[u+2],g=d+y,s=e+h<<0,e=h+g<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),f=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),p=e&r,y=p^e&n^S,b=s&o^~s&c,h=i+f+b+Un[u+3]+l[u+3],g=d+y,i=t+h<<0,t=h+g<<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+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+o<<0,this.h7=this.h7+c<<0};it.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=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]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[o>>>28&15]+$[o>>>24&15]+$[o>>>20&15]+$[o>>>16&15]+$[o>>>12&15]+$[o>>>8&15]+$[o>>>4&15]+$[o&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};it.prototype.toString=it.prototype.hex;it.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=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,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};it.prototype.array=it.prototype.digest;it.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 ah=He(Hn(),1);var Wc=/^(?:[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 en(t){return typeof t=="string"&&Wc.test(t)}a(en,"validate");function tn(t){if(!en(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)}a(tn,"parse");var we=[];for(let t=0;t<256;++t)we.push((t+256).toString(16).slice(1));function xt(t,e=0){return(we[t[e+0]]+we[t[e+1]]+we[t[e+2]]+we[t[e+3]]+"-"+we[t[e+4]]+we[t[e+5]]+"-"+we[t[e+6]]+we[t[e+7]]+"-"+we[t[e+8]]+we[t[e+9]]+"-"+we[t[e+10]]+we[t[e+11]]+we[t[e+12]]+we[t[e+13]]+we[t[e+14]]+we[t[e+15]]).toLowerCase()}a(xt,"unsafeStringify");var oh=new Uint8Array(16);function rn(){return crypto.getRandomValues(oh)}a(rn,"rng");function ch(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}}a(ch,"f");function Ts(t,e){return t<<e|t>>>32-e}a(Ts,"ROTL");function qc(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 i=t.length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let c=0;c<s;++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];o[c]=l}o[s-1][14]=(t.length-1)*8/2**32,o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<s;++c){let l=new Uint32Array(80);for(let g=0;g<16;++g)l[g]=o[c][g];for(let g=16;g<80;++g)l[g]=Ts(l[g-3]^l[g-8]^l[g-14]^l[g-16],1);let u=r[0],d=r[1],f=r[2],y=r[3],h=r[4];for(let g=0;g<80;++g){let b=Math.floor(g/20),w=Ts(u,5)+ch(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=Ts(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]+y>>>0,r[4]=r[4]+h>>>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])}a(qc,"sha1");function lh(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}a(lh,"stringToBytes");var Kc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Jc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Zc(t,e,r,n,i,s){let o=typeof r=="string"?lh(r):r,c=typeof n=="string"?tn(n):n;if(typeof n=="string"&&(n=tn(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(c),l.set(o,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,i){if(s??=0,s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[s+u]=l[u];return i}return xt(l)}a(Zc,"v35");function vs(t,e,r,n){return Zc(80,qc,t,e,r,n)}a(vs,"v5");vs.DNS=Kc;vs.URL=Jc;var Ss={};function Xc(t,e,r){let n;if(t)n=Yc(t.random??t.rng?.()??rn(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=rn();dh(Ss,i,s),n=Yc(s,Ss.msecs,Ss.seq,e,r)}return e??xt(n)}a(Xc,"v7");function dh(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}a(dh,"updateV7State");function Yc(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}a(Yc,"v7Bytes");var st=Xc;var Qc=Symbol.for("ls:tracing_async_local_storage"),Ht=Symbol.for("lc:context_variables"),el=a(t=>{globalThis[Qc]=t},"setGlobalAsyncLocalStorageInstance"),It=a(()=>globalThis[Qc],"getGlobalAsyncLocalStorageInstance");var fh=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),ph=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),mh=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Is=a(()=>typeof Deno<"u","isDeno"),hh=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Is(),"isNode"),gh=a(()=>{let t;return fh()?t="browser":hh()?t="node":ph()?t="webworker":mh()?t="jsdom":Is()?t="deno":t="other",t},"getEnv"),xs;function tl(){return xs===void 0&&(xs={library:"langchain-js",runtime:gh()}),xs}a(tl,"getRuntimeEnvironment");function Xe(t){try{return typeof process<"u"?process.env?.[t]:Is()?Deno?.env.get(t):void 0}catch{return}}a(Xe,"getEnvironmentVariable");var yh=class{static{a(this,"BaseCallbackHandlerMethodsClass")}};var _r=class extends yh{static{a(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,ls(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Xe("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 Bt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Bt.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends _r{static{a(this,"Handler")}name=st();constructor(){super(),Object.assign(this,t)}}return new e}},rl=a(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var nl=/^(?:[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 _h(t){return typeof t=="string"&&nl.test(t)}a(_h,"validate");var nn=_h;function bh(t){if(!nn(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)}a(bh,"parse");var zn=bh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function br(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()}a(br,"unsafeStringify");var wh=new Uint8Array(16);function wr(){return crypto.getRandomValues(wh)}a(wr,"rng");function Eh(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Th(t,e,r)}a(Eh,"v4");function Th(t,e,r){t=t||{};let n=t.random??t.rng?.()??wr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return br(n)}a(Th,"_v4");var zt=Eh;function vh(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}}a(vh,"f");function As(t,e){return t<<e|t>>>32-e}a(As,"ROTL");function Sh(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 i=t.length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let c=0;c<s;++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];o[c]=l}o[s-1][14]=(t.length-1)*8/2**32,o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<s;++c){let l=new Uint32Array(80);for(let g=0;g<16;++g)l[g]=o[c][g];for(let g=16;g<80;++g)l[g]=As(l[g-3]^l[g-8]^l[g-14]^l[g-16],1);let u=r[0],d=r[1],f=r[2],y=r[3],h=r[4];for(let g=0;g<80;++g){let b=Math.floor(g/20),w=As(u,5)+vh(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=As(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]+y>>>0,r[4]=r[4]+h>>>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])}a(Sh,"sha1");var il=Sh;function xh(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}a(xh,"stringToBytes");var Cs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rs="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Os(t,e,r,n,i,s){let o=typeof r=="string"?xh(r):r,c=typeof n=="string"?zn(n):n;if(typeof n=="string"&&(n=zn(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(c),l.set(o,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,i){if(s??=0,s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[s+u]=l[u];return i}return br(l)}a(Os,"v35");function ks(t,e,r,n){return Os(80,il,t,e,r,n)}a(ks,"v5");ks.DNS=Cs;ks.URL=Rs;var Ms=ks;var Ps={};function Ih(t,e,r){let n;if(t)n=sl(t.random??t.rng?.()??wr(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=wr();Ah(Ps,i,s),n=sl(s,Ps.msecs,Ps.seq,e,r)}return e??br(n)}a(Ih,"v7");function Ah(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}a(Ah,"updateV7State");function sl(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}a(sl,"v7Bytes");var Er=Ih;var al="gen_ai.operation.name",ol="gen_ai.system",Ns="gen_ai.request.model",cl="gen_ai.response.model",Ls="gen_ai.usage.input_tokens",Ds="gen_ai.usage.output_tokens",Us="gen_ai.usage.total_tokens",ll="gen_ai.request.max_tokens",ul="gen_ai.request.temperature",dl="gen_ai.request.top_p",fl="gen_ai.request.frequency_penalty",pl="gen_ai.request.presence_penalty",ml="gen_ai.response.finish_reasons",hl="gen_ai.prompt",gl="gen_ai.completion",yl="gen_ai.request.extra_query",_l="gen_ai.request.extra_body",bl="gen_ai.serialized.name",wl="gen_ai.serialized.signature",El="gen_ai.serialized.doc",Tl="gen_ai.response.id",vl="gen_ai.response.service_tier",Sl="gen_ai.response.system_fingerprint",xl="gen_ai.usage.input_token_details",Il="gen_ai.usage.output_token_details",Al="langsmith.trace.session_id",Cl="langsmith.trace.session_name",Rl="langsmith.span.kind",Ol="langsmith.trace.name",kl="langsmith.metadata",$s="langsmith.span.tags";var Ml="langsmith.request.streaming",Pl="langsmith.request.headers";var Fs="langsmith.usage_metadata";var Oh=a((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),kh,Nl=Symbol.for("ls:fetch_implementation");var Ll=a(()=>globalThis[Nl]===void 0?!0:kh??!1,"_shouldStreamForGlobalFetchImplementation"),Dl=a(t=>async(...e)=>{if(t||Z("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[Nl]??Oh)(...e);return(t||Z("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var sn=a(()=>Z("PROJECT")??ye("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var Ul={};function _e(t,e){let r=e?.code??t;Ul[r]||(Ul[r]=!0,e?.type&&typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(t,{type:e.type,code:e.code}):e?.type&&e?.code?console.warn(`${e.type} [${e.code}]: ${t}`):console.warn(t))}a(_e,"warnOnce");var O=a(t=>BigInt(t),"n"),jl=O("0x9E3779B1"),Hl=O("0x85EBCA77"),Mh=O("0xC2B2AE3D"),At=O("0x9E3779B185EBCA87"),Gt=O("0xC2B2AE3D27D4EB4F"),zl=O("0x165667B19E3779F9"),zs=O("0x85EBCA77C2B2AE63"),Ph=O("0x27D4EB2F165667C5"),Nh=O("0x165667919E3779F9"),Lh=O("0x9FB21C651E98DF25");function Dh(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}a(Dh,"hexToBytes");var at=Dh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),vr=(O(1)<<O(128))-O(1),z=(O(1)<<O(64))-O(1),qn=(O(1)<<O(32))-O(1),gt=64,Gl=gt/8,Uh=8,Gn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}a(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}a(Q,"readBigUInt64LE");function Tr(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}a(Tr,"readUInt32LE");function Bs(t,e=0){return t[e]}a(Bs,"readUInt8");var $h=a(t=>(t&O(255))<<O(56)|(t&O(65280))<<O(40)|(t&O(16711680))<<O(24)|(t&O(4278190080))<<O(8)|(t&O(0xff00000000))>>O(8)|(t&O(0xff0000000000))>>O(24)|(t&O(0xff000000000000))>>O(40)|(t&O(0xff00000000000000))>>O(56),"bswap64"),Fh=a(t=>(t=(t&O(65535))<<O(16)|(t&O(4294901760))>>O(16),t=(t&O(16711935))<<O(8)|(t&O(4278255360))>>O(8),t),"bswap32"),Bh=a((t,e)=>(t&qn)*(e&qn)&z,"XXH_mult32to64"),Sr=a(t=>{if(!t)throw new Error("Assert failed")},"assert");function jh(t,e){return(t<<e|t>>O(32)-e)&qn}a(jh,"rotl32");function Vl(t,e,r){for(let n=0;n<Gl;n++){let i=Q(e,n*8),s=i^Q(r,n*8);t[n^1]+=i,t[n]+=Bh(s,s>>O(32))}return t}a(Vl,"XXH3_accumulate_512");function $l(t,e,r,n){for(let i=0;i<n;i++)Vl(t,Y(e,i*gt),Y(r,i*8));return t}a($l,"XXH3_accumulate");function Hh(t,e){for(let r=0;r<Gl;r++){let n=Q(e,r*8),i=t[r];i=js(i,O(47)),i^=n,i*=jl,t[r]=i&z}return t}a(Hh,"XXH3_scrambleAcc");function Vn(t,e){return Wl(t[0]^Q(e,0),t[1]^Q(e,Uh))}a(Vn,"XXH3_mix2Accs");function Fl(t,e,r){let n=r;return n+=Vn(t.slice(0),Y(e,0*Gn)),n+=Vn(t.slice(2),Y(e,4*Gn)),n+=Vn(t.slice(4),Y(e,8*Gn)),n+=Vn(t.slice(6),Y(e,12*Gn)),ot(n&z)}a(Fl,"XXH3_mergeAccs");function zh(t,e,r,n,i){let s=Math.floor((r.byteLength-gt)/8),o=gt*s,c=Math.floor((e.byteLength-1)/o);for(let l=0;l<c;l++)t=$l(t,Y(e,l*o),r,s),t=i(t,Y(r,r.byteLength-gt));{let l=Math.floor((e.byteLength-1-o*c)/gt);t=$l(t,Y(e,c*o),r,l),t=n(t,Y(e,e.byteLength-gt),Y(r,r.byteLength-gt-7))}return t}a(zh,"XXH3_hashLong");function Gh(t,e,r){let n=new BigUint64Array([Mh,At,Gt,zl,zs,Hl,Ph,jl]);Sr(t.length>128),n=zh(n,t,e,Vl,Hh),Sr(n.length*8==64);{let i=Fl(n,Y(e,11),O(t.byteLength)*At&z);return Fl(n,Y(e,e.byteLength-gt-11),~(O(t.byteLength)*Gt)&z)<<O(64)|i}}a(Gh,"XXH3_hashLong_128b");function Wl(t,e){let r=t*e&vr;return r&z^r>>O(64)}a(Wl,"XXH3_mul128_fold64");function Bl(t,e,r){return Wl((Q(t,0)^Q(e,0)+r)&z,(Q(t,8)^Q(e,8)-r)&z)}a(Bl,"XXH3_mix16B");function Wn(t,e,r,n,i){let s=t&z,o=t>>O(64)&z;return s+=Bl(e,n,i),s^=Q(r,0)+Q(r,8),s&=z,o+=Bl(r,Y(n,16),i),o^=Q(e,0)+Q(e,8),o&=z,o<<O(64)|s}a(Wn,"XXH3_mix32B");function ot(t){return t^=t>>O(37),t*=Nh,t&=z,t^=t>>O(32),t}a(ot,"XXH3_avalanche");function Kn(t){return t^=t>>O(33),t*=Gt,t&=z,t^=t>>O(29),t*=zl,t&=z,t^=t>>O(32),t}a(Kn,"XXH3_avalanche64");function Vh(t,e,r){let n=t.byteLength;Sr(n>0&&n<=3);let i=O(Bs(t,n-1))|O(n<<8)|O(Bs(t,0)<<16)|O(Bs(t,n>>1)<<24),s=(O(Tr(e,0))^O(Tr(e,4)))+r,o=(i^s)&z,c=(O(Tr(e,8))^O(Tr(e,12)))-r,l=(jh(Fh(i),O(13))^c)&z;return(Kn(l)&z)<<O(64)|Kn(o)}a(Vh,"XXH3_len_1to3_128b");function js(t,e){return t^t>>e}a(js,"xorshift64");function Wh(t,e,r){let n=t.byteLength;Sr(n>=4&&n<=8);{let i=Tr(t,0),s=Tr(t,n-4),o=O(i)|O(s)<<O(32),c=(Q(e,16)^Q(e,24))+r&z,u=(o^c)*(At+(O(n)<<O(2)))&vr;return u+=(u&z)<<O(65),u&=vr,u^=u>>O(67),js(js(u&z,O(35))*Lh&z,O(28))|ot(u>>O(64))<<O(64)}}a(Wh,"XXH3_len_4to8_128b");function qh(t,e,r){let n=t.byteLength;Sr(n>=9&&n<=16);{let i=(Q(e,32)^Q(e,40))+r&z,s=(Q(e,48)^Q(e,56))-r&z,o=Q(t),c=Q(t,n-8),l=(o^c^i)*At,u=(l&z)+(O(n-1)<<O(54));l=l&(vr^z)|u,c^=s,l+=c+(c&qn)*(Hl-O(1))<<O(64),l&=vr,l^=$h(l>>O(64));let d=(l&z)*Gt;return d+=(l>>O(64))*Gt<<O(64),d&=vr,ot(d&z)|ot(d>>O(64))<<O(64)}}a(qh,"XXH3_len_9to16_128b");function Kh(t,e){let r=t.byteLength;return Sr(r<=16),r>8?qh(t,at,e):r>=4?Wh(t,at,e):r>0?Vh(t,at,e):Kn(e^Q(at,64)^Q(at,72))|Kn(e^Q(at,80)^Q(at,88))<<O(64)}a(Kh,"XXH3_len_0to16_128b");function Hs(t){return~t+O(1)&z}a(Hs,"inv64");function Jh(t,e,r){let n=O(t.byteLength)*At&z,i=O(t.byteLength-1)/O(32);for(;i>=0;){let c=Number(i);n=Wn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),i--}let s=n+(n>>O(64))&z;s=ot(s);let o=(n&z)*At+(n>>O(64))*zs+(O(t.byteLength)-r&z)*Gt;return o&=z,o=Hs(ot(o)),s|o<<O(64)}a(Jh,"XXH3_len_17to128_128b");function Zh(t,e,r){let n=O(t.byteLength)*At&z;for(let o=32;o<160;o+=32)n=Wn(n,Y(t,o-32),Y(t,o-16),Y(e,o-32),r);n=ot(n&z)|ot(n>>O(64))<<O(64);for(let o=160;o<=t.byteLength;o+=32)n=Wn(n,Y(t,o-32),Y(t,o-16),Y(e,3+o-160),r);n=Wn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),Hs(r));let i=n+(n>>O(64))&z;i=ot(i);let s=(n&z)*At+(n>>O(64))*zs+(O(t.byteLength)-r&z)*Gt;return s&=z,s=Hs(ot(s)),i|s<<O(64)}a(Zh,"XXH3_len_129to240_128b");function ql(t,e=O(0)){let r=t.byteLength;return r<=16?Kh(t,e):r<=128?Jh(t,at,e):r<=240?Zh(t,at,e):Gh(t,at,e)}a(ql,"XXH3_128");function Kl(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&z,i=t>>O(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}a(Kl,"xxh128ToBytes");var Jl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function H(t,e){if(!Jl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}a(H,"assertUuid");function Jn(t){let e=typeof t=="string"?Date.parse(t):t;return Er({msecs:e,seq:0})}a(Jn,"uuid7FromTime");function Zl(t){if(!Jl.test(t))return null;let e=t[14];return parseInt(e,16)}a(Zl,"getUuidVersion");function Yh(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}a(Yh,"uuidToBytes");function Xh(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)}`}a(Xh,"bytesToUuid");var Qh=new TextEncoder;function eg(t){let e=Qh.encode(t),r=ql(e);return Kl(r)}a(eg,"_fastHash128");function xr(t,e){let r=`${t}:${e}`,n=eg(r),i=new Uint8Array(16);if(Zl(t)===7){let o=Yh(t);i.set(o.slice(0,6),0)}else{let o=Date.now();i[0]=o/1099511627776&255,i[1]=o/4294967296&255,i[2]=o/16777216&255,i[3]=o/65536&255,i[4]=o/256&255,i[5]=o&255}return i[6]=112|n[0]&15,i[7]=n[1],i[8]=128|n[2]&63,i.set(n.slice(3,10),9),Xh(i)}a(xr,"nonCryptographicUuid7Deterministic");var Gs=a(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>Z(r)==="true"),"isEnvTracingEnabled");var Ws=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Vs=Symbol.for("ls:tracing_async_local_storage"),tg=new Ws,qs=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Vs]??tg}initializeGlobalInstance(e){globalThis[Vs]===void 0&&(globalThis[Vs]=e)}},rg=new qs;function Ks(t=!1){let e=rg.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
8
|
+
|
|
9
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}a(Ks,"getCurrentRunTree");var De=He(require("node:fs"),1),Ue=He(require("node:fs/promises"),1),ng=He(require("node:path"),1);var Qe=ng;async function Zn(t){await Ue.mkdir(t,{recursive:!0})}a(Zn,"mkdir");async function Ir(t,e){let r=`${t}.tmp`;await Ue.writeFile(r,e,{encoding:"utf8",mode:384}),await Ue.rename(r,t)}a(Ir,"writeFileAtomic");async function Yl(t){return Ue.readdir(t)}a(Yl,"readdir");async function Xl(t){return Ue.stat(t)}a(Xl,"stat");function Ar(t){return De.existsSync(t)}a(Ar,"existsSync");function Ql(t){De.mkdirSync(t,{recursive:!0})}a(Ql,"mkdirSync");function eu(t,e){De.writeFileSync(t,e)}a(eu,"writeFileSync");function tu(t,e){De.renameSync(t,e)}a(tu,"renameSync");function ru(t){De.unlinkSync(t)}a(ru,"unlinkSync");function Vt(t){return De.readFileSync(t,"utf-8")}a(Vt,"readFileSync");async function nu(t){await Ue.mkdir(t,{mode:448})}a(nu,"mkdirExclusive");function iu(t){try{return De.statSync(t).mtimeMs}catch{return}}a(iu,"statMtimeMs");async function Yn(t){await Ue.rm(t,{recursive:!0,force:!0})}a(Yn,"rmRecursive");function ig(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}a(ig,"isStale");var Xn=class{static{a(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 s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let i={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,i)}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[s,o]of this.cache.entries())r[s]=o.value;let n=Qe.dirname(e);Ar(n)||Ql(n);let i=`${e}.tmp`;try{eu(i,JSON.stringify({entries:r},null,2)),tu(i,e)}catch(s){throw Ar(i)&&ru(i),s}}load(e){if(!Ar(e))return 0;let r;try{let s=Vt(e);r=JSON.parse(s).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[s,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:o,createdAt:i};this.cache.set(s,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())ig(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 i=await n.refreshFunc();this.set(r,i,n.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},Qn=new Xn;function su(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}a(su,"isAbortError");var an=a(t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)},"castToError");var $e=class extends Error{static{a(this,"LangsmithError")}},Te=class t extends $e{static{a(this,"APIError")}constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=i,this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new yt({message:n,cause:an(r)});let s=r;return e===400?new qt(e,s,n,i):e===401?new Kt(e,s,n,i):e===403?new Jt(e,s,n,i):e===404?new Zt(e,s,n,i):e===409?new Yt(e,s,n,i):e===422?new Xt(e,s,n,i):e===429?new Qt(e,s,n,i):e>=500?new er(e,s,n,i):new t(e,s,n,i)}},Ct=class extends Te{static{a(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},yt=class extends Te{static{a(this,"APIConnectionError")}constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Wt=class extends yt{static{a(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},qt=class extends Te{static{a(this,"BadRequestError")}},Kt=class extends Te{static{a(this,"AuthenticationError")}},Jt=class extends Te{static{a(this,"PermissionDeniedError")}},Zt=class extends Te{static{a(this,"NotFoundError")}},Yt=class extends Te{static{a(this,"ConflictError")}},Xt=class extends Te{static{a(this,"UnprocessableEntityError")}},Qt=class extends Te{static{a(this,"RateLimitError")}},er=class extends Te{static{a(this,"InternalServerError")}};var ei="0.8.9";var ct,ag=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),og=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),cg=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),cu=a(()=>typeof globalThis.Deno<"u","isDeno"),lg=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!cu(),"isNode"),on=a(()=>ct||(typeof Bun<"u"?ct="bun":ag()?ct="browser":lg()?ct="node":og()?ct="webworker":cg()?ct="jsdom":cu()?ct="deno":ct="other",ct),"getEnv"),Zs;function ti(){if(Zs===void 0){let t=on(),e=dg();Zs={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:ei,...e}}return Zs}a(ti,"getRuntimeEnvironment");function Xs(){let t=ug(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(t))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[n]=i);return e}a(Xs,"getLangSmithEnvVarsMetadata");function ug(){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}a(ug,"getLangSmithEnvironmentVariables");function ye(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}a(ye,"getEnvironmentVariable");function Z(t){return ye(`LANGSMITH_${t}`)||ye(`LANGCHAIN_${t}`)}a(Z,"getLangSmithEnvironmentVariable");var Ys;function dg(){if(Ys!==void 0)return Ys;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=ye(r);n!==void 0&&(e[r]=n)}return Ys=e,e}a(dg,"getShas");function au(){return ye("OTEL_ENABLED")==="true"||Z("OTEL_ENABLED")==="true"}a(au,"getOtelEnabled");var ou=new Set(["langsmith","otel"]);function ri(t){if(t!==void 0)return t;let e=Z("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!ou.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...ou].sort().join(", ")}`);return au()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),r}return au()?"otel":"langsmith"}a(ri,"resolveTracingMode");var ta=class{static{a(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&ri()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. 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()}},ra=class{static{a(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new ta})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},na=class{static{a(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},Qs=Symbol.for("ls:otel_trace"),ea=Symbol.for("ls:otel_context"),lu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),fg=new ra,pg=new na,ia=class{static{a(this,"OTELProvider")}getTraceInstance(){return globalThis[Qs]??fg}getContextInstance(){return globalThis[ea]??pg}initializeGlobalInstances(e){globalThis[Qs]===void 0&&(globalThis[Qs]=e.trace),globalThis[ea]===void 0&&(globalThis[ea]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[lu]=e}getDefaultOTLPTracerComponents(){return globalThis[lu]??void 0}},sa=new ia;function ni(){return sa.getTraceInstance()}a(ni,"getOTELTrace");function uu(){return sa.getContextInstance()}a(uu,"getOTELContext");function du(){return sa.getDefaultOTLPTracerComponents()}a(du,"getDefaultOTLPTracerComponents");var mg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function hg(t){return mg[t]||t}a(hg,"getOperationName");function gg(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}a(gg,"isPrimitive");var ii=class{static{a(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 i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(e,r,n){let i=n&&ni().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);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 i=r.end_time;i&&(n.end(new Date(i)),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(Rl,r.run_type);let c=hg(r.run_type||"chain");e.setAttribute(al,c)}"name"in r&&r.name&&e.setAttribute(Ol,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Al,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Cl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute(Ns,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Fs,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ls,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Ds,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Us,r.total_tokens),this.setInvocationParameters(e,r);let s=r.extra?.metadata||{};for(let[c,l]of Object.entries(s))l!=null&&e.setAttribute(`${kl}.${c}`,gg(l)?String(l):JSON.stringify(l));let o=r.tags;if(o&&Array.isArray(o)?e.setAttribute($s,o.join(", ")):o&&e.setAttribute($s,String(o)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(bl,String(c.name)),c.signature&&e.setAttribute(wl,String(c.signature)),c.doc&&e.setAttribute(El,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(ol,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(ll,n.max_tokens),n.temperature!==void 0&&e.setAttribute(ul,n.temperature),n.top_p!==void 0&&e.setAttribute(dl,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(fl,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(pl,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(Ns,n.model),n.stream!==void 0&&e.setAttribute(Ml,n.stream),n.extra_headers&&e.setAttribute(Pl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(yl,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(_l,JSON.stringify(n.extra_body))),e.setAttribute(hl,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,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(Ls,i[0]),e.setAttribute(Ds,i[1]),e.setAttribute(Us,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(cl,String(n.model)),n.id&&e.setAttribute(Tl,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);s.length>0&&e.setAttribute(ml,s.join(", "))}if(n.service_tier&&e.setAttribute(vl,n.service_tier),n.system_fingerprint&&e.setAttribute(Sl,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;e.setAttribute(Fs,JSON.stringify(s)),s.input_token_details&&e.setAttribute(xl,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(Il,JSON.stringify(s.output_token_details))}}e.setAttribute(gl,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 o of n){let c=e[o];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 i=e.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let o of s)if(typeof o=="object"&&o.message&&typeof o.message=="object"&&o.message.kwargs&&typeof o.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.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 yg=Object.prototype.toString,_g=a(t=>yg.call(t)==="[object Error]","isError"),bg=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 aa(t){if(!(t&&_g(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:bg.has(r)}a(aa,"isNetworkError");function wg(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.")}a(wg,"validateRetries");function si(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}.`)}}a(si,"validateNumberOption");var oa=class extends Error{static{a(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 Eg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}a(Eg,"calculateDelay");function fu(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}a(fu,"calculateRemainingTime");async function Tg({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof oa)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,c=i.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:s,attemptNumber:e,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(l),fu(n,c)<=0)throw s;let u=await i.shouldConsumeRetry(l),d=fu(n,c);if(d<=0||o<=0)throw s;if(s instanceof TypeError&&!aa(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(l))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let f=Eg(r,i),y=Math.min(f,d);return y>0&&await new Promise((h,g)=>{let b=a(()=>{clearTimeout(w),i.signal?.removeEventListener("abort",b),g(i.signal.reason)},"onAbort"),w=setTimeout(()=>{i.signal?.removeEventListener("abort",b),h()},y);i.unref&&w.unref?.(),i.signal?.addEventListener("abort",b,{once:!0})}),i.signal?.throwIfAborted(),!0}a(Tg,"onAttemptFailure");async function ca(t,e={}){if(e={...e},wg(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,si("factor",e.factor,{min:0,allowInfinity:!1}),si("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),si("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),si("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let s=await t(r);return e.signal?.throwIfAborted(),s}catch(s){await Tg({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}a(ca,"pRetry");var ai=He(Hn(),1),pu="default"in ai.default?ai.default.default:ai.default;var vg=[408,425,429,500,502,503,504],cn=class{static{a(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 pu({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let s=this.onFailedResponseHook,o=this.queue.add(()=>ca(()=>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(s&&await s(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!vg.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([o,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):o}};function la(t){return typeof t?._getType=="function"}a(la,"isLangChainMessage");function ua(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}a(ua,"convertLangChainMessageToExample");var da=a(function(){let{crypto:t}=globalThis;if(t?.randomUUID)return da=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))},"uuid4");var Sg=/^[a-z][a-z0-9+.-]*:/i,mu=a(t=>Sg.test(t),"isAbsoluteURL"),Ae=a(t=>(Ae=Array.isArray,Ae(t)),"isArray"),fa=Ae;function Cr(t){return typeof t!="object"?{}:t??{}}a(Cr,"maybeObj");function pa(t){if(!t)return!0;for(let e in t)return!1;return!0}a(pa,"isEmptyObj");function hu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}a(hu,"hasOwn");var gu=a((t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new $e(`${t} must be an integer`);if(e<0)throw new $e(`${t} must be a positive integer`);return e},"validatePositiveInteger");var yu=a(t=>{try{return JSON.parse(t)}catch{return}},"safeJSON");var _u=a(t=>new Promise(e=>setTimeout(e,t)),"sleep");var Ot="0.0.1";function xg(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}a(xg,"getDetectedPlatform");var Ig=a(()=>{let t=xg();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":wu(Deno.build.os),"X-Stainless-Arch":bu(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":wu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ag();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Ag(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${s}.${o}`}}}return null}a(Ag,"getBrowserInfo");var bu=a(t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown","normalizeArch"),wu=a(t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),"normalizePlatform"),Cg,Eu=a(()=>Cg??=Ig(),"getPlatformHeaders");function Tu(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}a(Tu,"getDefaultFetch");function Rg(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}a(Rg,"makeReadableStream");function ma(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Rg({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}a(ma,"ReadableStreamFrom");async function vu(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}a(vu,"CancelReadableStream");var Su=a(({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ha="RFC3986",ga=a(t=>String(t),"default_formatter"),ya={RFC1738:a(t=>String(t).replace(/%20/g,"+"),"RFC1738"),RFC3986:ga},xu="RFC1738";var oi=a((t,e)=>(oi=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),oi(t,e)),"has"),lt=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var _a=1024,Iu=a((t,e,r,n,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let o="";for(let c=0;c<s.length;c+=_a){let l=s.length>=_a?s.slice(c,c+_a):s,u=[];for(let d=0;d<l.length;++d){let f=l.charCodeAt(d);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===xu&&(f===40||f===41)){u[u.length]=l.charAt(d);continue}if(f<128){u[u.length]=lt[f];continue}if(f<2048){u[u.length]=lt[192|f>>6]+lt[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=lt[224|f>>12]+lt[128|f>>6&63]+lt[128|f&63];continue}d+=1,f=65536+((f&1023)<<10|l.charCodeAt(d)&1023),u[u.length]=lt[240|f>>18]+lt[128|f>>12&63]+lt[128|f>>6&63]+lt[128|f&63]}o+=u.join("")}return o},"encode");function Au(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}a(Au,"is_buffer");function ba(t,e){if(Ae(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}a(ba,"maybe_map");var Cu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ru=a(function(t,e){Array.prototype.push.apply(t,Ae(e)?e:[e])},"push_to_array"),Mg,pe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Iu,encodeValuesOnly:!1,format:ha,formatter:ga,indices:!1,serializeDate(t){return(Mg??=Function.prototype.call.bind(Date.prototype.toISOString))(t)},skipNulls:!1,strictNullHandling:!1};function Pg(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}a(Pg,"is_non_nullish_primitive");var wa={};function Ou(t,e,r,n,i,s,o,c,l,u,d,f,y,h,g,b,w,v){let S=t,p=v,T=0,I=!1;for(;(p=p.get(wa))!==void 0&&!I;){let D=p.get(t);if(T+=1,typeof D<"u"){if(D===T)throw new RangeError("Cyclic object value");I=!0}typeof p.get(wa)>"u"&&(T=0)}if(typeof u=="function"?S=u(e,S):S instanceof Date?S=y?.(S):r==="comma"&&Ae(S)&&(S=ba(S,function(D){return D instanceof Date?y?.(D):D})),S===null){if(s)return l&&!b?l(e,pe.encoder,w,"key",h):e;S=""}if(Pg(S)||Au(S)){if(l){let D=b?e:l(e,pe.encoder,w,"key",h);return[g?.(D)+"="+g?.(l(S,pe.encoder,w,"value",h))]}return[g?.(e)+"="+g?.(String(S))]}let C=[];if(typeof S>"u")return C;let k;if(r==="comma"&&Ae(S))b&&l&&(S=ba(S,l)),k=[{value:S.length>0?S.join(",")||null:void 0}];else if(Ae(u))k=u;else{let D=Object.keys(S);k=d?D.sort(d):D}let E=c?String(e).replace(/\./g,"%2E"):String(e),U=n&&Ae(S)&&S.length===1?E+"[]":E;if(i&&Ae(S)&&S.length===0)return U+"[]";for(let D=0;D<k.length;++D){let N=k[D],W=typeof N=="object"&&typeof N.value<"u"?N.value:S[N];if(o&&W===null)continue;let te=f&&c?N.replace(/\./g,"%2E"):N,Se=Ae(S)?typeof r=="function"?r(U,te):U:U+(f?"."+te:"["+te+"]");v.set(t,T);let nt=new WeakMap;nt.set(wa,v),Ru(C,Ou(W,Se,r,n,i,s,o,c,r==="comma"&&b&&Ae(S)?null:l,u,d,f,y,h,g,b,w,nt))}return C}a(Ou,"inner_stringify");function Ng(t=pe){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||pe.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ha;if(typeof t.format<"u"){if(!oi(ya,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ya[r],i=pe.filter;(typeof t.filter=="function"||Ae(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Cu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=pe.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:pe.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:pe.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:pe.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:pe.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?pe.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:pe.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:pe.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:pe.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:pe.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:pe.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:pe.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:pe.strictNullHandling}}a(Ng,"normalize_stringify_options");function ku(t,e={}){let r=t,n=Ng(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ae(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof r!="object"||r===null)return"";let c=Cu[n.arrayFormat],l=c==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let y=0;y<i.length;++y){let h=i[y];n.skipNulls&&r[h]===null||Ru(o,Ou(r[h],h,c,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let d=o.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),d.length>0?f+d:""}a(ku,"stringify");function Mu(t){return ku(t,{arrayFormat:"repeat"})}a(Mu,"stringifyQuery");var li={off:0,error:200,warn:300,info:400,debug:500},Ea=a((t,e,r)=>{if(t){if(hu(li,t))return t;Me(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(li))}`)}},"parseLogLevel");function ln(){}a(ln,"noop");function ci(t,e,r){return!e||li[t]>li[r]?ln:e[t].bind(e)}a(ci,"makeLogFn");var Dg={error:ln,warn:ln,info:ln,debug:ln},Pu=new WeakMap;function Me(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Dg;let n=Pu.get(e);if(n&&n[0]===r)return n[1];let i={error:ci("error",e,r),warn:ci("warn",e,r),info:ci("info",e,r),debug:ci("debug",e,r)};return Pu.set(e,[r,i]),i}a(Me,"loggerFor");var _t=a(t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t),"formatRequestDetails");async function ui(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=e,o=await(async()=>{if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:await r.json():await r.text()})();return Me(t).debug(`[${n}] response parsed`,_t({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}a(ui,"defaultParseResponse");var Ug=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Nu=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},un,tr=class t extends Promise{static{a(this,"APIPromise")}constructor(e,r,n=ui){super(i=>{i(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),un.set(this,void 0),Ug(this,un,e,"f")}_thenUnwrap(e){return new t(Nu(this,un,"f"),this.responsePromise,async(r,n)=>e(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Nu(this,un,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};un=new WeakMap;var $g=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Fg=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},di,rr=class{static{a(this,"AbstractPage")}constructor(e,r,n,i){di.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),$g(this,di,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new $e("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Fg(this,di,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(di=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},dn=class extends tr{static{a(this,"PagePromise")}constructor(e,r,n){super(e,r,async(i,s)=>new n(i,s.response,await ui(i,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},fi=class extends rr{static{a(this,"OffsetPaginationTopLevelArray")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}},pi=class extends rr{static{a(this,"OffsetPaginationIssues")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}};var mi=class extends rr{static{a(this,"OffsetPaginationOnlineEvaluators")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=n.evaluators||[],this.total=n.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}};var ut=class extends rr{static{a(this,"ItemsCursorPostPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,body:{...Cr(this.options.body),cursor:e}}:null}},Rr=class extends rr{static{a(this,"ItemsCursorGetPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...Cr(this.options.query),cursor:e}}:null}};var Ta=a(()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function hi(t,e,r){return Ta(),new File(t,e??"unknown_file",r)}a(hi,"makeFile");function Lu(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}a(Lu,"getName");var Du=a(t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function","isAsyncIterable");var Uu=a(t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function","isBlobLike"),jg=a(t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Uu(t),"isFileLike"),Hg=a(t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function","isResponseLike");async function gi(t,e,r){if(Ta(),t=await t,jg(t))return t instanceof File?t:hi([await t.arrayBuffer()],t.name);if(Hg(t)){let i=await t.blob();return e||=new URL(t.url).pathname.split(/[\\/]/).pop(),hi(await va(i),e,r)}let n=await va(t);if(e||=Lu(t),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return hi(n,e,r)}a(gi,"toFile");async function va(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Uu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Du(t))for await(let r of t)e.push(...await va(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${zg(t)}`)}return e}a(va,"getBytes");function zg(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}a(zg,"propsForError");var G=class{static{a(this,"APIResource")}constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}};function Fu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}a(Fu,"encodeURIPath");var $u=Object.freeze(Object.create(null)),Vg=a((t=Fu)=>a(function(r,...n){if(r.length===1)return r[0];let i=!1,s=[],o=r.reduce((d,f,y)=>{/[?#]/.test(f)&&(i=!0);let h=n[y],g=(i?encodeURIComponent:t)(""+h);return y!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??$u)??$u)?.toString)&&(g=h+"",s.push({start:d.length+f.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),d+f+(y===n.length?"":g)},""),c=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=l.exec(c))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((d,f)=>d.start-f.start),s.length>0){let d=0,f=s.reduce((y,h)=>{let g=" ".repeat(h.start-d),b="^".repeat(h.length);return d=h.start+h.length,y+g+b},"");throw new $e(`Path parameters result in path with invalid segments:
|
|
10
|
+
${s.map(y=>y.error).join(`
|
|
11
|
+
`)}
|
|
12
|
+
${o}
|
|
13
|
+
${f}`)}return o},"path"),"createPathTagFunction"),F=Vg(Fu);var Or=class extends G{static{a(this,"Items")}create(e,r,n){let{extend_trace_retention:i,...s}=r;return this._client.post(F`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:i},body:s,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(F`/api/v1/platform/annotation-queues/${i}/items/${e}`,{body:s,...n})}list(e,r,n){return this._client.getAPIList(F`/api/v1/platform/annotation-queues/${e}/items`,Rr,{query:r,...n})}createStatus(e,r,n){return this._client.post(F`/api/v1/platform/annotation-queues/items/${e}/status`,{body:r,...n})}deleteAll(e,r,n){return this._client.post(F`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:r,...n})}retrieveCount(e,r,n){return this._client.get(F`/api/v1/platform/annotation-queues/${e}/items/count`,{query:r,...n})}retrievePlacement(e,r,n){let{queue_id:i}=r;return this._client.get(F`/api/v1/platform/annotation-queues/${i}/items/${e}/placement`,n)}};var kr=class extends G{static{a(this,"Runs")}create(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(F`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:s},body:i,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(F`/api/v1/annotation-queues/${i}/runs/${e}`,{body:s,...n})}list(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/runs`,{query:r,...n})}createByKey(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(F`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:s},body:i,...n})}deleteAll(e,r,n){return this._client.post(F`/api/v1/annotation-queues/${e}/runs/delete`,{body:r,...n})}deleteQueue(e,r,n){let{queue_id:i}=r;return this._client.delete(F`/api/v1/annotation-queues/${i}/runs/${e}`,n)}};var bt=class extends G{static{a(this,"AnnotationQueues")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new kr(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new Or(this._client)})}retrieve(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v1/annotation-queues/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(F`/api/v1/annotation-queues/${e}`,r)}annotationQueues(e,r){return this._client.post("/api/v1/annotation-queues",{body:e,...r})}createRunStatus(e,r,n){return this._client.post(F`/api/v1/annotation-queues/status/${e}`,{body:r,...n})}export(e,r,n){return this._client.post(F`/api/v1/annotation-queues/${e}/export`,{body:r,...n})}populate(e,r){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...r})}retrieveAnnotationQueues(e={},r){return this._client.getAPIList("/api/v1/annotation-queues",fi,{query:e,...r})}retrieveQueues(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}/queues`,r)}retrieveRun(e,r,n){let{queue_id:i,...s}=r;return this._client.get(F`/api/v1/annotation-queues/${i}/run/${e}`,{query:s,...n})}retrieveSize(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/size`,{query:r,...n})}retrieveTotalArchived(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/total_archived`,{query:r,...n})}retrieveTotalSize(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}/total_size`,r)}};bt.Runs=kr;bt.Items=Or;var Mr=class extends G{static{a(this,"ExperimentRuns")}query(e,r,n){return this._client.getAPIList(F`/api/v2/datasets/${e}/experiment-runs`,ut,{body:r,method:"post",...n})}};var kt=class extends G{static{a(this,"Datasets")}constructor(){super(...arguments),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new Mr(this._client)})}};kt.ExperimentRuns=Mr;var nr=class extends G{static{a(this,"Info")}list(e){return this._client.get("/api/v1/info",e)}};var ir=class extends G{static{a(this,"Issues")}retrieve(e,r){return this._client.get(F`/api/v1/platform/issues/${e}`,r)}list(e={},r){return this._client.getAPIList("/api/v1/platform/issues",pi,{query:e,...r})}};var Bu=Symbol("brand.privateNullableHeaders");function*Jg(t){if(!t)return;if(Bu in t){let{values:n,nulls:i}=t;yield*n.entries();for(let s of i)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():fa(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=fa(n[1])?n[1]:[n[1]],o=!1;for(let c of s)c!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,c])}}a(Jg,"iterateHeaders");var ee=a(t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[s,o]of Jg(n)){let c=s.toLowerCase();i.has(c)||(e.delete(s),i.add(c)),o===null?(e.delete(s),r.add(c)):(e.append(s,o),r.delete(c))}}return{[Bu]:!0,values:e,nulls:r}},"buildHeaders");var sr=class extends G{static{a(this,"OnlineEvaluators")}create(e,r){return this._client.post("/api/v1/platform/evaluators",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v1/platform/evaluators/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v1/platform/evaluators/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/evaluators",mi,{query:e,...r})}delete(e,r={},n){let{delete_run_rules:i}=r??{};return this._client.delete(F`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...n,headers:ee([{Accept:"*/*"},n?.headers])})}bulkDelete(e,r){let{evaluator_ids:n,delete_run_rules:i}=e;return this._client.delete("/api/v1/platform/evaluators",{query:{evaluator_ids:n,delete_run_rules:i},...r})}spend(e,r){return this._client.get("/api/v1/platform/evaluators/spend",{query:e,...r})}};var Pr=class extends G{static{a(this,"Runs")}retrieve(e,r,n){let{share_token:i,Accept:s,...o}=r;return this._client.get(F`/api/v2/public/${i}/run/${e}`,{query:o,...n,headers:ee([{...s!=null?{Accept:s}:void 0},n?.headers])})}query(e,r,n){let{Accept:i,...s}=r;return this._client.post(F`/api/v2/public/${e}/runs/query`,{body:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}};var Mt=class extends G{static{a(this,"Public")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Pr(this._client)})}};Mt.Runs=Pr;var Nr=class extends G{static{a(this,"Share")}create(e,r,n){return this._client.post(F`/api/v2/runs/${e}/share`,{body:r,...n})}delete(e,r,n){return this._client.delete(F`/api/v2/runs/${e}/share`,{body:r,...n,headers:ee([{Accept:"*/*"},n?.headers])})}};var Pt=class extends G{static{a(this,"Runs")}constructor(){super(...arguments),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new Nr(this._client)}),Object.defineProperty(this,"retrieve",{enumerable:!0,configurable:!0,writable:!0,value:this.retrieveV2}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:this.queryV2})}getURL(e,r,n){return this._client.get(F`/api/v2/runs/${e}/url`,{query:r,...n})}queryV2(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/runs/query",ut,{body:i,method:"post",...r,headers:ee([{...n!=null?{Accept:n}:void 0},r?.headers])})}retrieveV2(e,r,n){let{Accept:i,...s}=r;return this._client.get(F`/api/v2/runs/${e}`,{query:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}};Pt.Share=Nr;var Lr=class extends G{static{a(this,"Boxes")}create(e,r){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/boxes/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v2/sandboxes/boxes/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/boxes",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/boxes/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}createSnapshot(e,r,n){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:r,...n})}generateServiceURL(e,r,n){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/service-url`,{body:r,...n})}getStatus(e,r){return this._client.get(F`/api/v2/sandboxes/boxes/${e}/status`,r)}start(e,r){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/start`,r)}stop(e,r){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/stop`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var Dr=class extends G{static{a(this,"Registries")}create(e,r){return this._client.post("/api/v2/sandboxes/registries",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/registries/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v2/sandboxes/registries/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/registries",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/registries/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var Ur=class extends G{static{a(this,"Snapshots")}create(e,r){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/snapshots/${e}`,r)}list(e={},r){return this._client.get("/api/v2/sandboxes/snapshots",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/snapshots/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var dt=class extends G{static{a(this,"Sandboxes")}constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new Lr(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new Dr(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new Ur(this._client)})}};dt.Boxes=Lr;dt.Registries=Dr;dt.Snapshots=Ur;var ar=class extends G{static{a(this,"Threads")}listTraces(e,r,n){return this._client.getAPIList(F`/api/v2/threads/${e}/traces`,Rr,{query:r,...n})}query(e,r){return this._client.getAPIList("/api/v2/threads/query",ut,{body:e,method:"post",...r})}stats(e,r,n){return this._client.get(F`/api/v2/threads/${e}/stats`,{query:r,...n})}};var or=class extends G{static{a(this,"Traces")}listRuns(e,r,n){let{Accept:i,...s}=r;return this._client.get(F`/api/v2/traces/${e}/runs`,{query:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}query(e,r){return this._client.getAPIList("/api/v2/traces/query",ut,{body:e,method:"post",...r})}};var $r=a(t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0},"readEnv");var ry=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},ju=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Sa,xa,yi,Hu,K=class{static{a(this,"Langsmith")}constructor({baseURL:e=$r("LANGCHAIN_BASE_URL"),apiKey:r=$r("LANGSMITH_API_KEY")??null,tenantID:n=$r("LANGSMITH_TENANT_ID")??null,...i}={}){Sa.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{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,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{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,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),yi.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new kt(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Pt(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new ar(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new or(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new sr(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new Mt(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new bt(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new nr(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new ir(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new dt(this)});let s={apiKey:r,tenantID:n,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=s.baseURL,this.timeout=s.timeout??xa.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=Ea(s.logLevel,"ClientOptions.logLevel",this)??Ea($r("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Tu(),ry(this,yi,Su,"f");let c=$r("LANGCHAIN_CUSTOM_HEADERS");if(c){let l={};for(let u of c.split(`
|
|
14
|
+
`)){let d=u.indexOf(":");d>=0&&(l[u.substring(0,d).trim()]=u.substring(d+1).trim())}s.defaultHeaders={...l,...s.defaultHeaders}}this._options=s,this.apiKey=r,this.tenantID=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!r.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return ee([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ee([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return ee([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return Mu(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ot}`}defaultIdempotencyKey(){return`stainless-node-retry-${da()}`}makeStatusError(e,r,n,i){return Te.generate(e,r,n,i)}buildURL(e,r,n){let i=!ju(this,Sa,"m",Hu).call(this)&&n||this.baseURL,s=mu(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!pa(o)||!pa(c))&&(r={...c,...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new tr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,s=i.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(i);let{req:o,url:c,timeout:l}=await this.buildRequest(i,{retryCount:s-r});await this.prepareRequest(o,{url:c,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(Me(this).debug(`[${u}] sending request`,_t({retryOfRequestLogID:n,method:i.method,url:c,options:i,headers:o.headers})),i.signal?.aborted)throw new Ct;let y=new AbortController,h=await this.fetchWithTimeout(c,o,l,y).catch(an),g=Date.now();if(h instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Ct;let v=su(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return Me(this).info(`[${u}] connection ${v?"timed out":"failed"} - ${w}`),Me(this).debug(`[${u}] connection ${v?"timed out":"failed"} (${w})`,_t({retryOfRequestLogID:n,url:c,durationMs:g-f,message:h.message})),this.retryRequest(i,r,n??u);throw Me(this).info(`[${u}] connection ${v?"timed out":"failed"} - error; no more retries left`),Me(this).debug(`[${u}] connection ${v?"timed out":"failed"} (error; no more retries left)`,_t({retryOfRequestLogID:n,url:c,durationMs:g-f,message:h.message})),v?new Wt:new yt({cause:h})}let b=`[${u}${d}] ${o.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-f}ms`;if(!h.ok){let w=await this.shouldRetry(h);if(r&&w){let C=`retrying, ${r} attempts remaining`;return await vu(h.body),Me(this).info(`${b} - ${C}`),Me(this).debug(`[${u}] response error (${C})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),this.retryRequest(i,r,n??u,h.headers)}let v=w?"error; no more retries left":"error; not retryable";Me(this).info(`${b} - ${v}`);let S=await h.text().catch(C=>an(C).message),p=yu(S),T=p?void 0:S;throw Me(this).debug(`[${u}] response error (${v})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:T,durationMs:Date.now()-f})),this.makeStatusError(h.status,p,T,h.headers)}return Me(this).info(b),Me(this).debug(`[${u}] response start`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),{response:h,options:i,controller:y,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new dn(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:s,method:o,...c}=r||{},l=this._makeAbort(i);s&&s.addEventListener("abort",l,{once:!0});let u=setTimeout(l,n),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:i.signal,...d?{duplex:"half"}:{},method:"GET",...c};o&&(f.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(u)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let s,o=i?.get("retry-after-ms");if(o){let l=parseFloat(o);Number.isNaN(l)||(s=l)}let c=i?.get("retry-after");if(c&&!s){let l=parseFloat(c);Number.isNaN(l)?s=Date.parse(c)-Date.now():s=l*1e3}if(s===void 0){let l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,l)}return await _u(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,o=Math.min(.5*Math.pow(2,s),16),c=1-Math.random()*.25;return o*c*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:s,query:o,defaultBaseURL:c}=n,l=this.buildURL(s,o,c);"timeout"in n&&gu("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:d}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=ee([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Eu()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=ee([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ma(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:ju(this,yi,"f").call(this,{body:e,headers:n})}};xa=K,yi=new WeakMap,Sa=new WeakSet,Hu=a(function(){return this.baseURL!=="https://api.smith.langchain.com/"},"_Langsmith_baseURLOverridden");Object.defineProperty(K,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:xa});Object.defineProperty(K,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(K,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:$e});Object.defineProperty(K,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:Te});Object.defineProperty(K,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:yt});Object.defineProperty(K,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:Wt});Object.defineProperty(K,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:Ct});Object.defineProperty(K,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:Zt});Object.defineProperty(K,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:Yt});Object.defineProperty(K,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:Qt});Object.defineProperty(K,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:qt});Object.defineProperty(K,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:Kt});Object.defineProperty(K,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:er});Object.defineProperty(K,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:Jt});Object.defineProperty(K,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:Xt});Object.defineProperty(K,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:gi});K.Datasets=kt;K.Runs=Pt;K.Threads=ar;K.Traces=or;K.OnlineEvaluators=sr;K.Public=Mt;K.AnnotationQueues=bt;K.Info=nr;K.Issues=ir;K.Sandboxes=dt;var fn={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function zu(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?fn.SMITHDB_ONLY:r&&n?fn.DUAL:fn.CLICKHOUSE_ONLY}a(zu,"getQueryBackend");function bi(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
15
|
+
- "prompt-name" (for private prompts)
|
|
16
|
+
- "owner/prompt-name" (for prompts with explicit owner)
|
|
17
|
+
- "prompt-name:commit-hash" (with commit reference)
|
|
18
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}a(bi,"getInvalidPromptIdentifierMsg");var Ia=class extends Error{static{a(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}},Aa=class extends Error{static{a(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 wi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}a(wi,"isLangSmithNotFoundError");function Gu(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}a(Gu,"isLangSmithConflictError");async function L(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 i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new Aa(i);if(t.status===409)throw new Ia(i);let s=new Error(i);throw s.status=t.status,s}a(L,"raiseForStatus");var Vu="ERR_CONFLICTING_ENDPOINTS",_i=class extends Error{static{a(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:Vu}),this.name="ConflictingEndpointsError"}};function Wu(t){return typeof t=="object"&&t!==null&&t.code===Vu}a(Wu,"isConflictingEndpointsError");function Ce(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(bi(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,s]=e.split("/",2);if(!i||!s)throw new Error(bi(t));return[i,s,n]}else{if(!e)throw new Error(bi(t));return["-",e,n]}}a(Ce,"parseHubIdentifier");var ny=10,iy=1e4,qu="created_at";function sy(t){return new Promise(e=>setTimeout(e,t))}a(sy,"sleep");function ay(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}a(ay,"isEEXIST");function Ku(t){try{return Vt(Qe.join(t,qu)).split(`
|
|
19
|
+
`)}catch{return}}a(Ku,"lockMetadataLines");function oy(t){let e=Ku(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return iu(t)}a(oy,"lockCreatedAtMs");function cy(t){let e=Ku(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}a(cy,"lockOwner");async function ly(t){let e=oy(t);return e===void 0||Date.now()-e<=iy?!1:(await Yn(t),!0)}a(ly,"removeStaleLock");async function Ju(t,e){let r=`${t}.oauth.lock.lock`,n=Qe.dirname(r);n&&await Zn(n);let i=globalThis.crypto.randomUUID();for(;;){try{await nu(r)}catch(s){if(!ay(s))throw s;if(!await ly(r)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await sy(Math.min(ny,Math.max(0,e-Date.now())))}continue}try{await Ir(Qe.join(r,qu),`${new Date().toISOString()}
|
|
20
|
+
${i}
|
|
21
|
+
`)}catch(s){throw await Yn(r),s}break}return{async release(){cy(r)===i&&await Yn(r)}}}a(Ju,"acquireOAuthRefreshLock");var Ei="https://api.smith.langchain.com",uy="langsmith-cli",dy=6e4,fy=1e4;function py(){let t=on();return t==="browser"||t==="webworker"}a(py,"isBrowserLikeRuntime");function my(){let t=ye("LANGSMITH_CONFIG_FILE");if(t)return t;let e=ye("HOME")??ye("USERPROFILE");if(e)return Qe.join(e,".langsmith","config.json")}a(my,"getProfileConfigPath");function hy(t){let e=ye("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}a(hy,"resolveProfileName");function gy(){if(py())return;let t=my();if(!(!t||!Ar(t)))try{let e=JSON.parse(Vt(t)),r=hy(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}a(gy,"loadProfileState");function We(t){return t!=null&&t.trim()!==""}a(We,"hasValue");function Nt(t){return t?.trim().replace(/^["']|["']$/g,"")}a(Nt,"trimConfigValue");function Zu(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let r=Date.parse(e.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+dy}a(Zu,"shouldRefreshProfileToken");function yy(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let r="/api/v1";return e.endsWith(r)?e.slice(0,-r.length):e}a(yy,"normalizeConfigUrl");function _y(t,e){t.oauth??={},e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}a(_y,"applyTokenResponse");function Yu(t){return t.reason??new Error("The operation was aborted.")}a(Yu,"getAbortReason");async function by(t,e){if(!e)return t;if(e.aborted)throw Yu(e);let r,n=new Promise((i,s)=>{let o=a(()=>{s(Yu(e))},"onAbort");e.addEventListener("abort",o,{once:!0}),r=a(()=>{e.removeEventListener("abort",o)},"cleanup")});try{return await Promise.race([t,n])}finally{r?.()}}a(by,"waitForAbortSignal");function Xu(){let t=gy(),e=t?.profile;if(!t||!e)return{};let r=Nt(e.api_key),n=Nt(e.oauth?.access_token),i=Nt(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:r,workspaceId:e.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new Ca(t):void 0}}a(Xu,"loadProfileClientConfig");var Ca=class{static{a(this,"ProfileAuth")}constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e=wy(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Zu(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await by(this.refreshPromise,r));let n=Qu(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(Vt(this.state.configPath)),r=e.profiles?.[this.state.profileName];return r?(this.state.config=e,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){let r=this.state.profile.oauth?.refresh_token;if(!r)return;let n=Nt(this.state.profile.api_url)??Ei,i=Date.now()+fy,s;try{if(s=await Ju(this.state.configPath,i),this.reloadProfile()&&!Zu(this.state.profile))return;let c=new URLSearchParams({grant_type:"refresh_token",client_id:uy,refresh_token:this.state.profile.oauth?.refresh_token??r}),l=await e(`${yy(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!l.ok)return;let u=await l.json();if(!u.access_token)return;_y(this.state.profile,u),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await Ir(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
22
|
+
`)}catch{return}finally{await s?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function wy(t){let e=Nt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!Nt(t.oauth?.refresh_token))return Qu(t)}a(wy,"currentAuthHeaderFromProfile");function Qu(t){let e=Nt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let r=Nt(t.api_key);if(r)return{name:"x-api-key",value:r}}a(Qu,"authHeaderFromProfile");var ed="[...]",Ey={result:"[Circular]"},vi=[],Fr=[],Ty=new TextEncoder;function vy(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}a(vy,"defaultOptions");function Ti(t){return Ty.encode(t)}a(Ti,"encodeString");function td(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}a(td,"serializeWellKnownTypes");function Sy(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return td(r)}}a(Sy,"createDefaultReplacer");function rd(t){try{let i=function(d){let f=n(d);return f>r&&(r=f),f+2},s=function(d){return d===0?2:2+d*4},o=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"},c=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"?4:l(d)},l=function(d){if(d===null)return 4;if(d===void 0)return 0;let f=typeof d;if(f==="boolean")return 5;if(f==="number")return Number.isFinite(d)?d.toString().length:4;if(f==="bigint")return d.toString().length+2;if(f==="string")return i(d);if(f==="function"||f==="symbol")return 0;let y=d;if(y instanceof Date)return 26;if(y instanceof RegExp)return n(y.toString())+2;if(y instanceof Error){let g=y.name??"",b=y.message??"";return 22+n(g)+n(b)}if(typeof Buffer<"u"&&y instanceof Buffer)return 28+s(y.byteLength);if(ArrayBuffer.isView(y)){if(y instanceof DataView)return 2;let g=y.length??0,w=y instanceof Float32Array||y instanceof Float64Array?30:12;return 2+g*w}if(y instanceof ArrayBuffer)return 2;if(e.has(y))return 24;if(typeof y.toJSON=="function"){let g;try{g=y.toJSON("")}catch{return 16}e.add(y);let b=l(g);return e.delete(y),b}e.add(y);let h;if(Array.isArray(y)){h=2;let g=y.length;for(let b=0;b<g;b++)h+=c(y[b]),b<g-1&&(h+=1)}else if(y instanceof Map){h=2;let g=0;for(let[b,w]of y){if(o(w))continue;g>0&&(h+=1);let v=typeof b=="string"?b:String(b);h+=n(v)+3,h+=l(w),g++}}else if(y instanceof Set){h=2;let g=0;for(let b of y)g>0&&(h+=1),h+=c(b),g++}else{h=2;let g=0,b=Object.keys(y);for(let w=0;w<b.length;w++){let v=b[w],S=y[v];o(S)||(g>0&&(h+=1),h+=n(v)+3,h+=l(S),g++)}}return e.delete(y),h};a(i,"estimateString"),a(s,"estimateByteArrayJson"),a(o,"isDropped"),a(c,"estimateInArray"),a(l,"estimate");let e=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?d=>Buffer.byteLength(d,"utf8"):d=>d.length;return{size:l(t),maxStringLen:r}}catch{return{size:Re(t).length,maxStringLen:0}}}a(rd,"estimateSerializedSize");function Re(t,e,r,n,i){try{let s=JSON.stringify(t,Sy(r),n);return Ti(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
23
|
+
Context: ${e}`:""}`),Ti("[Unserializable]");Z("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
24
|
+
Context: ${e}`:""}`),typeof i>"u"&&(i=vy()),Oa(t,"",0,[],void 0,0,i);let o;try{Fr.length===0?o=JSON.stringify(t,r,n):o=JSON.stringify(t,xy(r),n)}catch{return Ti("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;vi.length!==0;){let c=vi.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return Ti(o)}}a(Re,"serialize");function Ra(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),vi.push([n,r,e,i])):Fr.push([e,r,t]):(n[r]=t,vi.push([n,r,e]))}a(Ra,"setReplace");function Oa(t,e,r,n,i,s,o){s+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Ra(Ey,t,e,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){Ra(ed,t,e,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Ra(ed,t,e,i);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)Oa(t[c],c,c,n,t,s,o);else{t=td(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];Oa(t[u],u,c,n,t,s,o)}}n.pop()}}a(Oa,"decirc");function xy(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Fr.length>0)for(var n=0;n<Fr.length;n++){var i=Fr[n];if(i[1]===e&&i[0]===r){r=i[2],Fr.splice(n,1);break}}return t.call(this,e,r)}}a(xy,"replaceGetterValues");var nd=require("node:worker_threads"),ka=nd.Worker,id=!0;var Iy=`
|
|
25
|
+
const { parentPort } = require("worker_threads");
|
|
26
|
+
|
|
27
|
+
const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
|
|
28
|
+
|
|
29
|
+
function serializeWellKnownTypes(val) {
|
|
30
|
+
if (val && typeof val === "object") {
|
|
31
|
+
if (val instanceof Map) return Object.fromEntries(val);
|
|
32
|
+
if (val instanceof Set) return Array.from(val);
|
|
33
|
+
if (val instanceof Date) return val.toISOString();
|
|
34
|
+
if (val instanceof RegExp) return val.toString();
|
|
35
|
+
if (val instanceof Error) return { name: val.name, message: val.message };
|
|
36
|
+
} else if (typeof val === "bigint") {
|
|
37
|
+
return val.toString();
|
|
38
|
+
}
|
|
39
|
+
return val;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function defaultReplacer(_key, val) {
|
|
43
|
+
return serializeWellKnownTypes(val);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Decirculate in-place: replace circular refs with { result: "[Circular]" }
|
|
47
|
+
// then restore after stringify. Mirrors fast-safe-stringify's decirc().
|
|
48
|
+
const restoreStack = [];
|
|
49
|
+
function decirc(val, k, stack, parent) {
|
|
50
|
+
if (typeof val === "object" && val !== null) {
|
|
51
|
+
for (let i = 0; i < stack.length; i++) {
|
|
52
|
+
if (stack[i] === val) {
|
|
53
|
+
const orig = parent[k];
|
|
54
|
+
parent[k] = CIRCULAR_REPLACE_NODE;
|
|
55
|
+
restoreStack.push([parent, k, orig]);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
stack.push(val);
|
|
60
|
+
if (Array.isArray(val)) {
|
|
61
|
+
for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
|
|
62
|
+
} else {
|
|
63
|
+
const normalized = serializeWellKnownTypes(val);
|
|
64
|
+
// Only recurse into normalized if it's still an object (arrays/objects),
|
|
65
|
+
// else it was replaced with a primitive (e.g. Date -> string).
|
|
66
|
+
if (normalized === val) {
|
|
67
|
+
const keys = Object.keys(val);
|
|
68
|
+
for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
stack.pop();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function serialize(obj) {
|
|
76
|
+
try {
|
|
77
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
if (!String(e && e.message).includes("Converting circular structure to JSON")) {
|
|
80
|
+
return "[Unserializable]";
|
|
81
|
+
}
|
|
82
|
+
decirc(obj, "", [], { "": obj });
|
|
83
|
+
try {
|
|
84
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
85
|
+
} catch (_) {
|
|
86
|
+
return "[unable to serialize, circular reference is too complex to analyze]";
|
|
87
|
+
} finally {
|
|
88
|
+
while (restoreStack.length) {
|
|
89
|
+
const [p, k, v] = restoreStack.pop();
|
|
90
|
+
p[k] = v;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
parentPort.on("message", (msg) => {
|
|
97
|
+
const { id, op, payload } = msg;
|
|
98
|
+
try {
|
|
99
|
+
if (op === "serialize") {
|
|
100
|
+
const str = serialize(payload);
|
|
101
|
+
const buf = Buffer.from(str, "utf8");
|
|
102
|
+
// Slice into its own ArrayBuffer so we can transfer without dragging
|
|
103
|
+
// unrelated bytes from any shared pool buffer.
|
|
104
|
+
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
105
|
+
parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
|
|
106
|
+
} else if (op === "ping") {
|
|
107
|
+
parentPort.postMessage({ id });
|
|
108
|
+
} else {
|
|
109
|
+
parentPort.postMessage({ id, error: "unknown op: " + op });
|
|
110
|
+
}
|
|
111
|
+
} catch (e) {
|
|
112
|
+
parentPort.postMessage({ id, error: String((e && e.message) || e) });
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
`,Pa=class{static{a(this,"SerializeWorker")}constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!id||ka===null)return this.disabled=!0,!1;try{let e=new ka(Iy,{eval:!0});return e.on("message",r=>{let n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(r.error)):r.bytes&&typeof r.length=="number"?n.resolve(new Uint8Array(r.bytes,0,r.length)):n.reject(new Error("worker returned malformed message")))}),e.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let n=this.nextId++;return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(o){this.pending.delete(n),s(o)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},Ma=null;function sd(){return Ma===null&&(Ma=new Pa),Ma}a(sd,"getSharedSerializeWorker");var Ay=64*1024,Cy=2048;function ad(t,e=Ay,r=Cy){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,s=0;for(;n.length>0;){if(s++>=r)return!1;let o=n.pop();if(o==null)continue;let c=typeof o;if(c==="string"){if(o.length>=e)return!0;continue}if(c!=="object")continue;let l=o;if(i.has(l)||(i.add(l),l instanceof Date||l instanceof RegExp||l instanceof Error||l instanceof ArrayBuffer||ArrayBuffer.isView(l)))continue;if(Array.isArray(l)){for(let d=l.length-1;d>=0;d--)n.push(l[d]);continue}if(l instanceof Map){for(let[,d]of l)n.push(d);continue}if(l instanceof Set){for(let d of l)n.push(d);continue}let u=Object.keys(l);for(let d=u.length-1;d>=0;d--)n.push(l[u[d]])}return!1}a(ad,"hasLargeString");function Ry(t,e){let[r]=Ce(t);if(r!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}a(Ry,"assertPullPublicPromptAllowed");function od(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}a(od,"_ensureUTCTimestamp");function Br(t){return{...t,start_time:od(t.start_time),end_time:od(t.end_time)}}a(Br,"_normalizeRunTimestamps");function cd(t,e,r){if(r)return t;let n=ti(),i=e??Xs(),s=t.extra??{},o=s.metadata;return t.extra={...s,runtime:{...n,...s?.runtime},metadata:{...i,...i.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??i.revision_id}:{},...o}},t}a(cd,"mergeRuntimeEnvIntoRun");var Oy=a(t=>{let e=t?.toString()??Z("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"),ky=a(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 My(t){let e=[];for await(let r of t)e.push(r);return e}a(My,"toArray");function Si(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}a(Si,"trimQuotes");var Py=a(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 ld(t){return typeof t=="number"?Number(t.toFixed(4)):t}a(ld,"_formatFeedbackScore");function Ny(t,e){if(!t)return;let r=a(u=>u.split(".").map(d=>parseInt(d,10)),"parse"),[n,i,s]=r(t),[o,c,l]=r(e);if(isNaN(n)||isNaN(i)||isNaN(s)||isNaN(o)||isNaN(c)||isNaN(l)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(n<o||n===o&&i<c||n===o&&i===c&&s<l)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}a(Ny,"_checkBackendVersion");var Ly=24*1024*1024,pd=1024*1024*1024,Dy=1e4,Uy=100;function md(t,e){new Headers({[t]:e})}a(md,"assertValidHeader");function ud(t){for(let[e,r]of Object.entries(t??{}))md(e,r)}a(ud,"assertValidHeaders");function dd(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([i,s])=>[i,s]):Object.entries(t),r={},n=new Map;for(let[i,s]of e){md(i,s);let o=i.toLowerCase(),c=n.get(o);c===void 0?(n.set(o,i),r[i]=s):r[c]=s}return r}a(dd,"normalizeHeaders");function $y(t,e,r){let n={...t},i=new Map(Object.keys(n).map(s=>[s.toLowerCase(),s]));for(let[s,o]of Object.entries(e)){let c=s.toLowerCase();n[i.get(c)??s]=o}for(let s of Object.keys(n))r.has(s.toLowerCase())&&delete n[s];return n}a($y,"mergeCallerHeaders");var Na=class{static{a(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??pd}peek(){return this.items[0]}push(e){let r,n=new Promise(s=>{r=s}),i=rd(e.item).size;return this.sizeBytes+i>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: ${i} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,workspaceId:e.workspaceId,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,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=[],i=0;for(;i+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){let s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,workspaceId:s.workspaceId,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}},Rt=class t{static{a(this,"Client")}get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Dl(this.debug);return(async(r,n)=>{let i,s=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,s)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,s))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(We(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(e,r){return e===r||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,r){if(!e?.headers)return!1;let n=new Headers(e.headers);if(We(n.get("x-api-key")))return!0;let i=n.get("Authorization");return We(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;let i=a(f=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return f.delete("Authorization"),f.has("x-api-key")||f.set("x-api-key",r.value),f;if(r.name==="Authorization"){if(We(f.get("x-api-key")))return f;let h=f.get("Authorization");return We(h)&&!this.isProfileManagedAuthorizationHeader(h??"",n)||f.set("Authorization",r.value),f}let y=f.get("Authorization");return We(y)&&!this.isProfileManagedAuthorizationHeader(y??"",n)||(We(y)&&f.delete("Authorization"),f.has("x-api-key")||f.set("x-api-key",r.value)),f},"applyAuth");if(!e)return{headers:{[r.name]:r.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};let s={...e.headers??{}},o=a(f=>Object.keys(s).find(y=>y.toLowerCase()===f),"getHeaderKey"),c=a(f=>{let y=o(f);return y?s[y]:void 0},"getHeader"),l=We(c("x-api-key")),u=c("authorization"),d=We(u)&&!this.isProfileManagedAuthorizationHeader(u??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let f=o("authorization");return f&&delete s[f],l||(s["x-api-key"]=r.value),{...e,headers:s}}if(r.name==="Authorization"){if(!l&&!d){let f=o("authorization");f&&f!=="Authorization"&&delete s[f],s.Authorization=r.value}return{...e,headers:s}}if(!d){let f=o("authorization");f&&delete s[f],l||(s["x-api-key"]=r.value)}return{...e,headers:s}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return Re(e,r);if(!ad(e))return Re(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=sd()),this._serializeWorker===null)return Re(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,Re(e,r)):n}catch{return Re(e,r)}}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,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"anonymizer",{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,"_fetchOptionsHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_openAPIClientSignature",{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:ye("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,"_stainlessVersionsChecked",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),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,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Z("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Z("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,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:ye("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();this.tracingSampleRate=Oy(e.tracingSamplingRate),this.apiUrl=Si(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Si(e.apiKey??r.apiKey);if(this.apiKey=We(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Si(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Si(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new cn({...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=Z("FAILED_TRACES_DIR")||void 0;let i=Z("FAILED_TRACES_MAX_MB");if(i){let l=parseInt(i,10);Number.isFinite(l)&&l>0&&(this.failedTracesMaxBytes=l*1024*1024)}let s=e.maxIngestMemoryBytes??pd;this.batchIngestCaller=new cn({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Py,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.hideMetadata=e.hideMetadata??r.hideMetadata,this.anonymizer=e.anonymizer,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Na(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:o,...c}=e.fetchOptions||{};this.fetchOptions=c,this._fetchOptionsHeaders=dd(o),ud(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=ri(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new ii),this.cachedLSEnvVarsForMetadata=Xs(),e.cache!==void 0&&e.disablePromptCache&&_e("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?(_e("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=Qn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=Qn)}static getDefaultClientConfig(){let e=Xu(),r=Z("API_KEY"),n=Z("ENDPOINT"),i=Z("WORKSPACE_ID"),s=We(r),o=n??e.apiUrl??Ei,c=i??e.workspaceId,l=Z("HIDE_INPUTS")==="true",u=Z("HIDE_OUTPUTS")==="true",d=Z("HIDE_METADATA")==="true";return{apiUrl:o,apiKey:r,webUrl:void 0,hideInputs:l,hideOutputs:u,hideMetadata:d,workspaceId:c,oauthAccessToken:s?void 0:e.oauthAccessToken,oauthRefreshToken:s?void 0:e.oauthRefreshToken,profileAuth:s?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:ky(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("apac")?(this.webUrl="https://apac.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 _sdkControlledHeaders(){let e=new Set;if(this.apiKey!==void 0)e.add("x-api-key");else{let r=this.profileAuth?.currentAuthHeader();r&&e.add(r.name.toLowerCase())}return this.workspaceId&&e.add("x-tenant-id"),e}get _callerHeaders(){return $y(dd(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${ei}`,...this._callerHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get _openAPIAuth(){let e={...this._callerHeaders},r=Object.keys(e).find(i=>i.toLowerCase()==="x-api-key"),n=this.apiKey;return n===void 0&&r!==void 0&&(n=e[r]??void 0,delete e[r]),n===void 0&&this.workspaceId===void 0&&(e["X-API-Key"]=null),{apiKey:n,defaultHeaders:Object.keys(e).length>0?e:void 0}}get headers(){return this._customHeaders}set headers(e){ud(e),this._customHeaders=e??{}}_getOpenAPIBaseUrl(){let e=this.apiUrl.replace(/\/$/,"");for(let r of["/api/v1","/api"])if(e.endsWith(r))return e.slice(0,-r.length);return e}get openAPIClient(){let e=this._openAPIAuth,r=JSON.stringify([e.apiKey,e.defaultHeaders]);return(this._openAPIClient===void 0||this._openAPIClientSignature!==r)&&(this._openAPIClientSignature=r,this._openAPIClient=this._newOpenAPIClient(e)),this._openAPIClient}_newOpenAPIClient(e=this._openAPIAuth){let{method:r,body:n,signal:i,...s}=this.fetchOptions;return new K({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:s,defaultHeaders:e.defaultHeaders})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get evaluators(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.onlineEvaluators}get runs(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.runs}get sandboxes(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.sandboxes}get datasets(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.datasets}get annotationQueues(){return this._checkStainlessVersion("0.16.14"),this.openAPIClient.annotationQueues}get threads(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.threads}get traces(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.traces}get public(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.public}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 processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}async processError(e){if(this.anonymizer==null)return e;let r=await this.anonymizer({error:e});return typeof r?.error=="string"?r.error:e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}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.error!==void 0&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events!==void 0&&(r.events=this._filterNewTokenEvents(r.events)),r}async _getResponse(e,r){let n=r?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let o=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,`fetch ${e}`),o})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));let o=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(o,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<s))break;i+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let s=r?{...r}:{};for(;;){let o=JSON.stringify(s),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(d,`fetch ${e}`),d})).json();if(!l||!l[i])break;yield l[i];let u=l.cursors;if(!u||!u.next)break;s.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 i of e)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of e){let s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?n.push(i):this.filteredPostUuids.add(s):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Ly}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Uy}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[i,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){s();break}let o=i.reduce((u,d)=>{let f=d.apiUrl??this.apiUrl,y=d.apiKey??this.apiKey,h=d.workspaceId??this.workspaceId,b=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl&&d.workspaceId===this.workspaceId?"default":`${f}|${y}|${h??""}`;return u[b]||(u[b]=[]),u[b].push(d),u},{}),c=[];for(let[u,d]of Object.entries(o)){let f=u==="default",y=f?[]:u.split("|"),h=y[2],g=this._processBatch(d,{apiUrl:f?void 0:y[0],apiKey:f?void 0:y[1],workspaceId:f||!h?void 0:h});c.push(g)}let l=Promise.all(c).finally(s);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,i,s){try{let o=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:o.toString("base64")}),l=`trace_${Date.now()}_${zt().slice(0,8)}.json`,u=Qe.join(e,l);if(t._fallbackDirsCreated.has(e)||(await Zn(e),t._fallbackDirsCreated.add(e)),s!==void 0&&s>0)try{let f=(await Yl(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json")),y=0;for(let h of f){let{size:g}=await Xl(Qe.join(e,h));y+=g}if(y>=s){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${y} bytes >= ${s} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Ir(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(o){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,o)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((i,s)=>i+(s.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let i={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},s=await this._ensureServerInfo();if(!this._multipartDisabled&&(s?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&s?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:c,sizeBytes:n})}catch(l){if(wi(l))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=cd(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(Dy),...this.fetchOptions});return await L(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
116
|
+
=== LangSmith Server Configuration ===
|
|
117
|
+
`+JSON.stringify(r,null,2)+`
|
|
118
|
+
`),r}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(r=>{Ny(r?.version,e)}).catch(()=>{}))}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 _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration#feedback-create",r=await this._ensureServerInfo();if(zu(r.instance_flags)===fn.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);_e(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${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=ni(),r=uu();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._mergedHeaders,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;let s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:l,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let o=cd(s,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=Re(o,`Creating run with id: ${o.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 L(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),s=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(i.length>0&&s.length>0){let l=i.reduce((d,f)=>(f.id&&(d[f.id]=f),d),{}),u=[];for(let d of s)d.id!==void 0&&l[d.id]?l[d.id]={...l[d.id],...d}:u.push(d);i=Object.values(l),s=u}let o={post:i,patch:s};if(!o.post.length&&!o.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=o[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(await this._serializeBody(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=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 L(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i={},s=[];for(let f of e??[]){let y=await this.prepareRunCreateOrUpdateInputs(f);y.id!==void 0&&y.attachments!==void 0&&(i[y.id]=y.attachments),delete y.attachments,s.push(y)}let o=[];for(let f of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(f));if(s.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(o.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(s.length>0&&o.length>0){let f=s.reduce((h,g)=>(g.id&&(h[g.id]=g),h),{}),y=[];for(let h of o)h.id!==void 0&&f[h.id]?f[h.id]={...f[h.id],...h}:y.push(h);s=Object.values(f),o=y}if(s.length===0&&o.length===0)return;let u=[],d=[];for(let[f,y]of[["post",s],["patch",o]])for(let h of y){let{inputs:g,outputs:b,events:w,extra:v,error:S,serialized:p,attachments:T,...I}=h,C={inputs:g,outputs:b,events:w,extra:v,error:S,serialized:p},k=await this._serializeBody(I,`Serializing for multipart ingestion of run with id: ${I.id}`);d.push({name:`${f}.${I.id}`,payload:new Blob([k],{type:`application/json; length=${k.length}`})});for(let[E,U]of Object.entries(C)){if(U===void 0)continue;let D=await this._serializeBody(U,`Serializing ${E} for multipart ingestion of run with id: ${I.id}`);d.push({name:`${f}.${I.id}.${E}`,payload:new Blob([D],{type:`application/json; length=${D.length}`})})}if(I.id!==void 0){let E=i[I.id];if(E){delete i[I.id];for(let[U,D]of Object.entries(E)){let N,W;if(Array.isArray(D)?[N,W]=D:(N=D.mimeType,W=D.data),U.includes(".")){console.warn(`Skipping attachment '${U}' for run ${I.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${I.id}.${U}`,payload:new Blob([W],{type:`${N}; length=${W.byteLength}`})})}}}u.push(`trace=${I.trace_id},id=${I.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let o of e)n.push(new Blob([`--${r}\r
|
|
119
|
+
`])),n.push(new Blob([`Content-Disposition: form-data; name="${o.name}"\r
|
|
120
|
+
`,`Content-Type: ${o.payload.type}\r
|
|
121
|
+
\r
|
|
122
|
+
`])),n.push(o.payload),n.push(new Blob([`\r
|
|
123
|
+
`]));return n.push(new Blob([`--${r}--\r
|
|
124
|
+
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(s){let o=a(async c=>{typeof c=="string"?s.enqueue(n.encode(c)):s.enqueue(c)},"writeChunk");for(let c of e){await o(`--${r}\r
|
|
125
|
+
`),await o(`Content-Disposition: form-data; name="${c.name}"\r
|
|
126
|
+
`),await o(`Content-Type: ${c.payload.type}\r
|
|
127
|
+
\r
|
|
128
|
+
`);let u=c.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)s.enqueue(d.value)}finally{u.releaseLock()}await o(`\r
|
|
129
|
+
`)}await o(`--${r}--\r
|
|
130
|
+
`),s.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=a(()=>this._createNodeFetchBody(e,i),"buildBuffered"),o=a(()=>this._createMultipartStream(e,i),"buildStream"),c=a(async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await l(),d={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(d["x-tenant-id"]=n.workspaceId);let f=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(f=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let y=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 L(y,"Failed to send multipart request",!0),y}),"sendWithRetry");try{let l,u=!1;Ll()&&!this.multipartStreamingDisabled&&on()!=="bun"?(u=!0,l=await c(o)):l=await c(s),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Ei&&(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(s))}catch(l){if(wi(l))throw l;if(console.warn(`${l.message.trim()}
|
|
131
|
+
|
|
132
|
+
Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,i).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){H(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs)),r.error&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events&&(r.events=this._filterNewTokenEvents(r.events));let i={...r,id:e};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let s={...this._mergedHeaders,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);let o=Re(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:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){return _e("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:r})}async _readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){H(e);let n=Br(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(_e("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:Z("PROJECT")||"default"})).id;let s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${r.id}?poll=true`}else if(e!==void 0){let i=await this._readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await My(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};r.sort((s,o)=>(s?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}e.child_runs=n[e.id]||[];for(let s in n)s!==e.id&&(i[s].child_runs=n[s]);return e}async*listRuns(e){_e("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:o,startTime:c,executionOrder:l,isRoot:u,runType:d,error:f,id:y,query:h,filter:g,traceFilter:b,treeFilter:w,limit:v,select:S,order:p}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],U=await Promise.all(E.map(D=>this.readProject({projectName:D}).then(N=>N.id)));T.push(...U)}let I=["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"],C={session:T.length?T:null,run_type:d,reference_example:o,query:h,filter:g,trace_filter:b,tree_filter:w,execution_order:l,parent_run:i,start_time:c?c.toISOString():null,error:f,id:y,limit:v,trace:s,select:S||I,is_root:u,order:p};C.select.includes("child_run_ids")&&_e("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let k=0;for await(let E of this._getCursorPaginatedList("/runs/query",C)){let U=E.map(Br);if(v){if(k>=v)break;if(U.length+k>v){yield*U.slice(0,v-k);break}k+=U.length,yield*U}else yield*U}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:s,startTime:o,endTime:c,limit:l,offset:u}=e,f={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:o?o.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},y=Number(u)||0,h="/runs/group",g=`${this.apiUrl}${h}`;for(;;){let b={...f,offset:y},w=Object.fromEntries(Object.entries(b).filter(([C,k])=>k!==void 0)),v=JSON.stringify(w),p=await(await this.caller.call(async()=>{let C=await this._fetch(g,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await L(C,`Failed to fetch ${h}`),C})).json(),{groups:T,total:I}=p;if(T.length===0)break;for(let C of T)yield C;if(y+=T.length,y>=I)break}}async*readThread(e){_e("readThread() is deprecated and will be removed after Jan 31, 2027. Use client.threads.listTraces() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-list-traces for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_THREAD"});let{threadId:r,projectId:n,projectName:i,isRoot:s=!0,limit:o,filter:c,order:l="asc"}=e;if(!n&&!i)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:i??void 0,isRoot:s,limit:o,filter:d,order:l})}async listThreads(e){_e("listThreads() is deprecated and will be removed after Jan 31, 2027. Use client.threads.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_THREADS"});let{projectId:r,projectName:n,limit:i,offset:s=0,filter:o,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),y={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()};o!=null&&(y.filter=o);let h=new Map;for await(let v of this._getCursorPaginatedList("/runs/query",y))for(let S of v){let p=Br(S),T=p.thread_id;if(T){let I=h.get(T)??[];I.push(p),h.set(T,I)}}let g=[];for(let[v,S]of h.entries()){S.sort((k,E)=>{let U=k,D=E,N=U.start_time??"",W=D.start_time??"";if(N!==W)return N.localeCompare(W);let te=U.dotted_order??"",Se=D.dotted_order??"";return te.localeCompare(Se)});let T=[...S.map(k=>k.start_time).filter(Boolean)].sort(),I=T.length?T[0]:"",C=T.length?T[T.length-1]:"";g.push({thread_id:v,runs:S,count:S.length,filter:"",total_tokens:0,total_cost:null,min_start_time:I,max_start_time:C,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}g.sort((v,S)=>{let p=v.max_start_time??"";return(S.max_start_time??"").localeCompare(p)});let b=s>0?g.slice(s):g;return i!==void 0?b.slice(0,i):b}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:o,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:f,filter:y,traceFilter:h,treeFilter:g,isRoot:b,dataSourceType:w}){let v=o||[];if(s&&(v=[...o||[],...await Promise.all(s.map(k=>this.readProject({projectName:k}).then(E=>E.id)))]),v.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let p=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:v,reference_example:c,start_time:l,end_time:u,error:d,query:f,filter:y,trace_filter:h,tree_filter:g,is_root:b,data_source_type:w}).filter(([k,E])=>E!==void 0)),T=JSON.stringify(p);return await(await this.caller.call(async()=>{let k=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await L(k,"get run stats"),k})).json()}async shareRun(e,{shareId:r}={}){_e("shareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.create() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_SHARE_RUN"});let n={run_id:e,share_token:r||zt()};H(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"share run"),c})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(e){_e("unshareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.delete() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_UNSHARE_RUN"}),H(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare run",!0),r})}async readRunSharedLink(e){_e('readRunSharedLink() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve({ selects: ["SHARE_URL"] }) instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.',{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN_SHARED_LINK"}),H(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){_e("listSharedRuns() is deprecated and will be removed after Jan 31, 2027. Use client.public.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_SHARED_RUNS"});let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let o of r)n.append("id",o);return H(e),(await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"list shared runs"),o})).json()).map(Br)}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),H(e);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}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};H(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"share dataset"),c})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(e){H(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare dataset",!0),r})}async readSharedDataset(e){return H(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"read shared dataset"),i})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>i.append(c,u)):i.append(c,l)});let s=await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(c,"list shared examples"),c}),o=await s.json();if(!s.ok)throw"detail"in o?new Error(`Failed to list shared examples.
|
|
133
|
+
Status: ${s.status}
|
|
134
|
+
Message: ${Array.isArray(o.detail)?o.detail.join(`
|
|
135
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return o.map(c=>({...c,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:o=null,numExamples:c=null,numRepetitions:l=null,evaluatorKeys:u=null}){let d=i?"?upsert=true":"",f=`${this.apiUrl}/sessions${d}`,y=s||{};n&&(y.metadata=n);let h={name:e,extra:y,description:r};o!==null&&(h.reference_dataset_id=o),c!=null&&(h.num_examples=c),l!=null&&(h.num_repetitions=l),u!=null&&u.length>0&&(h.evaluator_keys=u);let g=JSON.stringify(h);return await(await this.caller.call(async()=>{let v=await this._fetch(f,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await L(v,"create project"),v})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:o=null}){let c=`${this.apiUrl}/sessions/${e}`,l=s;i&&(l={...l||{},metadata:i});let u=JSON.stringify({name:r,extra:l,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let y=await this._fetch(c,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(y,"update project"),y})).json()}async hasProject({projectId:e,projectName:r}){let n="/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)H(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"has project"),o});try{let o=await s.json();return s.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let i="/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)H(e),i+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let o=await this._get(i,s),c;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);c=o[0]}else c=o;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}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/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}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/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:i,referenceDatasetName:s,includeStats:o,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),i!==void 0)d.append("reference_dataset",i);else if(s!==void 0){let f=await this.readDataset({datasetName:s});d.append("reference_dataset",f.id)}o!==void 0&&d.append("include_stats",o.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,H(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:o,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(h=>{u.append("input_keys",h)}),i.forEach(h=>{u.append("output_keys",h)}),s&&u.append("description",s),o&&u.append("data_type",o),c&&u.append("name",c),await(await this.caller.call(async()=>{let h=await this._fetch(l,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(h,"upload CSV"),h})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:o}={}){let c={name:e,description:r,extra:{source:"sdk",...o?{metadata:o}:{}}};n&&(c.data_type=n),i&&(c.inputs_schema_definition=i),s&&(c.outputs_schema_definition=s);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(f,"create dataset"),f})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)H(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);o=s[0]}else o=s;return o}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:i}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);let o=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,o)}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(`
|
|
136
|
+
`).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:o}={}){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);i!==void 0&&l.append("name",i),s!==void 0&&l.append("name_contains",s),o!==void 0&&l.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;H(s);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;H(o);let c=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${o}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",i=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)H(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,`delete ${n}`,!0),s})}async createExample(e,r,n){if(fd(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:e.dataset_id,s=r?n?.datasetName:e.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);let o=(r?n?.createdAt:e.created_at)||new Date,c;fd(e)?c=e:c={inputs:e,outputs:r,created_at:o?.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(i,[c]);return await this.readExample(l.example_ids?.[0]??zt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let S=e,p=S[0].dataset_id,T=S[0].dataset_name;if(p===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:T})).id);let I=await this._uploadExamplesMultipart(p,S);return await Promise.all(I.example_ids.map(k=>this.readExample(k)))}let{inputs:r,outputs:n,metadata:i,splits:s,sourceRunIds:o,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:f,datasetName:y}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=f,g=y;if(h===void 0&&g===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&g!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:g})).id);let b=r.map((S,p)=>({dataset_id:h,inputs:S,outputs:n?.[p],metadata:i?.[p],split:s?.[p],id:d?.[p],attachments:u?.[p],source_run_id:o?.[p],use_source_run_io:c?.[p],use_source_run_attachments:l?.[p]})),w=await this._uploadExamplesMultipart(h,b);return await Promise.all(w.example_ids.map(S=>this.readExample(S)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let i=e.map(o=>la(o)?ua(o):o),s=la(r)?ua(r):r;return this.createExample({input:i},{output:s},n)}async readExample(e){H(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...s}=n,o=s;return i&&(o.attachments=Object.entries(i).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),o}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:o,metadata:c,limit:l,offset:u,filter:d,includeAttachments:f}={}){let y;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)y=e;else if(r!==void 0)y=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let h=new URLSearchParams({dataset:y}),g=i?typeof i=="string"?i:i?.toISOString():void 0;g&&h.append("as_of",g);let b=o??!0;if(h.append("inline_s3_urls",b.toString()),n!==void 0)for(let v of n)h.append("id",v);if(s!==void 0)for(let v of s)h.append("splits",v);if(c!==void 0){let v=JSON.stringify(c);h.append("metadata",v)}l!==void 0&&h.append("limit",l.toString()),u!==void 0&&h.append("offset",u.toString()),d!==void 0&&h.append("filter",d),f===!0&&["attachment_urls","outputs","metadata"].forEach(v=>h.append("select",v));let w=0;for await(let v of this._getPaginated("/examples",h)){for(let S of v){let{attachment_urls:p,...T}=S,I=T;p&&(I.attachments=Object.entries(p).reduce((C,[k,E])=>(C[k.slice(11)]={presigned_url:E.presigned_url,mime_type:E.mime_type||void 0},C),{})),yield I,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){H(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>H(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;e.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,H(n);let i;r?i={id:n,...r}:i=e;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}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:i}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,H(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let o=new URLSearchParams;return n!==void 0&&o.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&o.append("tag",i),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${o.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let i;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?i=(await this.readDataset({datasetName:r})).id:i=e,H(i);let s=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&s.append("as_of",o),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let o;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?o=(await this.readDataset({datasetName:r})).id:o=e,H(o);let c={split_name:n,examples:i.map(u=>(H(u),u)),remove:s},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(u,"update dataset splits",!0),u})}async createFeedback(e,r,n){let{runId:i=null,key:s,score:o,value:c,correction:l,comment:u,sourceInfo:d,feedbackSourceType:f="api",sourceRunId:y,feedbackId:h,feedbackConfig:g,projectId:b,comparativeExperimentId:w,sessionId:v,startTime:S,extendTraceRetention:p}=typeof e=="object"&&e!==null?e:{runId:e,key:r,...n};if(!i&&!b)throw new Error("One of runId or projectId must be provided");if(i&&b)throw new Error("Only one of runId or projectId can be provided");i&&v===void 0&&await this._checkFeedbackSessionId();let T={type:f??"api",metadata:d??{}};y!==void 0&&T?.metadata!==void 0&&!T.metadata.__run&&(T.metadata.__run={run_id:y}),T?.metadata!==void 0&&T.metadata.__run?.run_id!==void 0&&H(T.metadata.__run.run_id);let I={id:h??Er(),run_id:i,key:s,score:ld(o),value:c,correction:l,comment:u,feedback_source:T,comparative_experiment_id:w,feedbackConfig:g,session_id:v??b,start_time:S,extend_trace_retention:p},C=JSON.stringify(I),k=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let E=await this._fetch(k,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:C});return await L(E,"create feedback",!0),E}),I}async updateFeedback(e,{score:r,value:n,correction:i,comment:s}){let o={};r!=null&&(o.score=ld(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),s!=null&&(o.comment=s),H(e);let c=JSON.stringify(o);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(l,"update feedback",!0),l})}async readFeedback(e){H(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){H(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let s of e)H(s),i.append("run",s);if(r)for(let s of r)i.append("key",s);if(n)for(let s of n)i.append("source",s);for await(let s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:i}={}){let s={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};let o=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:o,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:s,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(l.extra.metadata=o);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){H(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,i){let s=this._selectEvalResults(e),o=[];for(let c of s){let l=n||{};c.evaluatorInfo&&(l={...c.evaluatorInfo,...l});let u=null;c.targetRunId?u=c.targetRunId:r&&(u=r.id),o.push(await this.createFeedback(u,c.key,{score:c.score,value:c.value,comment:c.comment,correction:c.correction,sourceInfo:l,sourceRunId:c.sourceRunId,feedbackConfig:c.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id??i,startTime:r?.start_time}))}return[s,o]}async logEvaluationFeedback(e,r,n,i){if(e!=null&&typeof e=="object"&&"evaluatorResponse"in e){let[o]=await this._logEvaluationFeedback(e.evaluatorResponse,e.run,e.sourceInfo,e.projectId);return o}let[s]=await this._logEvaluationFeedback(e,r,n,i);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=e,s={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await L(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i}=e,s=new URLSearchParams;r&&r.forEach(c=>{s.append("key",c)}),n&&s.append("name_contains",n),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(let c of this._getPaginated("/feedback-configs",s))if(yield*c,o+=c.length,i!==void 0&&o>=i)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,s={feedback_key:e};return n!==void 0&&(s.feedback_config=n),i!==void 0&&(s.is_lower_score_better=i),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await L(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._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:s}=e,o=new URLSearchParams;r&&r.forEach((l,u)=>{H(l,`queueIds[${u}]`),o.append("ids",l)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(s!==void 0?Math.min(s,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",o))if(yield*l,c++,s!==void 0&&c>=s)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:i,rubricInstructions:s,rubricItems:o}=e,c={name:r,description:n,id:i||zt(),rubric_instructions:s,rubric_items:o},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._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:s,rubricItems:o}=r,c={};n!==void 0&&(c.name=n),i!==void 0&&(c.description=i),s!==void 0&&(c.rubric_instructions=s),o!==void 0&&(c.rubric_items=o);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs`,i=r.every(c=>typeof c=="string"),s,o;i?(_e("Passing run IDs as strings to addRunsToAnnotationQueue() is deprecated and will be removed after Jan 31, 2027. Use RunKey[] instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#annotation-queues-add-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_ADD_RUNS_STRING_IDS"}),s=n,o=JSON.stringify(r.map((c,l)=>H(c,`runs[${l}]`).toString()))):(s=`${n}/by-key`,o=JSON.stringify(r.map((c,l)=>{let u={run_id:H(c.runId,`runs[${l}].runId`).toString(),session_id:H(c.sessionId,`runs[${l}].sessionId`).toString(),start_time:typeof c.startTime=="string"?c.startTime:new Date(c.startTime).toISOString()};return c.sourceProposedExampleId!=null&&(u.source_proposed_example_id=H(c.sourceProposedExampleId,`runs[${l}].sourceProposedExampleId`).toString()),u}))),await this.caller.call(async()=>{let c=await this._fetch(s,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"add runs to annotation queue",!0),c})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${H(e,"queueId")}/run`,s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"get run from annotation queue"),o})).json();return Br(s)}async*listRunsFromAnnotationQueue(e,r={}){let{status:n,limit:i}=r,s=new URLSearchParams,o=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;n&&s.append("status",n),s.append("limit",o.toString());let c=0,l=`/annotation-queues/${H(e,"queueId")}/runs`;for await(let u of this._getPaginated(l,s))for(let d of u)if(yield Br(d),c++,c>=o)return}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs/${H(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(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/${H(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(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.
|
|
137
|
+
|
|
138
|
+
Current tenant: ${n.tenant_handle}
|
|
139
|
+
|
|
140
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _createCommitTags(e,r,n){let i=typeof n=="string"?[n]:n;await Promise.all(i.map(async s=>this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:s,commit_id:r})});return await L(o,"create commit tag"),o})))}async _likeOrUnlikePrompt(e,r){let[n,i,s]=Ce(e),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,`${r?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[r,n,i]=Ce(e);if(await this._currentTenantIsOwner(r)){let s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.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,i]=Ce(e);for await(let s of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,o=>o.commits))yield*s}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,i=>i.repos))yield*n}async getPrompt(e){let[r,n,i]=Ce(e),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return c?.status===404?null:(await L(c,"get prompt"),c)}))?.json();return o?.repo?o.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
|
|
141
|
+
|
|
142
|
+
creating a LangChain Hub handle.
|
|
143
|
+
You can add a handle by creating a public prompt at:
|
|
144
|
+
|
|
145
|
+
https://smith.langchain.com/prompts`);let[i,s,o]=Ce(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let c={repo_handle:s,...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._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(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[i,s,o]=Ce(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c,...n?.description!==void 0&&{description:n.description}},u=JSON.stringify(l),f=await(await this.caller.call(async()=>{let h=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(h,"create commit"),h})).json(),y=f.commit??f;return n?.tags&&await this._createCommitTags(`${i}/${s}`,y.id,n.tags),this._getPromptUrl(`${i}/${s}${y.commit_hash?`:${y.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 o of r){let c=o.id,l={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=Re(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),o.inputs){let f=Re(o.inputs,`Serializing inputs for example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.inputs`,y)}if(o.outputs){let f=Re(o.outputs,`Serializing outputs whle updating example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.outputs`,y)}if(o.attachments)for(let[f,y]of Object.entries(o.attachments)){let h,g;Array.isArray(y)?[h,g]=y:(h=y.mimeType,g=y.data);let b=new Blob([g],{type:`${h}; length=${g.byteLength}`});n.append(`${c}.attachment.${f}`,b)}if(o.attachments_operations){let f=Re(o.attachments_operations,`Serializing attachments while updating example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.attachments_operations`,y)}}let i=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(o,"update examples"),o})).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 s of r){let o=(s.id??zt()).toString(),c={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},l=Re(c,`Serializing body for uploaded example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(n.append(o,u),s.inputs){let d=Re(s.inputs,`Serializing inputs for uploaded example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(s.outputs){let d=Re(s.outputs,`Serializing outputs for uploaded example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let y,h;Array.isArray(f)?[y,h]=f:(y=f.mimeType,h=f.data);let g=new Blob([h],{type:`${y}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,g)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Ce(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(s);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(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,i]=Ce(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"delete prompt"),o})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,s]=Ce(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(l,"pull prompt commit"),l})).json();return{owner:n,repo:i,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples,hub_model_config:c.model_config,hub_model_provider:c.model_provider}}async pullPromptCommit(e,r){Ry(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),s=this._promptCache.get(i,n);if(s)return s;let o=await n();return this._promptCache.set(i,o,n),o}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&["description","readme","tags","isPublic"].some(i=>r[i]!==void 0)&&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,tags:r?.commitTags,description:r?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[r,n]=Ce(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=Ce(e);return this._repoExists(r,n)}async pullAgent(e,r){return await this._pullDirectory(e,"agent",r?.version)}async pullSkill(e,r){return await this._pullDirectory(e,"skill",r?.version)}async pushAgent(e,r){return this._pushDirectory(e,"agent",r)}async pushSkill(e,r){return this._pushDirectory(e,"skill",r)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,r){let n=new URLSearchParams;n.append("repo_type",e),n.append("is_archived",(!!r?.isArchived).toString()),r?.isPublic!==void 0&&n.append("is_public",r.isPublic.toString()),r?.query&&n.append("query",r.query);for await(let i of this._getPaginated("/repos",n,s=>s.repos))yield*i}async _pullDirectory(e,r,n){let[i,s,o]=Ce(e),c=n??(o!=="latest"?o:void 0),l=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories`)}`);return l.searchParams.set("repo_type",r),c&&l.searchParams.set("commit",c),await(await this.caller.call(async()=>{let d=await this._fetch(l.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(d,"pull directory"),d})).json()}async _pushDirectory(e,r,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[i,s]=Ce(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,s))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,s,n);else{let y=/^[a-z][a-z0-9-_]*$/;if(!y.test(s))throw new Error(`Invalid repo_handle ${JSON.stringify(s)}: must match ${y}`);await this._createRepo(s,r,n)}let o={files:n.files};n.parentCommit&&(o.parent_commit=n.parentCommit);let u=(await(await this.caller.call(async()=>{let y=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(o)});return await L(y,`push ${r}`),y})).json()).commit.commit_hash,d=await this._getSettings(),f=new URLSearchParams({organizationId:d.id});return`${this.getHostUrl()}/context/${s}/${u.slice(0,8)}?${f.toString()}`}async _deleteDirectory(e){let[r,n]=Ce(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete",r);await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${n}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"delete directory"),i})}async _repoExists(e,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"check repo exists"),n}),!0}catch(n){if(wi(n))return!1;throw n}}async _createRepo(e,r,n){let i={repo_handle:e,repo_type:r,is_public:!!n.isPublic};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags);try{await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await L(s,`create ${r}`),s})}catch(s){if(Gu(s))return;throw s}}async _updateRepoMetadata(e,r,n){let i={};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags),n.isPublic!==void 0&&(i.is_public=n.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await L(s,"update repo metadata"),s})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,o]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:s,apiKey:"placeholder"}),l=await c.readSharedDataset(o),u=i||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(o),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(y=>y.inputs),outputs:d.flatMap(y=>y.outputs?[y.outputs]:[]),datasetId:f.id})}catch(y){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),y}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return H(e),[r,e]}catch{}try{let o=new URL(e).pathname.split("/").filter(c=>c!=="");if(o.length>=n){let c=o[o.length-n];return[r,c]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} 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();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await du()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(Rt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function fd(t){return"dataset_id"in t||"dataset_name"in t}a(fd,"isExampleCreate");var ft=Symbol.for("lc:context_variables");var xi=Symbol.for("langsmith:replica_trace_roots");function La(t,e){if(ft in t)return t[ft][e]}a(La,"getContextVar");function hd(t,e,r){let n=ft in t?t[ft]:{};n[e]=r,t[ft]=n}a(hd,"setContextVar");var pn=36,Fy="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function gd(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Ms(r,Fy)}a(gd,"getReplicaKey");function By(t){return t.replace(/[-:.]/g,"")}a(By,"stripNonAlphanumeric");function _d(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}a(_d,"getMicrosecondPrecisionDatestring");function Da(t,e,r=1){let n=_d(t,r);return{dottedOrder:By(n)+e,microsecondPrecisionDatestring:n}}a(Da,"convertToDottedOrderFormat");var jy=new Set(["projectName","primary","updates","reroot"]);function Hy(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||jy.has(r)&&(e[r]=t[r]);return e}a(Hy,"filterReplicaForHeaders");var Ii=class t{static{a(this,"Baggage")}constructor(e,r,n,i){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=i}static fromHeader(e){let r=e.split(","),n={},i=[],s,o;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?i=d.split(","):l==="langsmith-project"?s=d:l==="langsmith-replicas"&&(o=JSON.parse(d).map(y=>Array.isArray(y)?y:Hy(y)))}return new t(n,i,s,o)}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(",")}},et=class t{static{a(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}),bd(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,s=i.client??t.getSharedClient(),o={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:s}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=_d(this.start_time,this.execution_order)),this.id||(this.id=Jn(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=Wy(this.replicas),!this.dotted_order){let{dottedOrder:c}=Da(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:sn(),child_runs:[],api_url:ye("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ye("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new Rt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(y=>{let{reroot:h,...g}=y;return g}),i=e.replicas??n,s=new t({...e,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),o=this.extra?.metadata??{},c=s.extra?.metadata??{};Object.keys(o).length>0&&(s.extra={...s.extra,metadata:{...o,...c}}),ft in this&&(s[ft]=this[ft]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(Gy(u)){let y={...u},h=zy(y.callbacks)?y.callbacks.copy?.():void 0;h&&(Object.assign(h,{_parentRunId:s.id}),h.handlers?.find(wd)?.updateFromRunTree?.(s),y.callbacks=h),s.extra[l]=y}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(s),s}async end(e,r,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,r,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[c,l]of Object.entries(r))i.runtime[c]||(i.runtime[c]=l);let s=e.parent_run?.id??e.parent_run_id,o;return n?o=[]:o=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:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:o,parent_run_id:s,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("."),i=null;for(let s=0;s<n.length;s++)if(n[s].slice(-pn)===e){i=s;break}if(i!==null){let s=n.slice(i+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-pn):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=La(this,xi)??{};n[e]=r,hd(this,xi,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,primary:n,runtimeEnv:i,excludeChildRuns:s=!0,reroot:o=!1,distributedParentId:c,apiUrl:l,apiKey:u,workspaceId:d}=e,f=this._convertToCreate(this,i,s);if(n===void 0&&r===this.project_name)return{...f,session_name:r};if(o){if(c)this._sliceParentId(c,f);else if(f.parent_run_id=void 0,f.dotted_order){let p=f.dotted_order.split(".");p.length>0&&(f.dotted_order=p[p.length-1],f.trace_id=f.id)}let S=gd({projectName:r,apiUrl:l,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(S,f.id)}let y;if(!o){let S=La(this,xi)??{},p=gd({projectName:r,apiUrl:l,apiKey:u,workspaceId:d});if(y=S[p],y&&(f.trace_id=y,f.dotted_order)){let T=f.dotted_order.split("."),I=null;for(let C=0;C<T.length;C++)if(T[C].slice(-pn)===y){I=C;break}if(I!==null){let C=T.slice(I);f.dotted_order=C.join(".")}}}if(n)return{...f,session_name:r};let h=f.id,g=xr(h,r),b;f.trace_id?b=xr(f.trace_id,r):b=g;let w;f.parent_run_id&&(w=xr(f.parent_run_id,r));let v;return f.dotted_order&&(v=f.dotted_order.split(".").map(T=>{let I=T.slice(-pn),C=xr(I,r);return T.slice(0,-pn)+C}).join(".")),{...f,id:g,trace_id:b,parent_run_id:w,dotted_order:v,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=ti();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,primary:i,apiKey:s,apiUrl:o,workspaceId:c,reroot:l,client:u}of this.replicas){let d=this._remapForProject({projectName:n??this.project_name,primary:i,runtimeEnv:r,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:s,workspaceId:c});await(u??this.client).createRun(d,{apiKey:s,apiUrl:o,workspaceId:c})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){_e("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,primary:n,apiKey:i,apiUrl:s,workspaceId:o,updates:c,reroot:l,client:u}of this.replicas){let d=this._remapForProject({projectName:r??this.project_name,primary:n,runtimeEnv:void 0,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:o}),f={id:d.id,name:d.name,run_type:d.run_type,start_time:d.start_time,outputs:d.outputs,error:d.error,parent_run_id:d.parent_run_id,session_name:d.session_name,reference_example_id:d.reference_example_id,end_time:d.end_time,dotted_order:d.dotted_order,trace_id:d.trace_id,events:d.events,tags:d.tags,extra:d.extra,attachments:this.attachments,...c};e?.excludeInputs||(f.inputs=d.inputs),await(u??this.client).updateRun(d.id,f,{apiKey:i,apiUrl:s,workspaceId:o})}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,i,s,o,c=Gs();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(f=>f?.name=="langchain_tracer");i=d?.getRun?.(u),s=d?.projectName,o=d?.client,c=c||!!d}return i?new t({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:c,project_name:s,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:o,tracingEnabled:c,project_name:s})}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,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),o=s.split(".").map(d=>{let[f,y]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:y}}),c=o[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:c,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let d=Ii.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 Ii(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,i]of Object.entries(r))e.set(n,i);return r}};Object.defineProperty(et,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function bd(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}a(bd,"isRunTree");function wd(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}a(wd,"isLangChainTracerLike");function yd(t){return Array.isArray(t)&&t.some(e=>wd(e))}a(yd,"containsLangChainTracerLike");function zy(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}a(zy,"isCallbackManagerLike");function Gy(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(yd(e?.handlers)||yd(e))}a(Gy,"isRunnableConfigLike");function Vy(){let t=ye("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}if(n.project_name!==void 0&&n.project_name!==null&&typeof n.project_name!="string"){console.warn(`Invalid project_name type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.project_name}`);continue}if(n.primary!==void 0&&typeof n.primary!="boolean"){console.warn(`Invalid primary type in LANGSMITH_RUNS_ENDPOINTS: expected boolean, got ${typeof n.primary}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key,projectName:n.project_name??void 0,primary:n.primary??void 0})}return r}else if(typeof e=="object"&&e!==null){qy(e);let r=[];for(let[n,i]of Object.entries(e)){let s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);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(Wu(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"),[]}}a(Vy,"_getWriteReplicasFromEnv");function Wy(t){let e=t?t.map(r=>Array.isArray(r)?{projectName:r[0],updates:r[1]}:r):Vy();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}a(Wy,"_ensureWriteReplicas");function qy(t){if(Object.keys(t).length>0&&Z("ENDPOINT"))throw new _i}a(qy,"_checkEndpointEnvUnset");var Ky=a(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function $a(t,e){if(t)return new et({...t,start_time:t._serialized_start_time??t.start_time,parent_run:$a(e),child_runs:t.child_runs.map(r=>$a(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:tl()},tracingEnabled:!1})}a($a,"convertRunToRunTree");function Ua(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}a(Ua,"_coerceToDict");function jr(t){return typeof t._addRunToRunMap=="function"}a(jr,"isBaseTracer");var cr=class extends _r{static{a(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?Ky(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
146
|
+
|
|
147
|
+
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Da(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.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 s=$a(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}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,i,s,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,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:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,i,s,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,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:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,i,s,o,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:o??"chain",child_runs:[],extra:s?{...l,metadata:s}:{...l},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=Ua(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=Ua(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=Ua(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,i,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??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:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,i,s,o){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,s,o);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,i,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??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:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,i,s,o){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,s,o);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,i,s){let o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(o,t,{chunk:s?.chunk}),o}};var Td={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 Pe(t,e){return`${t.open}${e}${t.close}`}a(Pe,"wrap");function qe(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}a(qe,"tryJsonStringify");function Ed(t){return typeof t=="string"?t.trim():t==null?t:qe(t,t.toString())}a(Ed,"formatKVMapItem");function Lt(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}a(Lt,"elapsed");var{color:Fe}=Td,Fa=class extends cr{static{a(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,i)=>{let s=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?Pe(Td.bold,s):s}).join(" > ");return Pe(Fe.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[chain/start]")} [${e}] Entering Chain run with input: ${qe(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[chain/end]")} [${e}] [${Lt(t)}] Exiting Chain run with output: ${qe(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[chain/error]")} [${e}] [${Lt(t)}] Chain run errored with error: ${qe(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(`${Pe(Fe.green,"[llm/start]")} [${e}] Entering LLM run with input: ${qe(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[llm/end]")} [${e}] [${Lt(t)}] Exiting LLM run with output: ${qe(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[llm/error]")} [${e}] [${Lt(t)}] LLM run errored with error: ${qe(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Ed(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[tool/end]")} [${e}] [${Lt(t)}] Exiting Tool run with output: "${Ed(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[tool/error]")} [${e}] [${Lt(t)}] Tool run errored with error: ${qe(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${qe(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[retriever/end]")} [${e}] [${Lt(t)}] Exiting Retriever run with output: ${qe(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[retriever/error]")} [${e}] [${Lt(t)}] Retriever run errored with error: ${qe(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Pe(Fe.blue,"[agent/action]")} [${r}] Agent selected action: ${qe(e.actions[e.actions.length-1],"[action]")}`)}};var Ba,ja=a(()=>(Ba===void 0&&(Ba=new Rt(Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Ba),"getDefaultLangChainClientSingleton");var Sd=new Set(["ls_agent_type"]);function Jy(t){let e;for(let r of t)for(let n of r)St.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Pn(e,n.message.usage_metadata));return e}a(Jy,"_getUsageMetadataFromGenerations");var mn=class Ha extends cr{static{a(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:i,replicas:s,metadata:o,tags:c}=e;this.projectName=n??sn(),this.replicas=s,this.exampleId=r,this.client=i??ja(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];let l=Ha.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){vd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){vd(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=Jy(r.generations);if(n!==void 0){e.extra=e.extra??{};let i=e.extra.metadata??{};i.usage_metadata=n,e.extra.metadata=i}}}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[o,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,o)||Sd.has(o))&&(n[o]=c)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new Ha({...this.fields,metadata:n,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}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 i=[r];for(;i.length>0;){let s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.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 et({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Ks(!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 vd(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[i,s]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||Sd.has(i))&&r[i]!==s&&(r[i]=s,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}a(vd,"_patchMissingTracingDefaults");var Ai=He(Hn(),1);var hn;function Zy(){return new("default"in Ai.default?Ai.default.default:Ai.default)({autoStart:!0,concurrency:1})}a(Zy,"createQueue");function Yy(){return typeof hn>"u"&&(hn=Zy()),hn}a(Yy,"getQueue");async function ne(t,e){if(e===!0){let r=It();r!==void 0?await r.run(void 0,async()=>t()):await t()}else hn=Yy(),hn.add(async()=>{let r=It();r!==void 0?await r.run(void 0,async()=>t()):await t()})}a(ne,"consumeCallback");var xd=a(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Xe(e)==="true"),"isTracingEnabled");function za(t){let e=It();if(e!==void 0)return e.getStore()?.[Ht]?.[t]}a(za,"getContextVariable");var Xy=Symbol("lc:configure_hooks"),Id=a(()=>za(Xy)||[],"_getConfigureHooks");var Qy=class{static{a(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Ci=class{static{a(this,"BaseRunManager")}constructor(t,e,r,n,i,s,o,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=o,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>ne(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,i){await Promise.all(this.handlers.map(s=>ne(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},e_=class extends Ci{static{a(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new lr(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=>ne(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=>ne(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)))}},Ad=class extends Ci{static{a(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,i,s){await Promise.all(this.handlers.map(o=>ne(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(c){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${c}`),o.raiseError)throw c}},o.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>ne(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,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},t_=class extends Ci{static{a(this,"CallbackManagerForChainRun")}getChild(t){let e=new lr(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,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>ne(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=>ne(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)))}},r_=class extends Ci{static{a(this,"CallbackManagerForToolRun")}getChild(t){let e=new lr(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=>ne(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=>ne(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=>ne(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)))}},lr=class gn extends Qy{static{a(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,i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:st();return await Promise.all(this.handlers.map(y=>{if(!y.ignoreLLM)return jr(y)&&y._createRunForLLMStart(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l),ne(async()=>{try{await y.handleLLMStart?.(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l)}catch(h){if((y.raiseError?console.error:console.warn)(`Error in handler ${y.constructor.name}, handleLLMStart: ${h}`),y.raiseError)throw h}},y.awaitHandlers)})),new Ad(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:st();return await Promise.all(this.handlers.map(y=>{if(!y.ignoreLLM)return jr(y)&&y._createRunForChatModelStart(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l),ne(async()=>{try{if(y.handleChatModelStart)await y.handleChatModelStart?.(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l);else if(y.handleLLMStart){let h=Dn(u);await y.handleLLMStart?.(e,[h],f,this._parentRunId,s,this.tags,this.metadata,l)}}catch(h){if((y.raiseError?console.error:console.warn)(`Error in handler ${y.constructor.name}, handleLLMStart: ${h}`),y.raiseError)throw h}},y.awaitHandlers)})),new Ad(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return jr(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,c,u),ne(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,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 t_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return jr(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),ne(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 r_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return jr(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),ne(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 e_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,s){await Promise.all(this.handlers.map(o=>ne(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${c}`),o.raiseError)throw c}},o.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 gn(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);n.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(let i of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends _r{static{a(this,"Handler")}name=st();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,s,o,c){return this._configureSync(e,r,n,i,s,o,c)}static _configureSync(e,r,n,i,s,o,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new gn,l.setHandlers(e?.map(Ga)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(Ga):r?.handlers,!1));let u=Xe("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=mn.getTraceableRunTree(),f=d?.tracingEnabled??xd();if(d?.tracingEnabled===!1&&l){let b=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of b)l.removeHandler(w)}let y=f||(Xe("LANGCHAIN_TRACING")??!1);if(u||y){if(l||(l=new gn),u&&!l.handlers.some(b=>b.name===Fa.prototype.name)){let b=new Fa;l.addHandler(b,!0)}if(y&&!l.handlers.some(b=>b.name==="langchain_tracer")&&f){let b=new mn;l.addHandler(b,!0)}f&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(b=>b.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:b,inheritable:w=!0,handlerClass:v,envVar:S}of Id()){let p=S&&Xe(S)==="true"&&v,T,I=b!==void 0?za(b):void 0;I&&rl(I)?T=I:p&&(T=new v({})),T!==void 0&&(l||(l=new gn),l.handlers.some(C=>C.name===T.name)||l.addHandler(T,w))}(n||i)&&l&&(l.addTags(n??[]),l.addTags(i??[],!1)),(s||o)&&l&&(l.addMetadata(s??{}),l.addMetadata(o??{},!1));let h=c?.tracerInheritableMetadata,g=c?.tracerInheritableTags;return l&&(h||g)&&(l.handlers=l.handlers.map(b=>b instanceof mn?b.copyWithTracingConfig({metadata:h,tags:g}):b),l.inheritableHandlers=l.inheritableHandlers.map(b=>b instanceof mn?b.copyWithTracingConfig({metadata:h,tags:g}):b)),l}};function Ga(t){return"name"in t?t:_r.fromMethods(t)}a(Ga,"ensureHandler");var Rd=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},n_=new Rd,Cd=Symbol.for("lc:child_config"),i_=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return It()??n_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Cd]}runWithConfig(t,e,r){let n=lr._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),s=i.getStore(),o=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&o?l=c.getRunTreeWithTracingConfig(o):r||(l=new et({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[Cd]:t}),s!==void 0&&s[Ht]!==void 0&&(l===void 0&&(l={}),l[Ht]=s[Ht]),i.run(l,e)}initializeGlobalInstance(t){It()===void 0&&el(t)}},yn=new i_;var s_=Object.prototype.hasOwnProperty;function Md(t,e){return s_.call(t,e)}a(Md,"hasOwnProperty");function Pd(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)Md(t,r)&&e.push(r);return e}a(Pd,"_objectKeys");function wt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}a(wt,"_deepClone");function Oi(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}a(Oi,"isInteger");function Nd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(Nd,"unescapePathComponent");function Ri(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Ri(t[r]))return!0}else if(typeof t=="object"){let r=Pd(t),n=r.length;for(var e=0;e<n;e++)if(Ri(t[r[e]]))return!0}}return!1}a(Ri,"hasUndefined");function kd(t,e){let r=[t];for(let n in e){let i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
|
|
148
|
+
`)}a(kd,"patchErrorMessageFormatter");var Ld=class extends Error{static{a(this,"PatchError")}constructor(t,e,r,n,i){super(kd(t,{name:e,index:r,operation:n,tree:i})),this.name=e,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=kd(t,{name:e,index:r,operation:n,tree:i})}};var Dd=V({JsonPatchError:a(()=>se,"JsonPatchError"),_areEquals:a(()=>_n,"_areEquals"),applyOperation:a(()=>ur,"applyOperation"),applyPatch:a(()=>Pi,"applyPatch"),applyReducer:a(()=>c_,"applyReducer"),deepClone:a(()=>a_,"deepClone"),getValueByPointer:a(()=>ki,"getValueByPointer"),validate:a(()=>Ud,"validate"),validator:a(()=>Mi,"validator")}),se=Ld,a_=wt,Hr={add:a(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:a(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:a(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:a(function(t,e,r){let n=ki(r,this.path);n&&(n=wt(n));let i=ur(r,{op:"remove",path:this.from}).removed;return ur(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},"move"),copy:a(function(t,e,r){let n=ki(r,this.from);return ur(r,{op:"add",path:this.path,value:wt(n)}),{newDocument:r}},"copy"),test:a(function(t,e,r){return{newDocument:r,test:_n(t[e],this.value)}},"test"),_get:a(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},o_={add:a(function(t,e,r){return Oi(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:a(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:a(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:Hr.move,copy:Hr.copy,test:Hr.test,_get:Hr._get};function ki(t,e){if(e=="")return t;var r={op:"_get",path:e};return ur(t,r),r.value}a(ki,"getValueByPointer");function ur(t,e,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Mi(e,0)),e.path===""){let o={newDocument:t};if(e.op==="add")return o.newDocument=e.value,o;if(e.op==="replace")return o.newDocument=e.value,o.removed=t,o;if(e.op==="move"||e.op==="copy")return o.newDocument=ki(t,e.from),e.op==="move"&&(o.removed=t),o;if(e.op==="test"){if(o.test=_n(t,e.value),o.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o.newDocument=t,o}else{if(e.op==="remove")return o.removed=t,o.newDocument=null,o;if(e.op==="_get")return e.value=t,o;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return o}}else{n||(t=wt(t));let o=(e.path||"").split("/"),c=t,l=1,u=o.length,d,f,y;for(typeof r=="function"?y=r:y=Mi;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Nd(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&o[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=o.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&y(e,0,t,d)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!Oi(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",s,e,t);Oi(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",s,e,t);let h=o_[e.op].call(e,c,f,t);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}}else if(l>=u){let h=Hr[e.op].call(e,c,f,t);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}if(c=c[f],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}a(ur,"applyOperation");function Pi(t,e,r,n=!0,i=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=wt(t));let s=new Array(e.length);for(let o=0,c=e.length;o<c;o++)s[o]=ur(t,e[o],r,!0,i,o),t=s[o].newDocument;return s.newDocument=t,s}a(Pi,"applyPatch");function c_(t,e,r){let n=ur(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}a(c_,"applyReducer");function Mi(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(Hr[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")&&Ri(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 i=t.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)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 o=Ud([{op:"_get",path:t.from,value:void 0}],r);if(o&&o.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)}a(Mi,"validator");function Ud(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pi(wt(e),wt(t),r||!0);else{r=r||Mi;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof se)return i;throw i}}a(Ud,"validate");function _n(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),i,s,o;if(r&&n){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!_n(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(o=c[i],!_n(t[o],e[o]))return!1;return!0}return t!==t&&e!==e}a(_n,"_areEquals");({...Dd});var f$=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 h_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,g_=[0,31,28,31,30,31,30,31,31,30,31,30,31],y_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,__=/^(?=.{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,b_=/^(?:[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,w_=/^(?:(?:[^\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,E_=/^(?:(?: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,T_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,v_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,S_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,x_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,I_=a(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(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),A_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,C_=/^((([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,R_=a(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 pt(t){return t.test.bind(t)}a(pt,"bind");var O_={date:$d,time:Fd.bind(void 0,!1),"date-time":P_,duration:R_,uri:D_,"uri-reference":pt(b_),"uri-template":pt(w_),url:pt(E_),email:I_,hostname:pt(__),ipv4:pt(A_),ipv6:pt(C_),regex:$_,uuid:pt(T_),"json-pointer":pt(v_),"json-pointer-uri-fragment":pt(S_),"relative-json-pointer":pt(x_)};function k_(t){return t%4===0&&(t%100!==0||t%400===0)}a(k_,"isLeapYear");function $d(t){let e=t.match(h_);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&k_(r)?29:g_[n])}a($d,"date");function Fd(t,e){let r=e.match(y_);if(!r)return!1;let n=+r[1],i=+r[2],s=+r[3],o=!!r[5];return(n<=23&&i<=59&&s<=59||n==23&&i==59&&s==60)&&(!t||o)}a(Fd,"time");var M_=/t|\s/i;function P_(t){let e=t.split(M_);return e.length==2&&$d(e[0])&&Fd(!0,e[1])}a(P_,"date_time");var N_=/\/|:/,L_=/^(?:[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 D_(t){return N_.test(t)&&L_.test(t)}a(D_,"uri");var U_=/[^\\]\\Z/;function $_(t){if(U_.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}a($_,"regex");var Bd;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(Bd||(Bd={}));var Xd=He(Yd(),1);var eb=Object.defineProperty,tb=a((t,e,r)=>e in t?eb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),rb=a((t,e,r)=>(tb(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function nb(t,e){let r=Array.from({length:t.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let s=t.slice(r[i].start,r[i+1].end),o=e.get(s.join(","));o!=null&&(n==null||o<n[0])&&(n=[o,i])}if(n!=null){let i=n[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}a(nb,"bytePairMerge");function ib(t,e){return t.length===1?[e.get(t.join(","))]:nb(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}a(ib,"bytePairEncode");function sb(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}a(sb,"escapeRegex");var Za=class{static{a(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(`
|
|
149
|
+
`).filter(Boolean).reduce((n,i)=>{let[s,o,...c]=i.split(" "),l=Number.parseInt(o,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,i]of Object.entries(r)){let s=Xd.default.toByteArray(n);this.rankMap.set(s.join(","),i),this.textMap.set(i,s)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,s])=>(n[s]=this.textEncoder.encode(i),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Za.specialTokenRegex(Object.keys(this.specialTokens)),s=[],o=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(c.size>0){let u=Za.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(;i.lastIndex=d,u=i.exec(t),!(u==null||o.has(u[0]));)d=u.index+1;let f=u?.index??t.length;for(let h of t.substring(l,f).matchAll(n)){let g=this.textEncoder.encode(h[0]),b=this.rankMap.get(g.join(","));if(b!=null){s.push(b);continue}s.push(...ib(g,this.rankMap))}if(u==null)break;let y=this.specialTokens[u[0]];s.push(y),l=u.index+u[0].length}return s}decode(t){let e=[],r=0;for(let s=0;s<t.length;++s){let o=t[s],c=this.textMap.get(o)??this.inverseSpecialTokens[o];c!=null&&(e.push(c),r+=c.length)}let n=new Uint8Array(r),i=0;for(let s of e)n.set(s,i),i+=s.length;return this.textDecoder.decode(n)}},Ya=Za;rb(Ya,"specialTokenRegex",t=>new RegExp(t.map(e=>sb(e)).join("|"),"g"));var rf=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var nf=["image","video","audio","text-plain","file"];var cb=["text","reasoning",...rf,...nf];var gb=a(function(){let t={};t.parser=function(_,m){return new r(_,m)},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(_,m){if(!(this instanceof r))return new r(_,m);var R=this;i(R),R.q=R.c="",R.bufferCheckPosition=t.MAX_BUFFER_LENGTH,R.opt=m||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!_,R.noscript=!!(_||R.opt.noscript),R.state=E.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(g)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),D(R,"onready")}a(r,"SAXParser"),Object.create||(Object.create=function(_){function m(){}return a(m,"F"),m.prototype=_,new m}),Object.keys||(Object.keys=function(_){var m=[];for(var R in _)_.hasOwnProperty(R)&&m.push(R);return m});function n(_){for(var m=Math.max(t.MAX_BUFFER_LENGTH,10),R=0,x=0,J=e.length;x<J;x++){var le=_[e[x]].length;if(le>m)switch(e[x]){case"textNode":W(_);break;case"cdata":N(_,"oncdata",_.cdata),_.cdata="";break;case"script":N(_,"onscript",_.script),_.script="";break;default:Se(_,"Max buffer length exceeded: "+e[x])}R=Math.max(R,le)}_.bufferCheckPosition=t.MAX_BUFFER_LENGTH-R+_.position}a(n,"checkBufferLength");function i(_){for(var m=0,R=e.length;m<R;m++)_[e[m]]=""}a(i,"clearBuffers");function s(_){W(_),_.cdata!==""&&(N(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(N(_,"onscript",_.script),_.script="")}a(s,"flushBuffers"),r.prototype={end:a(function(){nt(this)},"end"),write:nm,resume:a(function(){return this.error=null,this},"resume"),close:a(function(){return this.write(null)},"close"),flush:a(function(){s(this)},"flush")};var o=ReadableStream;o||(o=a(function(){},"Stream"));var c=t.EVENTS.filter(function(_){return _!=="error"&&_!=="end"});function l(_,m){return new u(_,m)}a(l,"createStream");function u(_,m){if(!(this instanceof u))return new u(_,m);o.apply(this),this._parser=new r(_,m),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(x){R.emit("error",x),R._parser.error=null},this._decoder=null,c.forEach(function(x){Object.defineProperty(R,"on"+x,{get:a(function(){return R._parser["on"+x]},"get"),set:a(function(J){if(!J)return R.removeAllListeners(x),R._parser["on"+x]=J,J;R.on(x,J)},"set"),enumerable:!0,configurable:!1})})}a(u,"SAXStream"),u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(_){return this._parser.write(_.toString()),this.emit("data",_),!0},u.prototype.end=function(_){return _&&_.length&&this.write(_),this._parser.end(),!0},u.prototype.on=function(_,m){var R=this;return!R._parser["on"+_]&&c.indexOf(_)!==-1&&(R._parser["on"+_]=function(){var x=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);x.splice(0,0,_),R.emit.apply(R,x)}),o.prototype.on.call(R,_,m)};var d="[CDATA[",f="DOCTYPE",y="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",g={xml:y,xmlns:h},b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,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-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function p(_){return _===" "||_===`
|
|
150
|
+
`||_==="\r"||_===" "}a(p,"isWhitespace");function T(_){return _==='"'||_==="'"}a(T,"isQuote");function I(_){return _===">"||p(_)}a(I,"isAttribEnd");function C(_,m){return _.test(m)}a(C,"isMatch");function k(_,m){return!C(_,m)}a(k,"notMatch");var E=0;t.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},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(_){var m=t.ENTITIES[_],R=typeof m=="number"?String.fromCharCode(m):m;t.ENTITIES[_]=R});for(var U in t.STATE)t.STATE[t.STATE[U]]=U;E=t.STATE;function D(_,m,R){_[m]&&_[m](R)}a(D,"emit");function N(_,m,R){_.textNode&&W(_),D(_,m,R)}a(N,"emitNode");function W(_){_.textNode=te(_.opt,_.textNode),_.textNode&&D(_,"ontext",_.textNode),_.textNode=""}a(W,"closeText");function te(_,m){return _.trim&&(m=m.trim()),_.normalize&&(m=m.replace(/\s+/g," ")),m}a(te,"textopts");function Se(_,m){return W(_),_.trackPosition&&(m+=`
|
|
151
|
+
Line: `+_.line+`
|
|
152
|
+
Column: `+_.column+`
|
|
153
|
+
Char: `+_.c),m=new Error(m),_.error=m,D(_,"onerror",m),_}a(Se,"error");function nt(_){return _.sawRoot&&!_.closedRoot&&q(_,"Unclosed root tag"),_.state!==E.BEGIN&&_.state!==E.BEGIN_WHITESPACE&&_.state!==E.TEXT&&Se(_,"Unexpected end"),W(_),_.c="",_.closed=!0,D(_,"onend"),r.call(_,_.strict,_.opt),_}a(nt,"end");function q(_,m){if(typeof _!="object"||!(_ instanceof r))throw new Error("bad call to strictFail");_.strict&&Se(_,m)}a(q,"strictFail");function rm(_){_.strict||(_.tagName=_.tagName[_.looseCase]());var m=_.tags[_.tags.length-1]||_,R=_.tag={name:_.tagName,attributes:{}};_.opt.xmlns&&(R.ns=m.ns),_.attribList.length=0,N(_,"onopentagstart",R)}a(rm,"newTag");function ns(_,m){var R=_.indexOf(":")<0?["",_]:_.split(":"),x=R[0],J=R[1];return m&&_==="xmlns"&&(x="xmlns",J=""),{prefix:x,local:J}}a(ns,"qname");function is(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var m=ns(_.attribName,!0),R=m.prefix,x=m.local;if(R==="xmlns")if(x==="xml"&&_.attribValue!==y)q(_,"xml: prefix must be bound to "+y+`
|
|
154
|
+
Actual: `+_.attribValue);else if(x==="xmlns"&&_.attribValue!==h)q(_,"xmlns: prefix must be bound to "+h+`
|
|
155
|
+
Actual: `+_.attribValue);else{var J=_.tag,le=_.tags[_.tags.length-1]||_;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[x]=_.attribValue}_.attribList.push([_.attribName,_.attribValue])}else _.tag.attributes[_.attribName]=_.attribValue,N(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}a(is,"attrib");function Ut(_,m){if(_.opt.xmlns){var R=_.tag,x=ns(_.tagName);R.prefix=x.prefix,R.local=x.local,R.uri=R.ns[x.prefix]||"",R.prefix&&!R.uri&&(q(_,"Unbound namespace prefix: "+JSON.stringify(_.tagName)),R.uri=x.prefix);var J=_.tags[_.tags.length-1]||_;R.ns&&J.ns!==R.ns&&Object.keys(R.ns).forEach(function(Bo){N(_,"onopennamespace",{prefix:Bo,uri:R.ns[Bo]})});for(var le=0,je=_.attribList.length;le<je;le++){var Oe=_.attribList[le],Ze=Oe[0],$t=Oe[1],xe=ns(Ze,!0),Ft=xe.prefix,im=xe.local,Fo=Ft===""?"":R.ns[Ft]||"",as={name:Ze,value:$t,prefix:Ft,local:im,uri:Fo};Ft&&Ft!=="xmlns"&&!Fo&&(q(_,"Unbound namespace prefix: "+JSON.stringify(Ft)),as.uri=Ft),_.tag.attributes[Ze]=as,N(_,"onattribute",as)}_.attribList.length=0}_.tag.isSelfClosing=!!m,_.sawRoot=!0,_.tags.push(_.tag),N(_,"onopentag",_.tag),m||(!_.noscript&&_.tagName.toLowerCase()==="script"?_.state=E.SCRIPT:_.state=E.TEXT,_.tag=null,_.tagName=""),_.attribName=_.attribValue="",_.attribList.length=0}a(Ut,"openTag");function ss(_){if(!_.tagName){q(_,"Weird empty close tag."),_.textNode+="</>",_.state=E.TEXT;return}if(_.script){if(_.tagName!=="script"){_.script+="</"+_.tagName+">",_.tagName="",_.state=E.SCRIPT;return}N(_,"onscript",_.script),_.script=""}var m=_.tags.length,R=_.tagName;_.strict||(R=R[_.looseCase]());for(var x=R;m--&&_.tags[m].name!==x;)q(_,"Unexpected close tag");if(m<0){q(_,"Unmatched closing tag: "+_.tagName),_.textNode+="</"+_.tagName+">",_.state=E.TEXT;return}_.tagName=R;for(var J=_.tags.length;J-- >m;){var le=_.tag=_.tags.pop();_.tagName=_.tag.name,N(_,"onclosetag",_.tagName);var je={};for(var Oe in le.ns)je[Oe]=le.ns[Oe];var Ze=_.tags[_.tags.length-1]||_;_.opt.xmlns&&le.ns!==Ze.ns&&Object.keys(le.ns).forEach(function($t){var xe=le.ns[$t];N(_,"onclosenamespace",{prefix:$t,uri:xe})})}m===0&&(_.closedRoot=!0),_.tagName=_.attribValue=_.attribName="",_.attribList.length=0,_.state=E.TEXT}a(ss,"closeTag");function Do(_){var m=_.entity,R=m.toLowerCase(),x,J="";return _.ENTITIES[m]?_.ENTITIES[m]:_.ENTITIES[R]?_.ENTITIES[R]:(m=R,m.charAt(0)==="#"&&(m.charAt(1)==="x"?(m=m.slice(2),x=parseInt(m,16),J=x.toString(16)):(m=m.slice(1),x=parseInt(m,10),J=x.toString(10))),m=m.replace(/^0+/,""),isNaN(x)||J.toLowerCase()!==m?(q(_,"Invalid character entity"),"&"+_.entity+";"):String.fromCodePoint(x))}a(Do,"parseEntity");function Uo(_,m){m==="<"?(_.state=E.OPEN_WAKA,_.startTagPosition=_.position):p(m)||(q(_,"Non-whitespace before first tag."),_.textNode=m,_.state=E.TEXT)}a(Uo,"beginWhiteSpace");function $o(_,m){var R="";return m<_.length&&(R=_.charAt(m)),R}a($o,"charAt");function nm(_){var m=this;if(this.error)throw this.error;if(m.closed)return Se(m,"Cannot write after close. Assign an onready handler.");if(_===null)return nt(m);typeof _=="object"&&(_=_.toString());for(var R=0,x="";x=$o(_,R++),m.c=x,!!x;)switch(m.trackPosition&&(m.position++,x===`
|
|
156
|
+
`?(m.line++,m.column=0):m.column++),m.state){case E.BEGIN:if(m.state=E.BEGIN_WHITESPACE,x==="\uFEFF")continue;Uo(m,x);continue;case E.BEGIN_WHITESPACE:Uo(m,x);continue;case E.TEXT:if(m.sawRoot&&!m.closedRoot){for(var J=R-1;x&&x!=="<"&&x!=="&";)x=$o(_,R++),x&&m.trackPosition&&(m.position++,x===`
|
|
157
|
+
`?(m.line++,m.column=0):m.column++);m.textNode+=_.substring(J,R-1)}x==="<"&&!(m.sawRoot&&m.closedRoot&&!m.strict)?(m.state=E.OPEN_WAKA,m.startTagPosition=m.position):(!p(x)&&(!m.sawRoot||m.closedRoot)&&q(m,"Text data outside of root node."),x==="&"?m.state=E.TEXT_ENTITY:m.textNode+=x);continue;case E.SCRIPT:x==="<"?m.state=E.SCRIPT_ENDING:m.script+=x;continue;case E.SCRIPT_ENDING:x==="/"?m.state=E.CLOSE_TAG:(m.script+="<"+x,m.state=E.SCRIPT);continue;case E.OPEN_WAKA:if(x==="!")m.state=E.SGML_DECL,m.sgmlDecl="";else if(!p(x))if(C(b,x))m.state=E.OPEN_TAG,m.tagName=x;else if(x==="/")m.state=E.CLOSE_TAG,m.tagName="";else if(x==="?")m.state=E.PROC_INST,m.procInstName=m.procInstBody="";else{if(q(m,"Unencoded <"),m.startTagPosition+1<m.position){var le=m.position-m.startTagPosition;x=new Array(le).join(" ")+x}m.textNode+="<"+x,m.state=E.TEXT}continue;case E.SGML_DECL:(m.sgmlDecl+x).toUpperCase()===d?(N(m,"onopencdata"),m.state=E.CDATA,m.sgmlDecl="",m.cdata=""):m.sgmlDecl+x==="--"?(m.state=E.COMMENT,m.comment="",m.sgmlDecl=""):(m.sgmlDecl+x).toUpperCase()===f?(m.state=E.DOCTYPE,(m.doctype||m.sawRoot)&&q(m,"Inappropriately located doctype declaration"),m.doctype="",m.sgmlDecl=""):x===">"?(N(m,"onsgmldeclaration",m.sgmlDecl),m.sgmlDecl="",m.state=E.TEXT):(T(x)&&(m.state=E.SGML_DECL_QUOTED),m.sgmlDecl+=x);continue;case E.SGML_DECL_QUOTED:x===m.q&&(m.state=E.SGML_DECL,m.q=""),m.sgmlDecl+=x;continue;case E.DOCTYPE:x===">"?(m.state=E.TEXT,N(m,"ondoctype",m.doctype),m.doctype=!0):(m.doctype+=x,x==="["?m.state=E.DOCTYPE_DTD:T(x)&&(m.state=E.DOCTYPE_QUOTED,m.q=x));continue;case E.DOCTYPE_QUOTED:m.doctype+=x,x===m.q&&(m.q="",m.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:m.doctype+=x,x==="]"?m.state=E.DOCTYPE:T(x)&&(m.state=E.DOCTYPE_DTD_QUOTED,m.q=x);continue;case E.DOCTYPE_DTD_QUOTED:m.doctype+=x,x===m.q&&(m.state=E.DOCTYPE_DTD,m.q="");continue;case E.COMMENT:x==="-"?m.state=E.COMMENT_ENDING:m.comment+=x;continue;case E.COMMENT_ENDING:x==="-"?(m.state=E.COMMENT_ENDED,m.comment=te(m.opt,m.comment),m.comment&&N(m,"oncomment",m.comment),m.comment=""):(m.comment+="-"+x,m.state=E.COMMENT);continue;case E.COMMENT_ENDED:x!==">"?(q(m,"Malformed comment"),m.comment+="--"+x,m.state=E.COMMENT):m.state=E.TEXT;continue;case E.CDATA:x==="]"?m.state=E.CDATA_ENDING:m.cdata+=x;continue;case E.CDATA_ENDING:x==="]"?m.state=E.CDATA_ENDING_2:(m.cdata+="]"+x,m.state=E.CDATA);continue;case E.CDATA_ENDING_2:x===">"?(m.cdata&&N(m,"oncdata",m.cdata),N(m,"onclosecdata"),m.cdata="",m.state=E.TEXT):x==="]"?m.cdata+="]":(m.cdata+="]]"+x,m.state=E.CDATA);continue;case E.PROC_INST:x==="?"?m.state=E.PROC_INST_ENDING:p(x)?m.state=E.PROC_INST_BODY:m.procInstName+=x;continue;case E.PROC_INST_BODY:if(!m.procInstBody&&p(x))continue;x==="?"?m.state=E.PROC_INST_ENDING:m.procInstBody+=x;continue;case E.PROC_INST_ENDING:x===">"?(N(m,"onprocessinginstruction",{name:m.procInstName,body:m.procInstBody}),m.procInstName=m.procInstBody="",m.state=E.TEXT):(m.procInstBody+="?"+x,m.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:C(w,x)?m.tagName+=x:(rm(m),x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:(p(x)||q(m,"Invalid character in tag name"),m.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:x===">"?(Ut(m,!0),ss(m)):(q(m,"Forward-slash in opening tag not followed by >"),m.state=E.ATTRIB);continue;case E.ATTRIB:if(p(x))continue;x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:C(b,x)?(m.attribName=x,m.attribValue="",m.state=E.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case E.ATTRIB_NAME:x==="="?m.state=E.ATTRIB_VALUE:x===">"?(q(m,"Attribute without value"),m.attribValue=m.attribName,is(m),Ut(m)):p(x)?m.state=E.ATTRIB_NAME_SAW_WHITE:C(w,x)?m.attribName+=x:q(m,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if(x==="=")m.state=E.ATTRIB_VALUE;else{if(p(x))continue;q(m,"Attribute without value"),m.tag.attributes[m.attribName]="",m.attribValue="",N(m,"onattribute",{name:m.attribName,value:""}),m.attribName="",x===">"?Ut(m):C(b,x)?(m.attribName=x,m.state=E.ATTRIB_NAME):(q(m,"Invalid attribute name"),m.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(p(x))continue;T(x)?(m.q=x,m.state=E.ATTRIB_VALUE_QUOTED):(q(m,"Unquoted attribute value"),m.state=E.ATTRIB_VALUE_UNQUOTED,m.attribValue=x);continue;case E.ATTRIB_VALUE_QUOTED:if(x!==m.q){x==="&"?m.state=E.ATTRIB_VALUE_ENTITY_Q:m.attribValue+=x;continue}is(m),m.q="",m.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:p(x)?m.state=E.ATTRIB:x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:C(b,x)?(q(m,"No whitespace between attributes"),m.attribName=x,m.attribValue="",m.state=E.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!I(x)){x==="&"?m.state=E.ATTRIB_VALUE_ENTITY_U:m.attribValue+=x;continue}is(m),x===">"?Ut(m):m.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(m.tagName)x===">"?ss(m):C(w,x)?m.tagName+=x:m.script?(m.script+="</"+m.tagName,m.tagName="",m.state=E.SCRIPT):(p(x)||q(m,"Invalid tagname in closing tag"),m.state=E.CLOSE_TAG_SAW_WHITE);else{if(p(x))continue;k(b,x)?m.script?(m.script+="</"+x,m.state=E.SCRIPT):q(m,"Invalid tagname in closing tag."):m.tagName=x}continue;case E.CLOSE_TAG_SAW_WHITE:if(p(x))continue;x===">"?ss(m):q(m,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var je,Oe;switch(m.state){case E.TEXT_ENTITY:je=E.TEXT,Oe="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:je=E.ATTRIB_VALUE_QUOTED,Oe="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:je=E.ATTRIB_VALUE_UNQUOTED,Oe="attribValue";break}if(x===";")if(m.opt.unparsedEntities){var Ze=Do(m);m.entity="",m.state=je,m.write(Ze)}else m[Oe]+=Do(m),m.entity="",m.state=je;else C(m.entity.length?S:v,x)?m.entity+=x:(q(m,"Invalid character in entity name"),m[Oe]+="&"+m.entity+x,m.entity="",m.state=je);continue;default:throw new Error(m,"Unknown state: "+m.state)}return m.position>=m.bufferCheckPosition&&n(m),m}a(nm,"write");return String.fromCodePoint||(function(){var _=String.fromCharCode,m=Math.floor,R=a(function(){var x=16384,J=[],le,je,Oe=-1,Ze=arguments.length;if(!Ze)return"";for(var $t="";++Oe<Ze;){var xe=Number(arguments[Oe]);if(!isFinite(xe)||xe<0||xe>1114111||m(xe)!==xe)throw RangeError("Invalid code point: "+xe);xe<=65535?J.push(xe):(xe-=65536,le=(xe>>10)+55296,je=xe%1024+56320,J.push(le,je)),(Oe+1===Ze||J.length>x)&&($t+=_.apply(null,J),J.length=0)}return $t},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R})(),t},"initializeSax"),yb=gb();var c3=require("@playwright/test");var X6={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 gf=He(no());gf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var $b="claude_4",Fb={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}},Bb=a(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:$b},models:Fb,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=Bb();var s3={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 Jp=require("child_process"),In=require("crypto"),ce=require("fs"),Zp=require("fs/promises"),Yp=require("stream/promises"),Xp=require("http"),Qp=He(require("net")),em=require("os"),Be=require("path");function jb(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}a(jb,"projectReportStatsForTelemetry");function yf(t,e,r){t.emit({outcome:e,stats:jb(r)})}a(yf,"emitReportProcessingStatsTelemetry");var _f=["script","template"],bf='<script id="playwrightReportBase64" type="application/zip">',wf="</script>";var Ep=require("htmlparser2"),Tp=He(Qf()),be=require("node:fs"),pr=require("node:path"),vp=require("node:os"),Sp=require("node:crypto");var vt=He(require("path")),fo=require("fs");var lo=require("path"),ji=require("fs");function ow(t,e,r=10){let n=t;for(let i=0;i<r;i++){let s=(0,lo.join)(n,"package.json");if((0,ji.existsSync)(s))try{if(JSON.parse((0,ji.readFileSync)(s,"utf8")).name===e)return n}catch{}n=(0,lo.join)(n,"..")}}a(ow,"findRepositoryRoot");function ep(t,e=10){return ow(t,"checksum-customer-engineering-workspace",e)}a(ep,"findCustomerEngineeringRoot");var po=He(no());var Le=a((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 tp(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}a(tp,"resolveMaxRRwebBytes");var cw=__dirname,rp=vt.join(__dirname,".."),ip=(0,fo.existsSync)(rp)?rp:cw;(0,po.config)({path:vt.resolve(ip,".env")});var np=Le(process.env.CHECKSUM_RUNTIME_DEV_MODE);function lw(){let t=__dirname;for(;!(0,fo.existsSync)(vt.join(t,"package.json"));)t=vt.join(t,"..");return t}a(lw,"findRoot");var vn=lw(),uw=ep(vn,10);(0,po.config)({path:[ip,uw].filter(t=>!!t).map(t=>vt.resolve(t,".env")),override:!1});var uo=Le(process.env.CHECKSUM_RUNTIME_REPO_MODE),dw=uo?vt.join(vn,"package","pw-report-template.html"):vt.join(vn,"pw-report-template.html"),fw=Le(process.env.CHECKSUM_DEBUG_ANALYTICS),pw=Le(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),mw=tp(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),Hi={isDevMode:np,isRepoMode:uo,CI:!!process.env.CI,checksumRootFolderBypass:uo&&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??(np?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:vn+"/checksumlib.js"},runtimeRoot:vn,playwrightReporter:{htmlReportTemplatePath:dw},bypassProxyForLocalhost:Le(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Le(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Le(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Le(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Le(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:mw},monitoring:{debugAnalytics:fw,logToConsole:pw,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Le(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Le(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Le(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Le(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Le(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 k5=require("@playwright/test/reporter");var Wr=require("path");var mo=a((t,e,r)=>`v2:${hw(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),hw=a(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var zi=require("fs"),he=He(require("typescript"));var gw=/^[0-9a-zA-Z]+$/,yw=5;function sp(t){return t?t.length===yw&&gw.test(t):!1}a(sp,"isValidChecksumTestId");var ho=class{static{a(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),i=n[n.length-1];if(!i||!i.endsWith(".checksum.spec.ts"))return;let o=i.replace(".checksum.spec.ts","").split(" - ").pop();return sp(o)?o:void 0}},go=class{static{a(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,zi.existsSync)(e)))try{let n=(0,zi.readFileSync)(e,"utf-8"),i=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),s=new Map,o=a(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&&sp(u.checksumTestId)&&s.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,o)},"visit");return o(i),r&&s.has(r)?s.get(r):s.size>0?Array.from(s.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],i=r[1];if(!n||!i)return;let s=this.extractStringLiteral(n),o=this.extractStringLiteral(i);if(s&&o)return{testTitle:s,checksumTestId:o}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},yo=class{static{a(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new go,new ho]}extract(e,r){for(let n of this.strategies){let i=n.extract(e,r);if(i)return i}}};var ap=new yo;function Gi(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?ap.extract(t.filePath,t.title):void 0)}a(Gi,"resolveChecksumTestId");var bo=a((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),_o=a(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function wo(t,e,r){let n=[],i=0,s=0,o=_o(e.expected)+_o(e.flaky),c=_o(e.unexpected);for(let l of t){let u=_w(l,r);n.push(u),u.recovered&&s++,u.bug&&(i++,u.outcome==="expected"||u.outcome==="flaky"?o--:u.outcome==="unexpected"&&c--)}return{passed:o,failed:c,bug:i,recovered:s,tests:n}}a(wo,"computeReportStats");function _w(t,e){let r=Gi({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=bw(t),i=ww(t.annotations),s=bo(t.playwrightTestId,e.playwrightIdToMetadata),o=Ew(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:s,bug:n,annotations:i,tags:t.tags,outcome:t.outcome,variantKey:mo(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}:{},...o!==void 0?{usingChecksumTestIdPlaceholder:o}:{}}}a(_w,"rowToTestWithMetadata");function op(t,e){let r=t.files,n=a(c=>{let u=Gi({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=mo(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),i=new Map;for(let c of r)for(let l of c.tests)i.set(n(l),l);let s=new Set(i.values()),o={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>s.has(l));for(let l of c.tests)o.total++,l.outcome==="expected"?o.expected++:l.outcome==="unexpected"?o.unexpected++:l.outcome==="flaky"?o.flaky++:o.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...o}}a(op,"dedupeReportByChecksumTestId");var bw=a(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),ww=a(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),Ew=a((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var cp=a((t,e,r)=>{if(!t)return;let n=r||e,i;if((0,Wr.isAbsolute)(t))i=t;else{let s=(0,Wr.dirname)(e);i=(0,Wr.resolve)(s,t)}return i.replace(n+"/","")},"toRelativeFilePath");var lp=require("node:util");var qr=8*1024,Sn=`
|
|
158
|
+
\u2026 [truncated]`,Tw=/[\u001b\u0080-\u009f]/g;function Eo(t){let e=t.replaceAll("\0","");return vw((0,lp.stripVTControlCharacters)(e))}a(Eo,"sanitizeTestErrorMessage");function vw(t){return t.replace(Tw,"")}a(vw,"removeResidualVTControls");function Vi(t){let e=Eo(t);if(Buffer.byteLength(e,"utf8")<=qr)return{value:e,truncated:!1};let r=qr-Buffer.byteLength(Sn,"utf8"),n="",i=0;for(let s of e){let o=Buffer.byteLength(s,"utf8");if(i+o>r)break;n+=s,i+=o}return{value:n+Sn,truncated:!0}}a(Vi,"boundTestErrorMessage");var dp=require("node:crypto");var Sw=new Set(["failed","timedOut","interrupted"]),To=new WeakMap;function fp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return To.set(t,new Map),t}a(fp,"createErrorDetailIndex");function pp(t,e){try{let r=xw(t);if(!r||Iw(r.tests))return!1;for(let n of r.tests){if(!Kr(n))continue;let i=_p(n.projectName),s=n.testId;if(i===void 0||!Wi(s))continue;let o=Aw(n);if(!o)continue;let c=Rw(o);c.truncated&&(e.truncatedCount+=1),Mw(e,yp(r.fileId,i,s),c.value,kw(o))}return!0}catch{return!1}}a(pp,"addTestFileErrorDetails");function mp(t){return Kr(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}a(mp,"isTestFileErrorDetailCandidate");function hp(t,e,r,n){let i=_p(r);if(!Wi(e)||i===void 0||!Wi(n))return;let s=yp(e,i,n);if(!t.ambiguousKeys.has(s))return t.messages.get(s)}a(hp,"getTestErrorMessage");function xw(t){if(!Kr(t))return;let e=t.fileId,r=t.tests;if(!(!Wi(e)||!Array.isArray(r)))return{fileId:e,tests:r}}a(xw,"parseTestFile");function Iw(t){return t.length>0&&!t.some(Kr)}a(Iw,"hasOnlyMalformedTests");function Aw(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!Kr(r))return;let n=r.status;if(typeof n!="string"||!Sw.has(n))return;let i=r.errors;if(Array.isArray(i))for(let s of i){let o=Cw(s);if(o)return o}}a(Aw,"extractFinalErrorDetail");function Cw(t){if(typeof t=="string"){let n=gp(t);return n?{message:n}:void 0}if(!Kr(t))return;let e=up(t.message,t.value),r=up(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}a(Cw,"normalizeError");function Rw(t){let{message:e,frame:r}=t;if(!e)return Vi(r??"");if(!r)return Vi(e);let n=Buffer.byteLength(e,"utf8");if(n>qr)return Vi(e);let i=`
|
|
159
|
+
|
|
160
|
+
`,s=Buffer.byteLength(i,"utf8"),o=Buffer.byteLength(r,"utf8");if(n+s+o<=qr)return{value:`${e}${i}${r}`,truncated:!1};let c=s+Buffer.byteLength(Sn,"utf8"),l=qr-n;if(l<c)return{value:e,truncated:!0};let u=Ow(r,l-c);return{value:`${e}${i}${u}${Sn}`,truncated:!0}}a(Rw,"boundNormalizedErrorDetail");function Ow(t,e){let r="",n=0;for(let i of t){let s=Buffer.byteLength(i,"utf8");if(n+s>e)break;r+=i,n+=s}return r}a(Ow,"utf8Prefix");function kw(t){let e=(0,dp.createHash)("sha256");return t.message&&e.update(t.message,"utf8"),t.message&&t.frame&&e.update(`
|
|
161
|
+
|
|
162
|
+
`,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}a(kw,"digestNormalizedErrorDetail");function gp(t){let e=Eo(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,"")}a(gp,"normalizeErrorText");function Mw(t,e,r,n){if(t.ambiguousKeys.has(e))return;let i=To.get(t);if(i||(i=new Map,To.set(t,i)),t.messages.get(e)===void 0){t.messages.set(e,r),i.set(e,n);return}i.get(e)!==n&&(t.messages.delete(e),i.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}a(Mw,"addErrorDetail");function yp(t,e,r){return JSON.stringify([t,e,r])}a(yp,"createIdentityKey");function up(...t){for(let e of t){if(typeof e!="string")continue;let r=gp(e);if(r)return r}}a(up,"firstMeaningfulString");function Kr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(Kr,"isRecord");function _p(t){return t==null||t===""?"":typeof t=="string"?t:void 0}a(_p,"normalizeProjectName");function Wi(t){return typeof t=="string"&&t.length>0}a(Wi,"isNonEmptyString");var Pw=a(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),Nw=a(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function bp(t,e=8388608){let r=Pw(e),n=0,i=t.tests?.map(s=>{if(s.errorMessage===void 0)return s;let o=Nw(s.errorMessage);if(o<=r)return r-=o,s;n+=1;let c={...s};return delete c.errorMessage,c});return{stats:{...t,...i!==void 0?{tests:i}:{}},omittedCount:n}}a(bp,"applyErrorDetailsPayloadBudget");var wp=a(t=>_f.includes(t),"isPayloadTag"),Dw=a((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let i=e?hp(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??[],...i?{errorMessage:i}:{}}})),"htmlReportToRows"),qi=class t{constructor(e,r,n,i={},s={},o,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=i;this.channel=o;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...s},this.checksumRoot=c||(0,pr.dirname)((0,pr.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{a(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,be.statSync)(this.reportHTMLFilePath).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,pr.join)((0,vp.tmpdir)(),`pw-report-${(0,Sp.randomUUID)()}.zip`),n=a(()=>{try{(0,be.existsSync)(r)&&(0,be.unlinkSync)(r)}catch{}},"cleanupFile"),i={sigterm:a(()=>{n(),process.exit(143)},"sigterm"),sigint:a(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",i.sigterm),process.once("SIGINT",i.sigint),process.once("exit",i.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let s=Date.now();await this.extractBase64ToFile(r);let o=Date.now()-s;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:o,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",i.sigterm),process.removeListener("SIGINT",i.sigint),process.removeListener("exit",i.exit);try{(0,be.existsSync)(r)&&(0,be.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let i=!1,s=!1,o=!1,c=[],l=0,u=(0,be.createWriteStream)(e);u.on("error",h=>{if(!s){s=!0;try{y.destroyed||y.destroy(),f.end()}catch{}n(h)}});let d=a(()=>{if(l<4)return;let h=c.join("");c.length=0,o||(h=h.replace("data:application/zip;base64,",""),o=!0);let g=Math.floor(h.length/4)*4,b=h.slice(0,g),w=h.slice(g);if(w.length>0?(c.push(w),l=w.length):l=0,b.length>0){let v=Buffer.from(b,"base64");u.write(v)}},"flushBuffer"),f=new Ep.Parser({onopentag:a((h,g)=>{wp(h)&&g.id==="playwrightReportBase64"&&(i=!0)},"onopentag"),ontext:a(h=>{i&&(c.push(h),l+=h.length,l>1024*1024&&d())},"ontext"),onclosetag:a(h=>{if(wp(h)&&i&&!s){if(s=!0,l>0){let g=c.join("");if(o||(g=g.replace("data:application/zip;base64,","")),g.length>0){let b=Buffer.from(g,"base64");u.write(b)}}try{y.destroyed||y.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:a(h=>{if(!s){s=!0;try{f.end(),y.destroyed||y.destroy(),u.destroyed||u.destroy()}catch{}n(h)}},"onerror")}),y=(0,be.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});y.on("data",h=>f.write(h.toString())),y.on("end",()=>{if(f.end(),!s){s=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),y.on("error",h=>{if(!s){s=!0;try{f.end(),u.destroyed||u.destroy()}catch{}n(h)}})})}modifyZipFile(e){let r=new Tp.default(e),n=r.getEntries(),i=fp(),s,o,c=0,l=0,u=0,d="";for(let y of n){if(y.isDirectory||!y.entryName.endsWith(".json"))continue;let h=y.getData().toString("utf8");if(l+=1,h.length>u&&(u=h.length,d=y.entryName),y.entryName==="report.json")s=JSON.parse(h),o=y;else{let g=this.replaceAttachmentPaths(h);y.setData(Buffer.from(g,"utf8"));try{let b=JSON.parse(g);mp(b)&&!pp(b,i)&&(c+=1)}catch{c+=1}}}if(!s||!o)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&op(s,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(s),this.report=s;let f=this.extractStats(s,i);return o.setData(Buffer.from(JSON.stringify(s),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:i.messages.size,errorDetailsTruncated:i.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:i.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(),i=n.replace(".html",".backup.html");(0,be.copyFileSync)(n,i);let s=(0,be.createWriteStream)(n);await new Promise((o,c)=>{s.on("error",c),s.write(r),s.write(bf+"data:application/zip;base64,");let l=(0,be.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let f=(typeof u=="string"?Buffer.from(u):u).toString("base64");s.write(f)||l.pause()}),s.on("drain",()=>{l.resume()}),l.on("end",()=>{s.write(wf),s.end(()=>o())}),l.on("error",u=>{try{s.destroyed||s.destroy()}catch{}c(u)}),s.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(s=>this.pwTestIdToChecksumTestId[s]===e);if(!n)return!0;let i=a(s=>s.some(o=>o.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let s of this.report.files)for(let o of s.tests)if(o.testId===n&&o.projectName===r&&i(o.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,be.readFileSync)(Hi.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=wo(Dw(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:a(s=>cp(s,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),i=bp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=i.stats,i.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,pr.basename)(e)}`:e}handleReportJSON(e){let r={},n=a(i=>{let s=i.testId,o=this.playwrightIdToMetadata[s];o&&(r[s]=o);let c=Gi({playwrightTestId:i.testId,filePath:i.location.file,title:i.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(i.checksumTestId=c),i.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(i=>{i.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 vo={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},Uw={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},rz=Object.fromEntries(Object.entries(Uw).map(t=>t.reverse())),$w={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"},nz=Object.fromEntries(Object.entries($w).map(t=>t.reverse()));var iz={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]},sz={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 Qi=require("fs"),Hp=require("path"),zp=require("stream");var xp=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 So=require("fs");var Ip="\x1B[31m",Fw="\x1B[33m",Bw="\x1B[32m",jw="\x1B[36m",Hw="\x1B[2m",zw="\x1B[1m",xn="\x1B[0m",Gw=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"),Vw=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Ww=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"),qw=a(t=>t==="ERROR"||t==="CRITICAL"?Ip:t==="WARNING"?Fw:Bw,"colorForSeverity"),Kw=a(t=>{let e=String(t.severity??"INFO"),r=`${qw(e)}${e.padEnd(5)}${xn}`,n=t.kind?`${jw}${t.kind}${xn}`:"",i=String(t.message??""),s=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Ip}${d.type??"Error"}: ${d.message??""}${xn}`})():"",o=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,f])=>!Vw.has(d)&&f!=null&&d!=="error"&&typeof f!="object"),l=a(d=>{let f=o.indexOf(d);return f===-1?o.length:f},"rank"),u=c.sort(([d],[f])=>l(d)-l(f)).slice(0,8).map(([d,f])=>`${Hw}${d}=${xn}${f}`).join(" ");return[r,zw+n+xn,i,u,s].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),Jw=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"),Ap=a(t=>{let e=Gw()?Kw(t):Ww(Jw(t));(0,So.writeSync)(1,e+`
|
|
163
|
+
`)},"emitEvent");var Cp=a(t=>{(0,So.writeSync)(2,t.endsWith(`
|
|
164
|
+
`)?t:`${t}
|
|
165
|
+
`)},"writeStderrLine");var Zw=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"),Yw=a((t,e,r)=>{let n=Date.now(),i={timestamp:new Date().toISOString(),kind:t,...e},s=!1,o={set(c){return Object.assign(i,c),o},emit(c){s||(s=!0,c&&Object.assign(i,c),i.duration_ms===void 0&&(i.duration_ms=Date.now()-n),r(i))}};return o},"startHandle"),Xw=a((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??Zw,n=t.label??"[wide-event]",i=t.sink??(c=>Ap(c)),s=a(c=>{if(!e(c))return;let l={severity:xp(c),message:c.message??r(c),...c};try{i(l)}catch(u){try{Cp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:s,emitWideEvent:a((c,l={})=>{s({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:a((c,l={})=>Yw(c,l,s),"wideEvent"),configureSink:a(c=>{i=c},"configureSink")}},"createWideEvents"),Rp=a(t=>t==="true"||t==="1","truthy"),Op=a(()=>Rp(process.env.CHECKSUM_WIDE_EVENTS)||Rp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),xo=Xw({decide:a(()=>Op(),"decide")}),Io=xo.configureSink,Jr=a((t,e={})=>xo.wideEvent(t,e),"wideEvent"),mr=a((t,e={})=>{xo.emitWideEvent(t,e)},"emitWideEvent"),tt=a(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function kp(t,e){let r;try{r=await t.json()}catch{r=void 0}return Qw({ok:t.ok,status:t.status,body:r},e)}a(kp,"assertOkJson");function Qw(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let i=e0(r?.message);throw t0(new Error(`${e.resource} failed (HTTP ${t.status})`+(i?`: ${i}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(i=>!r[i]);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(Qw,"assertJsonBody");function e0(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}a(e0,"extractMessage");function t0(t,e){return Object.assign(t,{status:e})}a(t0,"withStatus");var Ki=a(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var Ji={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},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},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},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},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 r0(t,e,r,n){if(t===void 0||t.trim()==="")return e;let i=Number(t);return Number.isInteger(i)?Math.min(n,Math.max(r,i)):e}a(r0,"clampEnvInt");var n0=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function i0(t){let e={...t},r=[];for(let[n,i,s]of n0)for(let o of i){let c=Math.floor(e[n]*s);e[o]>c&&(r.push(`${Ji[o].env} (${e[o]}ms) exceeds its bound under ${Ji[n].env} (${e[n]}ms); using ${c}ms`),e[o]=c)}return{tunables:e,warnings:r}}a(i0,"coerceScopeHierarchy");function Ao(t){let e={};for(let r of Object.keys(Ji)){let n=Ji[r];e[r]=r0(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,i0(e)}a(Ao,"resolveUploadTunablesDetailed");function s0(t){return Ao(t).tunables}a(s0,"resolveUploadTunables");var Mp=s0({});var Pp=new WeakMap,Co=new WeakMap;function Np(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,Pp.set(t,t.committedBytes),Co.set(t,0)}a(Np,"beginUpload");function Ro(t){t.loadedBytes=0,Co.set(t,0)}a(Ro,"resetAttemptBytes");var Lp=a(t=>(e,r,n,i)=>{let s=t.get(e)??0;return r-s<n?!1:(e.lastProgress=i,t.set(e,r),!0)},"stamperFor"),a0=Lp(Co),o0=Lp(Pp);function Oo(t,e,r,n){return t.loadedBytes=e,a0(t,e,r,n)}a(Oo,"recordSent");function ko(t,e,r,n){let i=Math.max(t.committedBytes??0,e);return t.committedBytes=i,o0(t,i,r,n)}a(ko,"recordCommitted");var Yi=require("fs"),Up=require("stream");function Zi(t,{baseMs:e,capMs:r,random:n=Math.random}){let i=Math.min(r,e*2**(t-1));return i/2+n()*(i/2)}a(Zi,"jitteredBackoffMs");async function Zr(t){await t.body?.cancel().catch(()=>{})}a(Zr,"drainBody");var No=a(t=>t===200||t===201,"isStored"),$p=a(t=>t===308,"isResumeIncomplete"),c0=a(t=>t===404||t===410,"isSessionGoneStatus"),Fp=a((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),l0=a((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function u0(t,e,r){let n=e,i=new TransformStream({transform(s,o){n+=s.byteLength,r?.(n),o.enqueue(s)}});return Up.Readable.toWeb(t).pipeThrough(i)}a(u0,"countingBody");var rt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{a(this,"ResumableUploadError")}},Bp=a(t=>t instanceof rt?t.status:void 0,"statusOf"),d0=a(t=>{let e=Bp(t);return e!==void 0&&c0(e)},"isSessionGone"),f0=a(t=>Ki(Bp(t)),"isPermanent");async function p0(t,e,r,n){let i=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await Zr(i),!No(i.status))throw new rt(`resumable init failed with status ${i.status}`,i.status);let s=i.headers.get("Location");if(!s)throw new rt("resumable init returned no Location");return s}a(p0,"initResumableSession");async function m0(t,e,r,n){let i=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await Zr(i),No(i.status))return{done:!0,offset:e};if(!$p(i.status))throw new rt(`offset query failed with status ${i.status}`,i.status);return{done:!1,offset:Fp(i.headers.get("Range"),0)}}a(m0,"queryCommittedOffset");async function Dp(t,e,{offset:r,endExclusive:n},i){let s=Math.max(0,(0,Yi.statSync)(t.filePath).size-r),o=Math.min(Math.max(0,n-r),s),c=r+o,l=o>0?(0,Yi.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":l0(r,c,t.size),"Content-Length":String(o)},duplex:"half",signal:i,...l?{body:u0(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await Zr(d),No(d.status))return{stored:!0,committed:t.size};if($p(d.status))return{stored:!1,committed:Fp(d.headers.get("Range"),r)};throw new rt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}a(Dp,"putChunk");async function h0(t,e,r,n){let i=r;for(;i<t.size;){let o=Math.min(i+t.chunkSizeBytes,t.size),{stored:c,committed:l}=await Dp(t,e,{offset:i,endExclusive:o},n);if(c){t.onCommitted?.(t.size);return}if(l<=i)throw new rt("resumable PUT made no forward progress");i=l,t.onCommitted?.(i)}let{stored:s}=await Dp(t,e,{offset:t.size,endExclusive:t.size},n);if(!s)throw new rt("resumable upload did not finalize");t.onCommitted?.(t.size)}a(h0,"sendFrom");async function g0(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new rt("no resumable target provided");return e.url=await p0(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}a(g0,"openSession");async function y0(t,e,r,n){if(!r)return 0;let i=await m0(e,t.size,t.fetchImpl,n);if(!i.done)return t.onCommitted?.(i.offset),i.offset}a(y0,"resumePoint");async function _0(t,e,r){let n=await g0(t,e,r),i=await y0(t,n,e.used,r);if(e.used=!0,i===void 0){t.onCommitted?.(t.size);return}await h0(t,n,i,r)}a(_0,"runAttempt");function b0(t,e,r){return d0(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):f0(t)?"stop":"retry"}a(b0,"afterFailure");async function jp(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await _0(t,e,t.makeSignal());return}catch(i){if(r=i,b0(i,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(Zi(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new rt(`resumable upload failed: ${String(r)}`)}a(jp,"uploadResumable");var w0=a(t=>{if(typeof t!="object"||t===null)return"network_error";let e="name"in t&&typeof t.name=="string"?t.name:"";if(e==="TimeoutError")return"timeout";if(e==="AbortError")return"no_progress_abort";let r="cause"in t?t.cause:void 0,n=typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:void 0;if(n==="UND_ERR_CONNECT_TIMEOUT"||n==="UND_ERR_HEADERS_TIMEOUT"||n==="UND_ERR_BODY_TIMEOUT")return"timeout";if(n!==void 0&&n.length>0)return`network_error:${n}`;let i="message"in t&&typeof t.message=="string"?t.message:"";return i.startsWith("Upload failed with status")?"http_error":i.startsWith("get-upload-url")?"signed_url_error":i.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),E0=a(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),Xi=class{constructor(e,r,n,i,s=!1,o={start:a(u=>{},"start"),complete:a(u=>{},"complete"),error:a((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=i;this.isolationMode=s;this.reporter=o;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=l.tunables??Mp,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{a(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(o=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,o({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,i=Jr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,Hp.basename)(r),test_id:e.info.testId,project:e.info.project}),s=[];try{let c=(0,Qi.statSync)(r).size;e.sizeBytes=c,Np(e,this.now()),i.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 y=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()-y,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,s.push(d),this.reporter.complete(r),e.complete=!0,i.emit({outcome:"success",attempt_count:s.length,attempts:s,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=w0(f),d.error=tt(f);let y=Ki(typeof f=="object"&&f!==null&&"status"in f?f.status:void 0);d.non_retryable=y,delete e.uploadURL;let h=y?"non_retryable":e.resumable?"resumable_owns_retries":u>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(d.retry_stop_reason=h,s.push(d),h)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,i.emit({outcome:"error",attempt_count:s.length,attempts:s,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:tt(l)})}catch(o){this.reporter.error(r,o),e.error=!0,i.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:s.length,attempts:s,error:tt(o)})}}async putWithWatchdog(e,r,n){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");let s=new AbortController,o=this.uploadTimeout??void 0;Ro(e);let c=this.armNoProgressWatchdog(e,()=>s.abort()),l=o!==void 0?setTimeout(()=>s.abort(new DOMException("upload attempt timeout","TimeoutError")),o):void 0,u=(0,Qi.createReadStream)(r),d=0,f=this.MIN_PROGRESS_BYTES,y=this.now,h=new TransformStream({transform(w,v){d+=w.byteLength,e.sizeBytes=n,Oo(e,d,f,y()),v.enqueue(w)}}),g=zp.Readable.toWeb(u).pipeThrough(h),b={method:"PUT",headers:{"Content-Type":vo[e.info.type]??""},body:g,duplex:"half",signal:s.signal};try{let w=await this.fetchImpl(i,b);if(!w.ok)throw await Zr(w),Object.assign(new Error(`Upload failed with status ${w.status}`),{status:w.status});ko(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await w.text())}finally{clearInterval(c),clearTimeout(l),u.destroy()}}armNoProgressWatchdog(e,r){let n=-1,i=this.now();return setInterval(()=>{let s=Math.max(e.loadedBytes??0,e.committedBytes??0);s>n?(n=s,i=this.now()):this.now()-i>this.PUT_NO_PROGRESS_ABORT_MS&&r()},E0(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(e,r,n,i){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");Ro(e);let o=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,l,u=a(()=>(clearInterval(l),c=new AbortController,l=this.armNoProgressWatchdog(e,()=>c?.abort()),c.signal),"armAttempt");try{await jp({target:{initUrl:s},filePath:r,size:n,contentType:vo[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:a(()=>AbortSignal.any([u(),AbortSignal.timeout(o)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:i,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:a(d=>new Promise(f=>setTimeout(f,d)),"sleep"),onSent:a(d=>Oo(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:a(d=>ko(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(l)}e.response=Promise.resolve("OK")}async backoff(e,r){let n=Zi(e,{baseMs:1e3,capMs:16e3}),i=Math.max(0,Math.min(n,r-this.now()));i>0&&await new Promise(s=>setTimeout(s,i))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let i=JSON.stringify(e.info),s=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,o={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(s,{method:"POST",headers:o,body:i,signal:r.signal}),{url:l,resumable:u}=await kp(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(i){throw delete e.uploadURL,i}finally{clearTimeout(n)}}};function es(t,e,r=Date.now()){let n=t.filter(s=>!s.complete&&!s.error);if(n.length===0)return!1;let i=n.reduce((s,o)=>Math.max(s,o.lastProgress??0),0);return i>0&&r-i>e}a(es,"isUploadStalled");function ts(t,e,r){return t!==void 0&&r-t>e}a(ts,"hasElapsedSinceTestEnd");function Gp(t,e,r){return ts(e.testRunEndTime,e.finalizeBudgetMs,r)?!0:t===void 0?!1:t.complete||t.error?!0:es([t],e.stallTimeoutMs,r)}a(Gp,"shouldStopWaitingForReport");function Vp(t){return t.abandonedAssets.length===0}a(Vp,"mayCleanUpSources");function T0(t,e,r){if((e.length===0||es(t.assets,t.stallTimeoutMs,r))&&ts(t.testRunEndTime,t.finalizeBudgetMs,r))return"budget";if(ts(t.testRunEndTime,t.finalizeCeilingMs,r))return"budget-ceiling"}a(T0,"backstopReason");function Wp(t,e){let r=t.assets.filter(s=>!s.complete&&!s.error),n=a(s=>({reason:s,abandonedAssets:r}),"decide"),i=T0(t,r,e);if(i!==void 0)return n(i);if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!es(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!ts(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}a(Wp,"decideFinalize");var qp=require("module");var v0=(0,qp.createRequire)(__filename);function Kp(t){let e,r;try{e=v0("undici"),r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4})}catch(i){return mr("monitor_dispatcher_unavailable",{outcome:"error",error:tt(i)}),process.emitWarning("@checksum-ai/runtime: undici dispatcher unavailable; upload timeouts fall back to the platform defaults",{detail:String(i)}),globalThis.fetch}let n=e.fetch;return(i,s)=>{let o={...s,dispatcher:r};return n(i,o)}}a(Kp,"createMonitorFetch");var Lo=class{static{a(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
|
|
166
|
+
`)}{/trm}`;process.stdout.write(`${r}
|
|
167
|
+
`)}event(e,r){return new Promise(n=>{let i=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${i}`),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}`)}},rs=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunablesResolution=Ao(process.env);this.tunables=this.tunablesResolution.tunables;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=this.tunables.watchTimeoutMs;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.FINALIZE_CEILING=this.tunables.finalizeCeilingMs;this.SHUTDOWN_FLUSH_TIMEOUT=2e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.doneWaitingForReport=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Lo,Io(n=>this.channel.wideEvent(n)),this.testAssetUploader=new Xi(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,ce.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(i){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,i)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:a((n,i)=>this.channel.trace("Upload Failed",{filename:n,error:i}),"error")},e.sessionId,{fetchImpl:Kp(this.tunables),tunables:this.tunables}),this.uploadMonitorInterval=setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL);for(let n of this.tunablesResolution.warnings)this.channel.debug(`[upload-tunables] ${n}`),mr("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{a(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,i]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+i),n){case"report":if(this.testRunEndTime=Date.now(),i!=="false")try{let s=Buffer.from(i??"","base64").toString("utf-8"),o=JSON.parse(s);await this.handleReport(o)}catch(s){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(s)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,Zp.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,Be.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=Hi.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,Jp.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:i,openReportCriteria:s,checksumRoot:o,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,Be.dirname)(r),l);let d=Jr("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),y=new qi(r,this.config.sessionId,this.pwTestIdToChecksumTestId,f,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,o,c,this.checksumTestIdToUsingPlaceholder),h=this.initAsset({type:"report",path:""});this.reportAsset=h;try{let w=await y.process();h.info.path=y.getProcessedFilePath(),d.set({processed_path:h.info.path,...w}),this.uploadAsset(h)}catch(w){this.channel.debug("Error processing report, "+w.message),h.error=!0,d.set({error:tt(w)})}let g=y.getReportsStats();this.stats=g,yf(d,h.error?"error":"success",g),this.channel.debug("Checking watch assets");let b=this.watchAssets.filter(w=>!(w.type!=="trace"||y.testHasTrace(w.testId??"",w.project??"")));b.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(b.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||y.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:tt(f)})}finally{if((s==="always"||s==="on-failure"&&i)&&await this.serveReport(r),n&&(0,ce.existsSync)(n))try{(0,ce.unlinkSync)(n)}catch(y){console.error(`Error deleting checksum metadata file ${n}: ${y.message}`)}}}async uploadReportData(e,r){let n=(0,Be.join)(e,"data");try{let i=(0,ce.readdirSync)(n),s=r?[".webm"]:[".zip",".webm"],o=i.filter(c=>!s.includes((0,Be.extname)(c)));this.channel.debug("Preparing to upload report data files,"+o);for(let c of o)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(i){this.channel.debug(`Error reading/adding report data files from dir ${n}`+i.message)}}shutdown(){clearInterval(this.uploadMonitorInterval);try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}this.channel.debug("Received shutdown message from CLI"),process.stdout.write("",()=>process.exit(0)),setTimeout(()=>process.exit(0),this.SHUTDOWN_FLUSH_TIMEOUT).unref()}async monitorUploadsCompletion(){let e=Date.now();!this.doneWaitingForReport&&Gp(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e)&&this.settleReport();let r=Wp({assets:this.assets,processingInProgress:this.processingInProgress,doneWaitingForReport:this.doneWaitingForReport,pendingWatchCount:this.watchAssets.length,testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,watchTimeoutMs:this.WATCH_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET,finalizeCeilingMs:this.FINALIZE_CEILING},e);if(!r){await os(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,e)}stopWaitingForReport(e){this.doneWaitingForReport=!0,this.reportOutcome=e}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let e="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,In.randomBytes)(8).toString("hex")}.json`;e=(0,Be.join)((0,em.tmpdir)(),n),(0,ce.writeFileSync)(e,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${e}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportOutcome==="uploaded"?"true":"false"}:${e}`)}finalizeRun(e,r){e.reason==="stall"&&this.emitStallDetected(e.abandonedAssets,r),e.abandonedAssets.forEach(o=>{o.error=!0});let n=this.assets.some(o=>o.error)?"uploads-complete-with-errors":"uploads-complete",i=this.assets.filter(o=>o.error);mr("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:i.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(o=>o.complete).length,errored:i.length,stalled:e.abandonedAssets.length>0,stalled_count:e.abandonedAssets.length,finalize_reason:e.reason,finalize_budget_ms:this.FINALIZE_BUDGET,finalize_ceiling_ms:this.FINALIZE_CEILING,watch_remaining:this.watchAssets.length,report_outcome:this.reportOutcome,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:i.map(o=>this.assetSnapshot(o,r))});let s=n==="uploads-complete"?{}:{uploadErrors:i.map(o=>{try{return JSON.stringify(o)}catch{return o.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r,finalizeReason:e.reason,abandonedAssets:e.abandonedAssets.map(o=>this.assetSnapshot(o,r))};if(Vp(e))try{this.cleanUp()}catch(o){this.channel.debug("cleanUp failed (ignored): "+o?.message)}else this.channel.debug(`skipping cleanUp: ${e.abandonedAssets.length} asset(s) abandoned (${e.reason})`);this.channel.event(n,JSON.stringify(s))}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,Be.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,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,Be.dirname)(r.info.path);break}e&&(0,ce.rmSync)(e,{recursive:!0,force:!0})}emitStallDetected(e,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,mr("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:e.length,pending_assets:e.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,Xp.createServer)((r,n)=>{let i=a(o=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(o)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let s="";r.on("data",o=>{s+=o.toString()}),r.on("end",()=>{let o;try{o=JSON.parse(s)}catch{i("Invalid body");return}let{type:c,payload:l,watch:u}=o;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){i("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){i("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){i("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:i("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(i){this.channel.debug("Failed to send run progress: "+i?.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 s=(r/e*100).toFixed(2);this.channel.event("upload-progress",s)}let n=this.assets.filter(s=>!s.uploadStarted);if(n.length===0)return;let i=a(()=>this.assets.filter(s=>s.uploadStarted&&!s.complete&&!s.error).length,"getNumOfActiveUploads");if(!(i()>=this.MAX_UPLOADS))for(;n.length>0&&i()<this.MAX_UPLOADS;){let s=n.pop();if(s===void 0)break;this.uploadAsset(s)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:i})=>n+(i??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:i})=>n+(i??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)})}}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(i=>i.path!==e.path))},"waitForCompletion");if((0,ce.existsSync)(e.path))r();else{let n=(0,Be.dirname)(e.path),i=(0,Be.basename)(e.path),s=!1,o=(0,ce.watch)(n,(c,l)=>{(async()=>{if(!(l!==i||s))try{this.channel.debug("Watched file changed "+e.path),s=!0,await r()}finally{o.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,i=1){return new Promise(s=>{let o=Date.now(),c=0,l=i,u=a(()=>{if(!(0,ce.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),s(!1);return}let d=(0,ce.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}`),s(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-o>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),s(!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,In.createHash)("sha1"),n=(0,ce.createReadStream)(e);return await(0,Yp.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 os(1e3),n=Jr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let i=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),i=e.replace(".zip",".actual.zip"),(0,ce.renameSync)(e,i);let c="checksum-playwright-trace:"+Date.now().toString()+(0,In.randomBytes)(1024).toString("hex");(0,ce.writeFileSync)(e,c)}let o=await a(async()=>await this.calculateFileSha1Streaming(e)+(0,Be.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${o}, sending for upload...`),this.addAsset({type:"report-data-file",path:i,...r!==void 0?{testId:r}:{},fileName:o}),n.emit({outcome:"success",file_name:o})}catch(i){let s=String(i);this.channel.debug("Error processing trace file"+s),this.channel.trace("Trace Processing Error",{error:s}),n?.emit({outcome:"error",error:tt(i)})}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=Qp.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let i=n.address().port;n.close(()=>{e(i)})})})}},tm;try{tm=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new rs(tm,process.argv[3]==="isolated");0&&(module.exports={TestRunMonitor});
|
|
168
|
+
/*! Bundled license information:
|
|
169
|
+
|
|
170
|
+
@langchain/core/dist/utils/js-sha256/hash.js:
|
|
171
|
+
(**
|
|
172
|
+
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
173
|
+
*
|
|
174
|
+
* @version 0.11.1
|
|
175
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
176
|
+
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
177
|
+
* @license MIT
|
|
178
|
+
*)
|
|
179
|
+
|
|
180
|
+
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
|
|
181
|
+
(*!
|
|
182
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
183
|
+
* (c) 2017-2022 Joachim Wester
|
|
184
|
+
* MIT licensed
|
|
185
|
+
*)
|
|
186
|
+
|
|
187
|
+
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
|
|
188
|
+
(*!
|
|
189
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
190
|
+
* (c) 2013-2021 Joachim Wester
|
|
191
|
+
* MIT license
|
|
192
|
+
*)
|
|
193
|
+
|
|
194
|
+
@langchain/core/dist/utils/sax-js/sax.js:
|
|
195
|
+
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
|
|
196
|
+
*/
|