@checksum-ai/runtime 4.16.7 → 4.17.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/checksum-progress-reporter.js +6 -189
- package/checksumlib.js +29 -29
- package/cli.js +172 -373
- package/index.js +101 -311
- package/package.json +1 -1
- package/pw-report-template.html +32 -33
- package/test-run-monitor.js +10 -193
package/test-run-monitor.js
CHANGED
|
@@ -1,196 +1,13 @@
|
|
|
1
|
-
"use strict";var lm=Object.create;var Xr=Object.defineProperty;var um=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var fm=Object.getPrototypeOf,pm=Object.prototype.hasOwnProperty;var a=(t,e)=>Xr(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}},mm=(t,e)=>{for(var r in e)Xr(t,r,{get:e[r],enumerable:!0})},jo=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dm(e))!pm.call(t,i)&&i!==r&&Xr(t,i,{get:()=>e[i],enumerable:!(n=um(e,i))||n.enumerable});return t};var He=(t,e,r)=>(r=t!=null?lm(fm(t)):{},jo(e||!t||!t.__esModule?Xr(r,"default",{value:t,enumerable:!0}):r,t)),hm=t=>jo(Xr({},"__esModule",{value:!0}),t);var Fc=re((fS,ys)=>{"use strict";var eh=Object.prototype.hasOwnProperty,ke="~";function en(){}a(en,"Events");Object.create&&(en.prototype=Object.create(null),new en().__proto__||(ke=!1));function th(t,e,r){this.fn=t,this.context=e,this.once=r||!1}a(th,"EE");function $c(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new th(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($c,"addListener");function Fn(t,e){--t._eventsCount===0?t._events=new en:delete t._events[e]}a(Fn,"clearEvent");function Ie(){this._events=new en,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)eh.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 $c(this,e,r,n,!1)},"on");Ie.prototype.once=a(function(e,r,n){return $c(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 Fn(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&Fn(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:Fn(this,s)}return this},"removeListener");Ie.prototype.removeAllListeners=a(function(e){var r;return e?(r=ke?ke+e:e,this._events[r]&&Fn(this,r)):(this._events=new en,this._eventsCount=0),this},"removeAllListeners");Ie.prototype.off=Ie.prototype.removeListener;Ie.prototype.addListener=Ie.prototype.on;Ie.prefixed=ke;Ie.EventEmitter=Ie;typeof ys<"u"&&(ys.exports=Ie)});var jc=re((mS,Bc)=>{"use strict";Bc.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 zc=re((hS,jn)=>{"use strict";var rh=jc(),Bn=class extends Error{static{a(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},Hc=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 Bn(o);typeof t.cancel=="function"&&t.cancel(),i(c)},e);rh(t.then(n,i),()=>{clearTimeout(s)})}),"pTimeout");jn.exports=Hc;jn.exports.default=Hc;jn.exports.TimeoutError=Bn});var Gc=re(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});function nh(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(nh,"lowerBound");_s.default=nh});var Vc=re(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var ih=Gc(),bs=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=ih.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}};ws.default=bs});var zn=re(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var sh=Fc(),Wc=zc(),ah=Vc(),Hn=a(()=>{},"empty"),oh=new Wc.TimeoutError,Es=class extends sh{static{a(this,"PQueue")}constructor(e){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Hn,this._resolveIdle=Hn,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:ah.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=Hn,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Hn,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():Wc.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(oh)});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}};Ts.default=Es});var Xd=re(Li=>{"use strict";Li.byteLength=X_;Li.toByteArray=eb;Li.fromByteArray=nb;var mt=[],Ke=[],Y_=typeof Uint8Array<"u"?Uint8Array:Array,Za="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(dr=0,Zd=Za.length;dr<Zd;++dr)mt[dr]=Za[dr],Ke[Za.charCodeAt(dr)]=dr;var dr,Zd;Ke[45]=62;Ke[95]=63;function Yd(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(Yd,"getLens");function X_(t){var e=Yd(t),r=e[0],n=e[1];return(r+n)*3/4-n}a(X_,"byteLength");function Q_(t,e,r){return(e+r)*3/4-r}a(Q_,"_byteLength");function eb(t){var e,r=Yd(t),n=r[0],i=r[1],s=new Y_(Q_(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(eb,"toByteArray");function tb(t){return mt[t>>18&63]+mt[t>>12&63]+mt[t>>6&63]+mt[t&63]}a(tb,"tripletToBase64");function rb(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(tb(n));return i.join("")}a(rb,"encodeChunk");function nb(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,c=r-n;o<c;o+=s)i.push(rb(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(nb,"fromByteArray")});var io=re((o3,Tt)=>{var no=require("fs"),Ui=require("path"),Ab=require("os"),Cb=require("crypto"),ff=["\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 Rb(){return ff[Math.floor(Math.random()*ff.length)]}a(Rb,"_getRandomTip");function zr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}a(zr,"parseBoolean");function Ob(){return process.stdout.isTTY}a(Ob,"supportsAnsi");function kb(t){return Ob()?`\x1B[2m${t}\x1B[0m`:t}a(kb,"dim");var Mb=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Pb(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
-
`);let n;for(;(n=
|
|
3
|
-
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}a(Pb,"parse");function Nb(t){t=t||{};let e=gf(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=hf(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let c=n[o].trim(),l=Db(r,c);s=me.decrypt(l.ciphertext,l.key);break}catch(c){if(o+1>=i)throw c}return me.parse(s)}a(Nb,"_parseVault");function Lb(t){console.error(`\u26A0 ${t}`)}a(Lb,"_warn");function Tn(t){console.log(`\u2506 ${t}`)}a(Tn,"_debug");function mf(t){console.log(`\u25C7 ${t}`)}a(mf,"_log");function hf(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(hf,"_dotenvKey");function Db(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(Db,"_instructions");function gf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)no.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=Ui.resolve(process.cwd(),".env.vault");return no.existsSync(e)?e:null}a(gf,"_vaultPath");function pf(t){return t[0]==="~"?Ui.join(Ab.homedir(),t.slice(1)):t}a(pf,"_resolveHome");function Ub(t){let e=zr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=zr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&mf("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(Ub,"_configVault");function $b(t){let e=Ui.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&&Tn("no encoding is specified (UTF-8 is used by default)");let o=[e];if(t&&t.path)if(!Array.isArray(t.path))o=[pf(t.path)];else{o=[];for(let d of t.path)o.push(pf(d))}let c,l={};for(let d of o)try{let f=me.parse(no.readFileSync(d,{encoding:r}));me.populate(l,f,t)}catch(f){i&&Tn(`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=Ui.relative(process.cwd(),y);f.push(h)}catch(h){i&&Tn(`failed to load ${y} ${h.message}`),c=h}mf(`injected env (${d}) from ${f.join(",")} ${kb(`// tip: ${Rb()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}a($b,"configDotenv");function Fb(t){if(hf(t).length===0)return me.configDotenv(t);let e=gf(t);return e?me._configVault(t):(Lb(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}a(Fb,"config");function Bb(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=Cb.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(Bb,"decrypt");function jb(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&&Tn(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(jb,"populate");var me={configDotenv:$b,_configVault:Ub,_parseVault:Nb,config:Fb,decrypt:Bb,parse:Pb,populate:jb};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 so=re((D3,Tf)=>{Tf.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 $i=re(Sf=>{var vf={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 Wb(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}a(Wb,"E");for(let t of Object.keys(vf))Sf[t]=Wb(vf[t])});var Rf=re((F3,Cf)=>{var qb=require("fs"),de=require("path"),xf=so(),Kb=$i(),Jb=typeof process=="object"&&process.platform==="win32",If=a(t=>typeof t=="object"&&t!==null,"is_Obj"),Af=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=qb,If(t)&&If(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}a(ie,"Utils");Cf.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 Kb.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 Af[(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 xf.STORED:return"STORED ("+t+")";case xf.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=Jb;ie.crcTable=Af});var kf=re((j3,Of)=>{var Zb=require("path");Of.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=Zb.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 Pf=re((z3,Mf)=>{Mf.exports={efs:!0,encode:a(t=>Buffer.from(t,"utf8"),"encode"),decode:a(t=>t.toString("utf8"),"decode")}});var Vr=re((V3,Gr)=>{Gr.exports=Rf();Gr.exports.Constants=so();Gr.exports.Errors=$i();Gr.exports.FileAttr=kf();Gr.exports.decoder=Pf()});var Lf=re((W3,Nf)=>{var Dt=Vr(),M=Dt.Constants;Nf.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 Uf=re((K3,Df)=>{var Je=Vr(),j=Je.Constants;Df.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 oo=re(ao=>{ao.EntryHeader=Lf();ao.MainHeader=Uf()});var Ff=re((Y3,$f)=>{$f.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 jf=re((Q3,Bf)=>{var Yb=+(process?.versions?.node??"").split(".")[0]||0;Bf.exports=function(t,e){var r=require("zlib");let n=Yb>=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 Wf=re((t5,Vf)=>{"use strict";var{randomFillSync:Hf}=require("crypto"),Xb=$i(),Qb=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}),Gf=a((t,e)=>Math.imul(t,e)>>>0,"uMul"),zf=a((t,e)=>Qb[(t^e)&255]^t>>>8,"crc32update"),vn=a(()=>typeof Hf=="function"?Hf(Buffer.alloc(12)):vn.node(),"genSalt");vn.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 Fi={genSalt:vn};function Bi(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(Bi,"Initkeys");Bi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=zf(e[0],t),e[1]+=e[0]&255,e[1]=Gf(e[1],134775813)+1,e[2]=zf(e[2],e[1]>>>24),t};Bi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Gf(t,t^1)>>8&255};function ew(t){let e=new Bi(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(ew,"make_decrypter");function tw(t){let e=new Bi(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(tw,"make_encrypter");function rw(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=ew(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw Xb.WRONG_PASSWORD();return n(t.slice(12))}a(rw,"decrypt");function nw(t){Buffer.isBuffer(t)&&t.length>=12?Fi.genSalt=function(){return t.slice(0,12)}:t==="node"?Fi.genSalt=vn.node:Fi.genSalt=vn}a(nw,"_salter");function iw(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=tw(r),s=Fi.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(iw,"encrypt");Vf.exports={decrypt:rw,encrypt:iw,_salter:nw}});var qf=re(ji=>{ji.Deflater=Ff();ji.Inflater=jf();ji.ZipCrypto=Wf()});var lo=re((i5,Kf)=>{var X=Vr(),sw=oo(),Ve=X.Constants,co=qf();Kf.exports=function(t,e){var r=new sw.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=co.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 co.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 co.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 Yf=re((a5,Zf)=>{var Jf=lo(),aw=oo(),Ne=Vr();Zf.exports=function(t,e){var r=[],n=Object.create(null),i=Buffer.alloc(0),s=new aw.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 Jf(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 Jf(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 ep=re((c5,Qf)=>{var oe=Vr(),ae=require("path"),ow=lo(),cw=Yf(),fr=a((...t)=>oe.findLast(t,e=>typeof e=="boolean"),"get_Bool"),Xf=a((...t)=>oe.findLast(t,e=>typeof e=="string"),"get_Str"),lw=a((...t)=>oe.findLast(t,e=>typeof e=="function"),"get_Fun"),uw={noSort:!1,readEntries:!1,method:oe.Constants.NONE,fs:null};Qf.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),uw);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 cw(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 ow(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=Xf(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=Xf(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=lw(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 k0={};mm(k0,{TestRunMonitor:()=>ns});module.exports=hm(k0);var cs=a(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");function Ho(t=5,e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let r="";for(let n=t;n>0;--n)r+=e[Math.floor(Math.random()*e.length)]??"";return r}a(Ho,"randomString");var T3=require("@playwright/test");var G6=require("@playwright/test");var mE=require("@playwright/test");var uE=require("@playwright/test");var zo=Object.defineProperty,V=a((t,e)=>{let r={};for(var n in t)zo(r,n,{get:t[n],enumerable:!0});return e||zo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function Go(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 Go(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}a(Go,"createNamespace");var Vo=Go("langchain");var ls=Vo.sub("error"),Wo=class extends ls.brand(Error){static{a(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},ym=class extends ls.brand(Wo,"model-abort"){static{a(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},SE=class qo extends ls.brand(Wo,"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 qo(e.message);return r.cause=e,r}};var _m=/([A-Z]+)([A-Z][a-z0-9]+)/g,bm=/([a-z0-9])([A-Z])/g,wm=/[-_\s]+/g;function Em(t){return t.replace(_m,"$1_$2").replace(bm,"$1_$2").replace(wm,"_").toLowerCase()}a(Em,"snakeCase");function Ko(t,e){return e?.[t]||Em(t)}a(Ko,"keyToJson");function Jo(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}a(Jo,"mapKeys");var Tm="__lc_escaped__";function vm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}a(vm,"needsEscaping");function Sm(t){return{[Tm]:t}}a(Sm,"escapeObject");function xm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}a(xm,"isSerializableLike");function Im(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(Im,"createNotImplemented");function Cn(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Im(t);if(xm(t))return t;e.add(t);let r=t;if(vm(r))return e.delete(t),Sm(r);let n={};for(let[i,s]of Object.entries(r))n[i]=Cn(s,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Cn(r,e)):t}a(Cn,"escapeIfNeeded");function Zo(t){return Array.isArray(t)?[...t]:{...t}}a(Zo,"shallowCopy");function Am(t,e){let r=Zo(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]=Zo(c[l]),c=c[l]}c[s]!==void 0&&(c[s]={lc:1,type:"secret",id:[i]})}return r}a(Am,"replaceSecrets");function us(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(us,"get_lc_unique_name");var Bt=class Yo{static{a(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,us(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 Yo||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]=Cn(l,s);let o=Jo(Object.keys(r).length?Am(i,r):i,Ko,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Qr(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(Qr,"isDataContentBlock");function Rn(t){return Qr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}a(Rn,"isURLContentBlock");function On(t){return Qr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}a(On,"isBase64ContentBlock");function ds(t){return Qr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}a(ds,"isIDContentBlock");function kn({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(kn,"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 Mn(t){return t instanceof Uint8Array}a(Mn,"_isBytesArray");function fs(t){try{return JSON.parse(t)}catch{return}}a(fs,"safeParseJson");var Ge=a(t=>t(),"iife");function Cm(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(Cm,"convertAnthropicAnnotation");function Qo(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(Qo,"convertToV1FromAnthropicContentBlock");function ec(t){function*e(){for(let r of t){let n=Qo(r);n?yield n:yield r}}return a(e,"iterateContent"),Array.from(e())}a(ec,"convertToV1FromAnthropicInput");function Xo(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=Cm(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(Rm(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=fs(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=fs(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=Qo(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(Xo,"convertToV1FromAnthropicMessage");var tc={translateContent:Xo,translateContentChunk:Xo};function Rm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}a(Rm,"_isAIMessageChunk");function Om(t){return Rn(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:On(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ds(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}a(Om,"convertToV1FromDataContentBlock");function rc(t){return t.map(Om)}a(rc,"convertToV1FromDataContent");function nc(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(nc,"isOpenAIDataBlock");function ic(t){if(P(t,"image_url")&&B(t.image_url)&&A(t.image_url.url)){let e=kn({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=kn({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(ic,"convertToV1FromOpenAIDataBlock");function km(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Pn(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(km,"convertToV1FromChatCompletions");function Mm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Pn(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(Mm,"convertToV1FromChatCompletionsChunk");function Pn(t){let e=[];for(let r of t)nc(r)?e.push(ic(r)):e.push(r);return e}a(Pn,"convertToV1FromChatCompletionsInput");function Pm(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(Pm,"convertResponsesAnnotation");function sc(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(Pm)}: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(sc,"convertToV1FromResponses");function Nm(t){function*e(){yield*sc(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(Nm,"convertToV1FromResponsesChunk");var ac={translateContent:a(t=>typeof t.content=="string"?km(t):sc(t),"translateContent"),translateContentChunk:a(t=>typeof t.content=="string"?Mm(t):Nm(t),"translateContentChunk")};function ps(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}a(ps,"isMessage");function oc(t,e="pretty"){return e==="pretty"?Lm(t):JSON.stringify(t)}a(oc,"convertToFormattedString");function Lm(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(Lm,"convertToPrettyString");var ms=Symbol.for("langchain.message");function Dm(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(Dm,"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"}}[ms]=!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[rc,Pn,ec].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&&ms in t&&t[ms]===!0&&ps(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=Dm(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return oc(this,t)}};function hs(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(hs,"defaultToolCallParser");function gs(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(gs,"convertFileFormatToMimeType");function Fm(t){if(B(t.document)&&B(t.document.source)){let e=gs(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(Mn(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(Fm,"convertConverseDocumentBlock");function Bm(t){if(P(t,"image")&&B(t.image)){let e=gs(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(Mn(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}a(Bm,"convertConverseImageBlock");function jm(t){if(P(t,"video")&&B(t.video)){let e=gs(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(Mn(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}a(jm,"convertConverseVideoBlock");function cc(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 Fm(n);continue}else if(P(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(P(n,"image")&&B(n.image)){yield Bm(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 jm(n);continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(cc,"convertToV1FromChatBedrockConverseMessage");var lc={translateContent:cc,translateContentChunk:cc};function uc(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(uc,"convertToV1FromDeepSeekMessage");var dc={translateContent:uc,translateContentChunk:uc};function fc(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(fc,"convertToV1FromChatGoogleMessage");var pc={translateContent:fc,translateContentChunk:fc};function mc(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(mc,"convertToV1FromChatVertexMessage");var hc={translateContent:mc,translateContentChunk:mc};function gc(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(gc,"convertToV1FromGroqMessage");var yc={translateContent:gc,translateContentChunk:gc};function _c(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(_c,"convertToV1FromOllamaMessage");var bc={translateContent:_c,translateContentChunk:_c};function wc(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(wc,"convertToV1FromOpenRouterMessage");var Ec={translateContent:wc,translateContentChunk:wc};function Tc(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(Tc,"convertToV1FromXAIMessage");var vc={translateContent:Tc,translateContentChunk:Tc};function Sc(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(Sc,"convertToV1FromChatGoogleMessage");var xc={translateContent:Sc,translateContentChunk:Sc};globalThis.lc_block_translators_registry??=new Map([["anthropic",tc],["bedrock-converse",lc],["deepseek",dc],["google",xc],["google-genai",pc],["google-vertexai",hc],["groq",yc],["ollama",bc],["openai",ac],["openrouter",Ec],["xai",vc]]);function Ic(t){return globalThis.lc_block_translators_registry.get(t)}a(Ic,"getTranslator");function Ac(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(Ac,"mergeModalitiesTokenDetails");function Hm(t,e){let r={...Ac(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(Hm,"mergeInputTokenDetails");function zm(t,e){let r={...Ac(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}a(zm,"mergeOutputTokenDetails");function Nn(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:Hm(t?.input_token_details,e?.input_token_details),output_token_details:zm(t?.output_token_details,e?.output_token_details)}}a(Nn,"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.
|
|
1
|
+
"use strict";var bn=Object.create;var ge=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,An=Object.prototype.hasOwnProperty;var s=(e,t)=>ge(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}},Mn=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},St=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of In(t))!An.call(e,o)&&o!==r&&ge(e,o,{get:()=>t[o],enumerable:!(n=Sn(t,o))||n.enumerable});return e};var oe=(e,t,r)=>(r=e!=null?bn(Rn(e)):{},St(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),Cn=e=>St(ge({},"__esModule",{value:!0}),e);var Ke=W((Fi,q)=>{var Ve=require("fs"),Ie=require("path"),vn=require("os"),Nn=require("crypto"),At=["\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 wn(){return At[Math.floor(Math.random()*At.length)]}s(wn,"_getRandomTip");function se(e){return typeof e=="string"?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}s(se,"parseBoolean");function Dn(){return process.stdout.isTTY}s(Dn,"supportsAnsi");function Ln(e){return Dn()?`\x1B[2m${e}\x1B[0m`:e}s(Ln,"dim");var On=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Pn(e){let t={},r=e.toString();r=r.replace(/\r\n?/mg,`
|
|
2
|
+
`);let n;for(;(n=On.exec(r))!=null;){let o=n[1],a=n[2]||"";a=a.trim();let i=a[0];a=a.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),i==='"'&&(a=a.replace(/\\n/g,`
|
|
3
|
+
`),a=a.replace(/\\r/g,"\r")),t[o]=a}return t}s(Pn,"parse");function Un(e){e=e||{};let t=vt(e);e.path=t;let r=k.configDotenv(e);if(!r.parsed){let i=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw i.code="MISSING_DATA",i}let n=xt(e).split(","),o=n.length,a;for(let i=0;i<o;i++)try{let c=n[i].trim(),d=kn(r,c);a=k.decrypt(d.ciphertext,d.key);break}catch(c){if(i+1>=o)throw c}return k.parse(a)}s(Un,"_parseVault");function Fn(e){console.error(`\u26A0 ${e}`)}s(Fn,"_warn");function he(e){console.log(`\u2506 ${e}`)}s(he,"_debug");function Ct(e){console.log(`\u25C7 ${e}`)}s(Ct,"_log");function xt(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:""}s(xt,"_dotenvKey");function kn(e,t){let r;try{r=new URL(t)}catch(c){if(c.code==="ERR_INVALID_URL"){let d=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 d.code="INVALID_DOTENV_KEY",d}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 o=r.searchParams.get("environment");if(!o){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let a=`DOTENV_VAULT_${o.toUpperCase()}`,i=e.parsed[a];if(!i){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:i,key:n}}s(kn,"_instructions");function vt(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)Ve.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=Ie.resolve(process.cwd(),".env.vault");return Ve.existsSync(t)?t:null}s(vt,"_vaultPath");function Mt(e){return e[0]==="~"?Ie.join(vn.homedir(),e.slice(1)):e}s(Mt,"_resolveHome");function Bn(e){let t=se(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),r=se(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!r)&&Ct("loading env from encrypted .env.vault");let n=k._parseVault(e),o=process.env;return e&&e.processEnv!=null&&(o=e.processEnv),k.populate(o,n,e),{parsed:n}}s(Bn,"_configVault");function Hn(e){let t=Ie.resolve(process.cwd(),".env"),r="utf8",n=process.env;e&&e.processEnv!=null&&(n=e.processEnv);let o=se(n.DOTENV_CONFIG_DEBUG||e&&e.debug),a=se(n.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:o&&he("no encoding is specified (UTF-8 is used by default)");let i=[t];if(e&&e.path)if(!Array.isArray(e.path))i=[Mt(e.path)];else{i=[];for(let h of e.path)i.push(Mt(h))}let c,d={};for(let h of i)try{let T=k.parse(Ve.readFileSync(h,{encoding:r}));k.populate(d,T,e)}catch(T){o&&he(`failed to load ${h} ${T.message}`),c=T}let m=k.populate(n,d,e);if(o=se(n.DOTENV_CONFIG_DEBUG||o),a=se(n.DOTENV_CONFIG_QUIET||a),o||!a){let h=Object.keys(m).length,T=[];for(let R of i)try{let _=Ie.relative(process.cwd(),R);T.push(_)}catch(_){o&&he(`failed to load ${R} ${_.message}`),c=_}Ct(`injected env (${h}) from ${T.join(",")} ${Ln(`// tip: ${wn()}`)}`)}return c?{parsed:d,error:c}:{parsed:d}}s(Hn,"configDotenv");function Gn(e){if(xt(e).length===0)return k.configDotenv(e);let t=vt(e);return t?k._configVault(e):(Fn(`you set DOTENV_KEY but you are missing a .env.vault file at ${t}`),k.configDotenv(e))}s(Gn,"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 i=Nn.createDecipheriv("aes-256-gcm",r,o);return i.setAuthTag(a),`${i.update(n)}${i.final()}`}catch(i){let c=i instanceof RangeError,d=i.message==="Invalid key length",m=i.message==="Unsupported state or unable to authenticate data";if(c||d){let h=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw h.code="INVALID_DOTENV_KEY",h}else if(m){let h=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw h.code="DECRYPTION_FAILED",h}else throw i}}s(Wn,"decrypt");function $n(e,t,r={}){let n=!!(r&&r.debug),o=!!(r&&r.override),a={};if(typeof t!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(t))Object.prototype.hasOwnProperty.call(e,i)?(o===!0&&(e[i]=t[i],a[i]=t[i]),n&&he(o===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(e[i]=t[i],a[i]=t[i]);return a}s($n,"populate");var k={configDotenv:Hn,_configVault:Bn,_parseVault:Un,config:Gn,decrypt:Wn,parse:Pn,populate:$n};q.exports.configDotenv=k.configDotenv;q.exports._configVault=k._configVault;q.exports._parseVault=k._parseVault;q.exports.config=k.config;q.exports.decrypt=k.decrypt;q.exports.parse=k.parse;q.exports.populate=k.populate;q.exports=k});var je=W((pa,Pt)=>{Pt.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 Re=W(Ft=>{var Ut={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 Zn(e){return function(...t){return t.length&&(e=e.replace(/\{(\d)\}/g,(r,n)=>t[n]||"")),new Error("ADM-ZIP: "+e)}}s(Zn,"E");for(let e of Object.keys(Ut))Ft[e]=Zn(Ut[e])});var Wt=W((ga,Gt)=>{var Jn=require("fs"),F=require("path"),kt=je(),Yn=Re(),qn=typeof process=="object"&&process.platform==="win32",Bt=s(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 D(e){this.sep=F.sep,this.fs=Jn,Bt(e)&&Bt(e.fs)&&typeof e.fs.statSync=="function"&&(this.fs=e.fs)}s(D,"Utils");Gt.exports=D;D.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 i;try{i=t.fs.statSync(o)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))t.fs.mkdirSync(o);else throw c}if(i&&i.isFile())throw Yn.FILE_IN_THE_WAY(`"${o}"`)}})}s(r,"mkdirSync"),r(e)};D.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 i=F.dirname(e);o.fs.existsSync(i)||o.makeDir(i);var c;try{c=o.fs.openSync(e,"w",438)}catch{o.fs.chmodSync(e,438),c=o.fs.openSync(e,"w",438)}if(c)try{o.fs.writeSync(c,t,0,t.length,0)}finally{o.fs.closeSync(c)}return o.fs.chmodSync(e,n||438),!0};D.prototype.writeFileToAsync=function(e,t,r,n,o){typeof n=="function"&&(o=n,n=void 0);let a=this;a.fs.exists(e,function(i){if(i&&!r)return o(!1);a.fs.stat(e,function(c,d){if(i&&d&&d.isDirectory())return o(!1);var m=F.dirname(e);a.fs.exists(m,function(h){if(!h)try{a.makeDir(m)}catch{return o(!1)}let T=s(function(R){a.fs.write(R,t,0,t.length,0,function(_){a.fs.close(R,function(){if(_)return o(!1);a.fs.chmod(e,n||438,function(){o(!0)})})})},"writeToFd");a.fs.open(e,"w",438,function(R,_){R?a.fs.chmod(e,438,function(){a.fs.open(e,"w",438,function(p,f){if(p||!f)return o(!1);T(f)})}):_?T(_):o(!1)})})})})};D.prototype.findFiles=function(e){let t=this;function r(n,o,a,i){typeof o=="boolean"&&(a=o,o=void 0);let c=[];return t.fs.readdirSync(n).forEach(function(d){let m=F.join(n,d),h=t.fs.statSync(m);if((!o||o.test(m))&&c.push(F.normalize(m)+(h.isDirectory()?t.sep:"")),h.isDirectory()&&a){let T=t.fs.realpathSync(m);i.has(T)||(i.add(T),c=c.concat(r(m,o,a,i)))}}),c}return s(r,"findSync"),r(e,void 0,!0,new Set([t.fs.realpathSync(e)]))};D.prototype.findFilesAsync=function(e,t){let r=this,n=[],o=!1,a=s(function(c){o||(o=!0,t(c,c?void 0:n))},"finish"),i=s(function(c,d,m){r.fs.readdir(c,function(h,T){if(h)return m(h);let R=T.length;if(!R)return m();T.forEach(function(_){let p=F.join(c,_);r.fs.stat(p,function(f,u){if(f)return m(f);if(!u){--R||m();return}if(n.push(F.normalize(p)+(u.isDirectory()?r.sep:"")),!u.isDirectory()){--R||m();return}r.fs.realpath(p,function(y,E){if(y)return m(y);if(d.has(E)){--R||m();return}d.add(E),i(p,d,function(l){if(l)return m(l);--R||m()})})})})})},"walk");r.fs.realpath(e,function(c,d){if(c)return a(c);i(e,new Set([d]),a)})};D.prototype.getAttributes=function(){};D.prototype.setAttributes=function(){};D.crc32update=function(e,t){return Ht[(e^t)&255]^e>>>8};D.crc32=function(e){typeof e=="string"&&(e=Buffer.from(e,"utf8"));let t=e.length,r=-1;for(let n=0;n<t;)r=D.crc32update(r,e[n++]);return~r>>>0};D.methodToString=function(e){switch(e){case kt.STORED:return"STORED ("+e+")";case kt.DEFLATED:return"DEFLATED ("+e+")";default:return"UNSUPPORTED ("+e+")"}};D.canonical=function(e){if(!e)return"";let t=F.posix.normalize("/"+e.split("\\").join("/"));return F.join(".",t)};D.zipnamefix=function(e){if(!e)return"";let t=F.posix.normalize("/"+e.split("\\").join("/"));return F.posix.join(".",t)};D.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]};D.sanitize=function(e,t){e=F.resolve(F.normalize(e));for(var r=t.split("/"),n=0,o=r.length;n<o;n++){var a=F.normalize(F.join(e,r.slice(n,o).join(F.sep)));if(a===e||a.startsWith(e+F.sep))return a}return F.normalize(F.join(e,F.basename(t)))};D.toBuffer=s(function(t,r){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):typeof t=="string"?r(t):Buffer.alloc(0)},"toBuffer");D.readBigUInt64LE=function(e,t){let r=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+r};D.writeBigUInt64LE=function(e,t,r){let n=t>>>0,o=Math.floor(t/4294967296)>>>0;e.writeUInt32LE(n,r),e.writeUInt32LE(o,r+4)};D.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)};D.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};D.isWin=qn;D.crcTable=Ht});var zt=W((ya,$t)=>{var Xn=require("path");$t.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 s(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=Xn.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:s(function(){},"decodeAttributes"),encodeAttributes:s(function(){},"encodeAttributes"),toJSON:s(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:s(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Kt=W((Ta,Vt)=>{Vt.exports={efs:!0,encode:s(e=>Buffer.from(e,"utf8"),"encode"),decode:s(e=>e.toString("utf8"),"decode")}});var ae=W((ba,ie)=>{ie.exports=Wt();ie.exports.Constants=je();ie.exports.Errors=Re();ie.exports.FileAttr=zt();ie.exports.decoder=Kt()});var Zt=W((Sa,jt)=>{var Q=ae(),b=Q.Constants;jt.exports=function(){var e=20,t=10,r=0,n=0,o=0,a=0,i=0,c=0,d=0,m=0,h=0,T=0,R=0,_=0,p=0;e|=Q.isWin?2560:768,r|=b.FLG_EFS;let f={extraLen:0},u=s(l=>Math.max(0,l)>>>0,"uint32"),y=s(l=>Math.max(0,l)&65535,"uint16"),E=s(l=>Math.max(0,l)&255,"uint8");return o=Q.fromDate2DOS(new Date),{get made(){return e},set made(l){e=l},get version(){return t},set version(l){t=l},get flags(){return r},set flags(l){r=l},get flags_efs(){return(r&b.FLG_EFS)>0},set flags_efs(l){l?r|=b.FLG_EFS:r&=~b.FLG_EFS},get flags_desc(){return(r&b.FLG_DESC)>0},set flags_desc(l){l?r|=b.FLG_DESC:r&=~b.FLG_DESC},get method(){return n},set method(l){switch(l){case b.STORED:this.version=10;break;case b.DEFLATED:default:this.version=20}n=l},get time(){return Q.fromDOS2Date(this.timeval)},set time(l){l=new Date(l),this.timeval=Q.fromDate2DOS(l)},get timeval(){return o},set timeval(l){o=u(l)},get timeHighByte(){return E(o>>>8)},get crc(){return a},set crc(l){a=u(l)},get compressedSize(){return i},set compressedSize(l){i=u(l)},get size(){return c},set size(l){c=u(l)},get fileNameLength(){return d},set fileNameLength(l){d=l},get extraLength(){return m},set extraLength(l){m=l},get extraLocalLength(){return f.extraLen},set extraLocalLength(l){f.extraLen=l},get commentLength(){return h},set commentLength(l){h=l},get diskNumStart(){return T},set diskNumStart(l){T=u(l)},get inAttr(){return R},set inAttr(l){R=u(l)},get attr(){return _},set attr(l){_=u(l)},get fileAttr(){return(_||0)>>16&4095},get offset(){return p},set offset(l){p=u(l)},get encrypted(){return(r&b.FLG_ENC)===b.FLG_ENC},get centralHeaderSize(){return b.CENHDR+d+m+h},get realDataOffset(){return p+b.LOCHDR+f.fnameLen+f.extraLen},get localHeader(){return f},loadLocalHeaderFromBinary:s(function(l){var g=l.slice(p,p+b.LOCHDR);if(g.readUInt32LE(0)!==b.LOCSIG)throw Q.Errors.INVALID_LOC();f.version=g.readUInt16LE(b.LOCVER),f.flags=g.readUInt16LE(b.LOCFLG),f.flags_desc=(f.flags&b.FLG_DESC)>0,f.method=g.readUInt16LE(b.LOCHOW),f.time=g.readUInt32LE(b.LOCTIM),f.crc=g.readUInt32LE(b.LOCCRC),f.compressedSize=g.readUInt32LE(b.LOCSIZ),f.size=g.readUInt32LE(b.LOCLEN),f.fnameLen=g.readUInt16LE(b.LOCNAM),f.extraLen=g.readUInt16LE(b.LOCEXT);let I=p+b.LOCHDR+f.fnameLen,A=I+f.extraLen;return l.slice(I,A)},"loadLocalHeaderFromBinary"),loadFromBinary:s(function(l){if(l.length!==b.CENHDR||l.readUInt32LE(0)!==b.CENSIG)throw Q.Errors.INVALID_CEN();e=l.readUInt16LE(b.CENVEM),t=l.readUInt16LE(b.CENVER),r=l.readUInt16LE(b.CENFLG),n=l.readUInt16LE(b.CENHOW),o=l.readUInt32LE(b.CENTIM),a=l.readUInt32LE(b.CENCRC),i=l.readUInt32LE(b.CENSIZ),c=l.readUInt32LE(b.CENLEN),d=l.readUInt16LE(b.CENNAM),m=l.readUInt16LE(b.CENEXT),h=l.readUInt16LE(b.CENCOM),T=l.readUInt16LE(b.CENDSK),R=l.readUInt16LE(b.CENATT),_=l.readUInt32LE(b.CENATX),p=l.readUInt32LE(b.CENOFF)},"loadFromBinary"),localHeaderToBinary:s(function(){var l=Buffer.alloc(b.LOCHDR);return l.writeUInt32LE(b.LOCSIG,0),l.writeUInt16LE(t,b.LOCVER),l.writeUInt16LE(r&~b.FLG_DESC,b.LOCFLG),l.writeUInt16LE(n,b.LOCHOW),l.writeUInt32LE(o,b.LOCTIM),l.writeUInt32LE(a,b.LOCCRC),l.writeUInt32LE(i,b.LOCSIZ),l.writeUInt32LE(c,b.LOCLEN),l.writeUInt16LE(d,b.LOCNAM),l.writeUInt16LE(f.extraLen,b.LOCEXT),l},"localHeaderToBinary"),centralHeaderToBinary:s(function(){var l=Buffer.alloc(b.CENHDR+d+m+h);return l.writeUInt32LE(b.CENSIG,0),l.writeUInt16LE(e,b.CENVEM),l.writeUInt16LE(t,b.CENVER),l.writeUInt16LE(r&~b.FLG_DESC,b.CENFLG),l.writeUInt16LE(n,b.CENHOW),l.writeUInt32LE(o,b.CENTIM),l.writeUInt32LE(a,b.CENCRC),l.writeUInt32LE(i,b.CENSIZ),l.writeUInt32LE(c,b.CENLEN),l.writeUInt16LE(d,b.CENNAM),l.writeUInt16LE(m,b.CENEXT),l.writeUInt16LE(h,b.CENCOM),l.writeUInt16LE(T,b.CENDSK),l.writeUInt16LE(R,b.CENATT),l.writeUInt32LE(_,b.CENATX),l.writeUInt32LE(p,b.CENOFF),l},"centralHeaderToBinary"),toJSON:s(function(){let l=s(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:l(i),size:l(c),fileNameLength:l(d),extraLength:l(m),commentLength:l(h),diskNumStart:T,inAttr:R,attr:_,offset:p,centralHeaderSize:l(b.CENHDR+d+m+h)}},"toJSON"),toString:s(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Yt=W((Ra,Jt)=>{var Z=ae(),M=Z.Constants;Jt.exports=function(){var e=0,t=0,r=0,n=0,o=0;let a=s(()=>e>M.EF_ZIP64_OR_16||t>M.EF_ZIP64_OR_16||r>M.EF_ZIP64_OR_32||n>M.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return e},set diskEntries(i){e=t=i},get totalEntries(){return t},set totalEntries(i){t=e=i},get size(){return r},set size(i){r=i},get offset(){return n},set offset(i){n=i},get commentLength(){return o},set commentLength(i){o=i},get mainHeaderSize(){return(a()?M.ZIP64HDR+M.END64HDR:0)+M.ENDHDR+o},loadFromBinary:s(function(i){if((i.length!==M.ENDHDR||i.readUInt32LE(0)!==M.ENDSIG)&&(i.length<M.ZIP64HDR||i.readUInt32LE(0)!==M.ZIP64SIG))throw Z.Errors.INVALID_END();i.readUInt32LE(0)===M.ENDSIG?(e=i.readUInt16LE(M.ENDSUB),t=i.readUInt16LE(M.ENDTOT),r=i.readUInt32LE(M.ENDSIZ),n=i.readUInt32LE(M.ENDOFF),o=i.readUInt16LE(M.ENDCOM)):(e=Z.readBigUInt64LE(i,M.ZIP64SUB),t=Z.readBigUInt64LE(i,M.ZIP64TOT),r=Z.readBigUInt64LE(i,M.ZIP64SIZB),n=Z.readBigUInt64LE(i,M.ZIP64OFF),o=0)},"loadFromBinary"),toBinary:s(function(){if(!a()){var i=Buffer.alloc(M.ENDHDR+o);return i.writeUInt32LE(M.ENDSIG,0),i.writeUInt32LE(0,4),i.writeUInt16LE(e,M.ENDSUB),i.writeUInt16LE(t,M.ENDTOT),i.writeUInt32LE(r,M.ENDSIZ),i.writeUInt32LE(n,M.ENDOFF),i.writeUInt16LE(o,M.ENDCOM),i.fill(" ",M.ENDHDR),i}var i=Buffer.alloc(this.mainHeaderSize);let c=0;i.writeUInt32LE(M.ZIP64SIG,c),Z.writeBigUInt64LE(i,M.ZIP64HDR-M.ZIP64LEAD,c+M.ZIP64SIZE),i.writeUInt16LE(45,c+M.ZIP64VEM),i.writeUInt16LE(45,c+M.ZIP64VER),i.writeUInt32LE(0,c+M.ZIP64DSK),i.writeUInt32LE(0,c+M.ZIP64DSKDIR),Z.writeBigUInt64LE(i,e,c+M.ZIP64SUB),Z.writeBigUInt64LE(i,t,c+M.ZIP64TOT),Z.writeBigUInt64LE(i,r,c+M.ZIP64SIZB),Z.writeBigUInt64LE(i,n,c+M.ZIP64OFF);let d=n+r;return c+=M.ZIP64HDR,i.writeUInt32LE(M.END64SIG,c),i.writeUInt32LE(0,c+M.END64START),Z.writeBigUInt64LE(i,d,c+M.END64OFF),i.writeUInt32LE(1,c+M.END64NUMDISKS),c+=M.END64HDR,i.writeUInt32LE(M.ENDSIG,c),i.writeUInt32LE(0,c+4),i.writeUInt16LE(Math.min(e,M.EF_ZIP64_OR_16),c+M.ENDSUB),i.writeUInt16LE(Math.min(t,M.EF_ZIP64_OR_16),c+M.ENDTOT),i.writeUInt32LE(Math.min(r,M.EF_ZIP64_OR_32),c+M.ENDSIZ),i.writeUInt32LE(Math.min(n,M.EF_ZIP64_OR_32),c+M.ENDOFF),i.writeUInt16LE(o,c+M.ENDCOM),i.fill(" ",c+M.ENDHDR),i},"toBinary"),toJSON:s(function(){let i=s(function(c,d){let m=c.toString(16).toUpperCase();for(;m.length<d;)m="0"+m;return"0x"+m},"offset");return{diskEntries:e,totalEntries:t,size:r+" bytes",offset:i(n,4),commentLength:o}},"toJSON"),toString:s(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Je=W(Ze=>{Ze.EntryHeader=Zt();Ze.MainHeader=Yt()});var Xt=W((Ca,qt)=>{qt.exports=function(e){var t=require("zlib"),r={chunkSize:(parseInt(e.length/1024)+1)*1024};return{deflate:s(function(){return t.deflateRawSync(e,r)},"deflate"),deflateAsync:s(function(n){var o=t.createDeflateRaw(r),a=[],i=0;o.on("data",function(c){a.push(c),i+=c.length}),o.on("end",function(){var c=Buffer.alloc(i),d=0;c.fill(0);for(var m=0;m<a.length;m++){var h=a[m];h.copy(c,d),d+=h.length}n&&n(c)}),o.end(e)},"deflateAsync")}}});var er=W((va,Qt)=>{var Qn=+(process?.versions?.node??"").split(".")[0]||0;Qt.exports=function(e,t){var r=require("zlib");let n=Qn>=15&&t>0?{maxOutputLength:t}:{};return{inflate:s(function(){return r.inflateRawSync(e,n)},"inflate"),inflateAsync:s(function(o){var a=r.createInflateRaw(n),i=[],c=0;a.on("data",function(d){i.push(d),c+=d.length}),a.on("end",function(){var d=Buffer.alloc(c),m=0;d.fill(0);for(var h=0;h<i.length;h++){var T=i[h];T.copy(d,m),m+=T.length}o&&o(d)}),a.end(e)},"inflateAsync")}}});var sr=W((wa,or)=>{"use strict";var{randomFillSync:tr}=require("crypto"),eo=Re(),to=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}),nr=s((e,t)=>Math.imul(e,t)>>>0,"uMul"),rr=s((e,t)=>to[(e^t)&255]^e>>>8,"crc32update"),ye=s(()=>typeof tr=="function"?tr(Buffer.alloc(12)):ye.node(),"genSalt");ye.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 Ae={genSalt:ye};function Me(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])}s(Me,"Initkeys");Me.prototype.updateKeys=function(e){let t=this.keys;return t[0]=rr(t[0],e),t[1]+=t[0]&255,t[1]=nr(t[1],134775813)+1,t[2]=rr(t[2],t[1]>>>24),e};Me.prototype.next=function(){let e=(this.keys[2]|2)>>>0;return nr(e,e^1)>>8&255};function ro(e){let t=new Me(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}}s(ro,"make_decrypter");function no(e){let t=new Me(e);return function(r,n,o=0){n||(n=Buffer.alloc(r.length));for(let a of r){let i=t.next();n[o++]=a^i,t.updateKeys(a)}return n}}s(no,"make_encrypter");function oo(e,t,r){if(!e||!Buffer.isBuffer(e)||e.length<12)return Buffer.alloc(0);let n=ro(r),o=n(e.slice(0,12)),a=(t.flags&8)===8?t.timeHighByte:t.crc>>>24;if(o[11]!==a)throw eo.WRONG_PASSWORD();return n(e.slice(12))}s(oo,"decrypt");function so(e){Buffer.isBuffer(e)&&e.length>=12?Ae.genSalt=function(){return e.slice(0,12)}:e==="node"?Ae.genSalt=ye.node:Ae.genSalt=ye}s(so,"_salter");function io(e,t,r,n=!1){e==null&&(e=Buffer.alloc(0)),Buffer.isBuffer(e)||(e=Buffer.from(e.toString()));let o=no(r),a=Ae.genSalt();a[11]=t.crc>>>24&255,n&&(a[10]=t.crc>>>16&255);let i=Buffer.alloc(e.length+12);return o(a,i),o(e,i,12)}s(io,"encrypt");or.exports={decrypt:oo,encrypt:io,_salter:so}});var ir=W(Ce=>{Ce.Deflater=Xt();Ce.Inflater=er();Ce.ZipCrypto=sr()});var qe=W((Oa,ar)=>{var w=ae(),ao=Je(),j=w.Constants,Ye=ir();ar.exports=function(e,t){var r=new ao.EntryHeader,n=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,i=null,c=Buffer.alloc(0),d=Buffer.alloc(0),m=!0;let h=e,T=typeof h.decoder=="object"?h.decoder:w.decoder;m=T.hasOwnProperty("efs")?T.efs:!1;function R(){return!t||!(t instanceof Uint8Array)?Buffer.alloc(0):(d=r.loadLocalHeaderFromBinary(t),t.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}s(R,"getCompressedDataFromZip");function _(l){let g=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return w.crc32(l)===g}s(_,"crc32OK");function p(l,g,I){if(typeof g>"u"&&typeof l=="string"&&(I=l,l=void 0),a)return l&&g&&g(Buffer.alloc(0),w.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var A=R();if(A.length===0)return l&&g&&g(A),A;if(r.encrypted){if(typeof I!="string"&&!Buffer.isBuffer(I))throw w.Errors.INVALID_PASS_PARAM();A=Ye.ZipCrypto.decrypt(A,r,I)}var S;switch(r.method){case w.Constants.STORED:if(S=Buffer.alloc(A.length),A.copy(S),_(S))return l&&g&&g(S),S;throw l&&g&&g(S,w.Errors.BAD_CRC()),w.Errors.BAD_CRC();case w.Constants.DEFLATED:var C=new Ye.Inflater(A,r.size);if(l)C.inflateAsync(function(x){g&&(_(x)?g(x):g(x,w.Errors.BAD_CRC()))});else{if(S=C.inflate(),!_(S))throw w.Errors.BAD_CRC(`"${T.decode(n)}"`);return S}break;default:throw l&&g&&g(Buffer.alloc(0),w.Errors.UNKNOWN_METHOD()),w.Errors.UNKNOWN_METHOD()}}s(p,"decompress");function f(l,g){if((!i||!i.length)&&Buffer.isBuffer(t))return l&&g&&g(R()),R();if(i.length&&!a){var I;switch(r.method){case w.Constants.STORED:return r.compressedSize=r.size,I=Buffer.alloc(i.length),i.copy(I),l&&g&&g(I),I;default:case w.Constants.DEFLATED:var A=new Ye.Deflater(i);if(l)A.deflateAsync(function(C){I=Buffer.alloc(C.length),r.compressedSize=C.length,C.copy(I),g&&g(I)});else{var S=A.deflate();return r.compressedSize=S.length,S}A=null;break}}else if(l&&g)g(Buffer.alloc(0));else return Buffer.alloc(0)}s(f,"compress");function u(l,g){return w.readBigUInt64LE(l,g)}s(u,"readUInt64LE");function y(l){try{for(var g=0,I,A,S;g+4<l.length;)I=l.readUInt16LE(g),g+=2,A=l.readUInt16LE(g),g+=2,S=l.slice(g,g+A),g+=A,j.ID_ZIP64===I&&E(S)}catch{throw w.Errors.EXTRA_FIELD_PARSE_ERROR()}}s(y,"parseExtra");function E(l){var g,I,A,S;l.length>=j.EF_ZIP64_SCOMP&&(g=u(l,j.EF_ZIP64_SUNCOMP),r.size===j.EF_ZIP64_OR_32&&(r.size=g)),l.length>=j.EF_ZIP64_RHO&&(I=u(l,j.EF_ZIP64_SCOMP),r.compressedSize===j.EF_ZIP64_OR_32&&(r.compressedSize=I)),l.length>=j.EF_ZIP64_DSN&&(A=u(l,j.EF_ZIP64_RHO),r.offset===j.EF_ZIP64_OR_32&&(r.offset=A)),l.length>=j.EF_ZIP64_DSN+4&&(S=l.readUInt32LE(j.EF_ZIP64_DSN),r.diskNumStart===j.EF_ZIP64_OR_16&&(r.diskNumStart=S))}return s(E,"parseZip64ExtendedInformation"),{get entryName(){return T.decode(n)},get rawEntryName(){return n},set entryName(l){n=w.toBuffer(l,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 c},set extra(l){c=l,r.extraLength=l.length,y(l)},get comment(){return T.decode(o)},set comment(l){if(o=w.toBuffer(l,T.encode),r.commentLength=o.length,o.length>65535)throw w.Errors.COMMENT_TOO_LONG()},get name(){let l=T.decode(n);return a?l.replace(/[/\\]$/,"").split("/").pop():l.split("/").pop()},get isDirectory(){return a},getCompressedData:s(function(){return f(!1,null)},"getCompressedData"),getCompressedDataAsync:s(function(l){f(!0,l)},"getCompressedDataAsync"),setData:s(function(l){i=w.toBuffer(l,w.decoder.encode),!a&&i.length?(r.size=i.length,r.method=w.Constants.DEFLATED,r.crc=w.crc32(l),r.changed=!0):r.method=w.Constants.STORED},"setData"),getData:s(function(l){return r.changed?i:p(!1,null,l)},"getData"),getDataAsync:s(function(l,g){r.changed?l(i):p(!0,l,g)},"getDataAsync"),set attr(l){r.attr=l},get attr(){return r.attr},set header(l){r.loadFromBinary(l)},get header(){return r},packCentralHeader:s(function(){r.flags_efs=this.efs,r.extraLength=c.length;var l=r.centralHeaderToBinary(),g=w.Constants.CENHDR;return n.copy(l,g),g+=n.length,c.copy(l,g),g+=r.extraLength,o.copy(l,g),l},"packCentralHeader"),packLocalHeader:s(function(){let l=0;r.flags_efs=this.efs,r.extraLocalLength=d.length;let g=r.localHeaderToBinary(),I=Buffer.alloc(g.length+n.length+r.extraLocalLength);return g.copy(I,l),l+=g.length,n.copy(I,l),l+=n.length,d.copy(I,l),l+=d.length,I},"packLocalHeader"),toJSON:s(function(){let l=s(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:l(t),data:l(i)}},"toJSON"),toString:s(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var dr=W((Ua,cr)=>{var lr=qe(),lo=Je(),z=ae();cr.exports=function(e,t){var r=[],n=Object.create(null),o=Buffer.alloc(0),a=new lo.MainHeader,i=!1,c=null;let d=new Set,m=t,{noSort:h,decoder:T}=m;e?p(m.readEntries):i=!0;function R(){let u=new Set;for(let y of Object.keys(n)){let E=y.split("/");if(E.pop(),!!E.length)for(let l=0;l<E.length;l++){let g=E.slice(0,l+1).join("/")+"/";u.add(g)}}for(let y of u)if(!(y in n)){let E=new lr(m);E.entryName=y,E.attr=16,E.temporary=!0,r.push(E),n[E.entryName]=E,d.add(E)}}s(R,"makeTemporaryFolders");function _(){if(i=!0,n=Object.create(null),a.diskEntries>(e.length-a.offset)/z.Constants.CENHDR)throw z.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(a.diskEntries);for(var u=a.offset,y=0;y<r.length;y++){var E=u,l=new lr(m,e);l.header=e.slice(E,E+=z.Constants.CENHDR),l.entryName=e.slice(E,E+=l.header.fileNameLength),l.header.extraLength&&(l.extra=e.slice(E,E+=l.header.extraLength)),l.header.commentLength&&(l.comment=e.slice(E,E+l.header.commentLength)),u+=l.header.centralHeaderSize,r[y]=l,n[l.entryName]=l}d.clear(),R()}s(_,"readEntries");function p(u){var y=e.length-z.Constants.ENDHDR,E=Math.max(0,y-65535),l=E,g=e.length,I=-1,A=0;for(typeof m.trailingSpace=="boolean"&&m.trailingSpace&&(E=0),y;y>=l;y--)if(e[y]===80){if(e.readUInt32LE(y)===z.Constants.ENDSIG){I=y,A=y,g=y+z.Constants.ENDHDR,l=y-z.Constants.END64HDR;continue}if(e.readUInt32LE(y)===z.Constants.END64SIG){l=E;continue}if(e.readUInt32LE(y)===z.Constants.ZIP64SIG){I=y,g=y+z.readBigUInt64LE(e,y+z.Constants.ZIP64SIZE)+z.Constants.ZIP64LEAD;break}}if(I==-1)throw z.Errors.INVALID_FORMAT();a.loadFromBinary(e.slice(I,g)),a.commentLength&&(o=e.slice(A+z.Constants.ENDHDR)),u&&_()}s(p,"readMainHeader");function f(){r.length>1&&!h&&(r=r.map(u=>({entry:u,key:u.entryName.toLowerCase()})).sort((u,y)=>u.key.localeCompare(y.key)).map(u=>u.entry))}return s(f,"sortEntries"),{get entries(){return i||_(),r.filter(u=>!d.has(u))},get comment(){return T.decode(o)},set comment(u){o=z.toBuffer(u,T.encode),a.commentLength=o.length},getEntryCount:s(function(){return i?r.length:a.diskEntries},"getEntryCount"),forEach:s(function(u){this.entries.forEach(u)},"forEach"),getEntry:s(function(u){return i||_(),n[u]||null},"getEntry"),setEntry:s(function(u){i||_(),r.push(u),n[u.entryName]=u,a.totalEntries=r.length},"setEntry"),deleteFile:s(function(u,y=!0){i||_();let E=n[u];this.getEntryChildren(E,y).map(g=>g.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:s(function(u){i||_();let y=n[u],E=r.indexOf(y);E>=0&&(r.splice(E,1),delete n[u],a.totalEntries=r.length)},"deleteEntry"),getEntryChildren:s(function(u,y=!0){if(i||_(),typeof u=="object")if(u.isDirectory&&y){let E=[],l=u.entryName;for(let g of r)g.entryName.startsWith(l)&&E.push(g);return E}else return[u];return[]},"getEntryChildren"),getChildCount:s(function(u){if(u&&u.isDirectory){let y=this.getEntryChildren(u);return y.includes(u)?y.length-1:y.length}return 0},"getChildCount"),compressToBuffer:s(function(){i||_(),f();let u=[],y=[],E=0,l=0;a.size=0,a.offset=0;let g=0;for(let S of this.entries){let C=S.getCompressedData();S.header.offset=l;let x=S.packLocalHeader(),v=x.length+C.length;l+=v,u.push(x),u.push(C);let N=S.packCentralHeader();y.push(N),a.size+=N.length,E+=v+N.length,g++}E+=a.mainHeaderSize,a.offset=l,a.totalEntries=g,l=0;let I=Buffer.alloc(E);for(let S of u)S.copy(I,l),l+=S.length;for(let S of y)S.copy(I,l),l+=S.length;let A=a.toBinary();return o&&o.copy(A,A.length-o.length),A.copy(I,l),e=I,i=!1,I},"compressToBuffer"),toAsyncBuffer:s(function(u,y,E,l){try{i||_(),f();let g=[],I=[],A=0,S=0,C=0;a.size=0,a.offset=0;let x=s(function(v){if(v.length>0){let N=v.shift(),G=N.entryName+N.extra.toString();E&&E(G),N.getCompressedDataAsync(function($){l&&l(G),N.header.offset=S;let ee=N.packLocalHeader(),Se=ee.length+$.length;S+=Se,g.push(ee),g.push($);let me=N.packCentralHeader();I.push(me),a.size+=me.length,A+=Se+me.length,C++,x(v)})}else{A+=a.mainHeaderSize,a.offset=S,a.totalEntries=C,S=0;let N=Buffer.alloc(A);g.forEach(function($){$.copy(N,S),S+=$.length}),I.forEach(function($){$.copy(N,S),S+=$.length});let G=a.toBinary();o&&o.copy(G,G.length-o.length),G.copy(N,S),e=N,i=!1,u(N)}},"compress2Buffer");x(Array.from(this.entries))}catch(g){y(g)}},"toAsyncBuffer")}}});var fr=W((ka,pr)=>{var O=ae(),L=require("path"),co=qe(),uo=dr(),te=s((...e)=>O.findLast(e,t=>typeof t=="boolean"),"get_Bool"),ur=s((...e)=>O.findLast(e,t=>typeof t=="string"),"get_Str"),po=s((...e)=>O.findLast(e,t=>typeof t=="function"),"get_Fun"),fo={noSort:!1,readEntries:!1,method:O.Constants.NONE,fs:null};pr.exports=function(e,t){let r=null,n=Object.assign(Object.create(null),fo);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=O.Constants.BUFFER,e=void 0)),Object.assign(n,t);let o=new O(n),a=s(p=>{p.filter(f=>f.attr).sort((f,u)=>u.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=O.decoder),e&&typeof e=="string")if(o.fs.existsSync(e))n.method=O.Constants.FILE,n.filename=e,r=o.fs.readFileSync(e);else throw O.Errors.INVALID_FILENAME();let i=new uo(r,n),{canonical:c,sanitize:d,zipnamefix:m}=O;function h(p){if(p&&i){var f;if(typeof p=="string"&&(f=i.getEntry(L.posix.normalize(p))),typeof p=="object"&&typeof p.entryName<"u"&&typeof p.header<"u"&&(f=i.getEntry(p.entryName)),f)return f}return null}s(h,"getEntry");function T(p){let{join:f,normalize:u,sep:y}=L.posix;return f(L.isAbsolute(p)?"/":".",u(y+p.split("\\").join(y)+y))}s(T,"fixPath");function R(p){return p instanceof RegExp?(function(f){return function(u){return f.test(u)}})(p):typeof p!="function"?()=>!0:p}s(R,"filenameFilter");let _=s((p,f)=>{let u=f.slice(-1);return u=u===o.sep?o.sep:"",L.relative(p,f)+u},"relativePath");return{readFile:s(function(p,f){var u=h(p);return u&&u.getData(f)||null},"readFile"),childCount:s(function(p){let f=h(p);if(f)return i.getChildCount(f)},"childCount"),readFileAsync:s(function(p,f){var u=h(p);u?u.getDataAsync(f):f(null,"getEntry failed for:"+p)},"readFileAsync"),readAsText:s(function(p,f){var u=h(p);if(u){var y=u.getData();if(y&&y.length)return y.toString(f||"utf8")}return""},"readAsText"),readAsTextAsync:s(function(p,f,u){var y=h(p);y?y.getDataAsync(function(E,l){if(l){f(E,l);return}E&&E.length?f(E.toString(u||"utf8")):f("")}):f("")},"readAsTextAsync"),deleteFile:s(function(p,f=!0){var u=h(p);u&&i.deleteFile(u.entryName,f)},"deleteFile"),deleteEntry:s(function(p){var f=h(p);f&&i.deleteEntry(f.entryName)},"deleteEntry"),addZipComment:s(function(p){i.comment=p},"addZipComment"),getZipComment:s(function(){return i.comment||""},"getZipComment"),addZipEntryComment:s(function(p,f){var u=h(p);u&&(u.comment=f)},"addZipEntryComment"),getZipEntryComment:s(function(p){var f=h(p);return f&&f.comment||""},"getZipEntryComment"),updateFile:s(function(p,f){var u=h(p);u&&u.setData(f)},"updateFile"),addLocalFile:s(function(p,f,u,y){if(o.fs.existsSync(p)){f=f?T(f):"";let E=L.win32.basename(L.win32.normalize(p));f+=u||E;let l=o.fs.statSync(p),g=l.isFile()?o.fs.readFileSync(p):Buffer.alloc(0);l.isDirectory()&&(f+=o.sep),this.addFile(f,g,y,l)}else throw O.Errors.FILE_NOT_FOUND(p)},"addLocalFile"),addLocalFileAsync:s(function(p,f){p=typeof p=="object"?p:{localPath:p};let u=L.resolve(p.localPath),{comment:y}=p,{zipPath:E,zipName:l}=p,g=this;o.fs.stat(u,function(I,A){if(I)return f(I,!1);E=E?T(E):"";let S=L.win32.basename(L.win32.normalize(u));if(E+=l||S,A.isFile())o.fs.readFile(u,function(C,x){return C?f(C,!1):(g.addFile(E,x,y,A),setImmediate(f,void 0,!0))});else if(A.isDirectory())return E+=o.sep,g.addFile(E,Buffer.alloc(0),y,A),setImmediate(f,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:s(function(p,f,u){if(u=R(u),f=f?T(f):"",p=L.normalize(p),o.fs.existsSync(p)){let y=o.findFiles(p),E=this;if(y.length)for(let l of y){let g=L.join(f,_(p,l));u(g)&&E.addLocalFile(l,L.dirname(g))}}else throw O.Errors.FILE_NOT_FOUND(p)},"addLocalFolder"),addLocalFolderAsync:s(function(p,f,u,y){y=R(y),u=u?T(u):"",p=L.normalize(p);var E=this;o.fs.open(p,"r",function(l){if(l&&l.code==="ENOENT")f(void 0,O.Errors.FILE_NOT_FOUND(p));else if(l)f(void 0,l);else{var g=o.findFiles(p),I=-1,A=s(function(){if(I+=1,I<g.length){var S=g[I],C=_(p,S).split("\\").join("/");C=C.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),y(C)?o.fs.stat(S,function(x,v){x&&f(void 0,x),v.isFile()?o.fs.readFile(S,function(N,G){N?f(void 0,N):(E.addFile(u+C,G,"",v),A())}):(E.addFile(u+C+"/",Buffer.alloc(0),"",v),A())}):process.nextTick(()=>{A()})}else f(!0,void 0)},"next");A()}})},"addLocalFolderAsync"),addLocalFolderAsync2:s(function(p,f){let u=this;p=typeof p=="object"?p:{localPath:p};let y=L.resolve(T(p.localPath)),{zipPath:E,filter:l,namefix:g}=p;l instanceof RegExp?l=(function(S){return function(C){return S.test(C)}})(l):typeof l!="function"&&(l=s(function(){return!0},"filter")),E=E?T(E):"",g==="latin1"&&(g=s(S=>S.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof g!="function"&&(g=s(S=>S,"namefix"));let I=s(S=>L.join(E,g(_(y,S))),"relPathFix"),A=s(S=>L.win32.basename(L.win32.normalize(g(S))),"fileNameFix");o.fs.open(y,"r",function(S){S&&S.code==="ENOENT"?f(void 0,O.Errors.FILE_NOT_FOUND(y)):S?f(void 0,S):o.findFilesAsync(y,function(C,x){if(C)return f(C);x=x.filter(v=>l(I(v))),x.length||f(void 0,!1),setImmediate(x.reverse().reduce(function(v,N){return function(G,$){if(G||$===!1)return setImmediate(v,G,!1);u.addLocalFileAsync({localPath:N,zipPath:L.dirname(I(N)),zipName:A(N)},v)}},f))})})},"addLocalFolderAsync2"),addLocalFolderPromise:s(function(p,f){return new Promise((u,y)=>{this.addLocalFolderAsync2(Object.assign({localPath:p},f),(E,l)=>{E&&y(E),l&&u(this)})})},"addLocalFolderPromise"),addFile:s(function(p,f,u,y){p=m(p);let E=h(p),l=E!=null;l||(E=new co(n),E.entryName=p),E.comment=u||"";let g=typeof y=="object"&&y instanceof o.fs.Stats;g&&(E.header.time=y.mtime);var I=E.isDirectory?16:0;let A=E.isDirectory?16384:32768;return g?A|=4095&y.mode:typeof y=="number"?A|=4095&y:A|=E.isDirectory?493:420,I=(I|A<<16)>>>0,E.attr=I,E.setData(f),l||i.setEntry(E),E},"addFile"),getEntries:s(function(p){return i.password=p,i?i.entries:[]},"getEntries"),getEntry:s(function(p){return h(p)},"getEntry"),getEntryCount:s(function(){return i.getEntryCount()},"getEntryCount"),forEach:s(function(p){return i.forEach(p)},"forEach"),extractEntryTo:s(function(p,f,u,y,E,l){y=te(!1,y),E=te(!1,E),u=te(!0,u),l=ur(E,l);var g=h(p);if(!g)throw O.Errors.NO_ENTRY();var I=c(g.entryName),A=d(f,l&&!g.isDirectory?c(l):u?I:L.basename(I));if(g.isDirectory){var S=i.getEntryChildren(g);return S.forEach(function(v){if(v.isDirectory)return;var N=v.getData();if(!N)throw O.Errors.CANT_EXTRACT_FILE();var G=c(u?v.entryName:v.entryName.substring(g.entryName.length)),$=d(f,G);let ee=E?v.header.fileAttr:void 0;o.writeFileTo($,N,y,ee)}),!0}var C=g.getData(i.password);if(!C)throw O.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(A)&&!y)throw O.Errors.CANT_OVERRIDE();let x=E?p.header.fileAttr:void 0;return o.writeFileTo(A,C,y,x),!0},"extractEntryTo"),test:s(function(p){if(!i)return!1;for(var f of i.entries)try{if(f.isDirectory)continue;var u=f.getData(p);if(!u)return!1}catch{return!1}return!0},"test"),extractAllTo:s(function(p,f,u,y){if(u=te(!1,u),y=ur(u,y),f=te(!1,f),!i)throw O.Errors.NO_ZIP();let E=[];i.entries.forEach(function(l){var g=d(p,c(l.entryName));if(l.isDirectory){o.makeDir(g),u&&E.push({path:g,attr:l.header.fileAttr});return}var I=l.getData(y);if(!I)throw O.Errors.CANT_EXTRACT_FILE();let A=u?l.header.fileAttr:void 0;o.writeFileTo(g,I,f,A);try{o.fs.utimesSync(g,l.header.time,l.header.time)}catch{}}),a(E)},"extractAllTo"),extractAllToAsync:s(function(p,f,u,y){if(y=po(f,u,y),u=te(!1,u),f=te(!1,f),!y)return new Promise((C,x)=>{this.extractAllToAsync(p,f,u,function(v){v?x(v):C(this)})});if(!i){y(O.Errors.NO_ZIP());return}p=L.resolve(p);let E=s(C=>d(p,L.normalize(c(C.entryName))),"getPath"),l=s((C,x)=>new Error(C+': "'+x+'"'),"getError"),g=[],I=[];i.entries.forEach(C=>{C.isDirectory?g.push(C):I.push(C)});let A=[];for(let C of g){let x=E(C),v=u?C.header.fileAttr:void 0;try{o.makeDir(x)}catch{y(l("Unable to create folder",x));continue}v&&A.push({path:x,attr:v});try{o.fs.utimesSync(x,C.header.time,C.header.time)}catch{}}let S=s(C=>{if(!C)try{a(A)}catch(x){return y(l("Unable to set folder permissions",x.path||""))}y(C)},"done");I.reverse().reduce(function(C,x){return function(v){if(v)C(v);else{let N=L.normalize(c(x.entryName)),G=d(p,N);x.getDataAsync(function($,ee){if(ee)C(ee);else if(!$)C(O.Errors.CANT_EXTRACT_FILE());else{let Se=u?x.header.fileAttr:void 0;o.writeFileToAsync(G,$,f,Se,function(me){if(!me)return C(l("Unable to write file",G));o.fs.utimes(G,x.header.time,x.header.time,function(){C()})})}})}}},S)()},"extractAllToAsync"),writeZip:s(function(p,f){if(arguments.length===1&&typeof p=="function"&&(f=p,p=""),!p&&n.filename&&(p=n.filename),!!p){var u=i.compressToBuffer();if(u){var y=o.writeFileTo(p,u,!0);typeof f=="function"&&f(y?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:s(function(p,f){let{overwrite:u,perm:y}=Object.assign({overwrite:!0},f);return new Promise((E,l)=>{!p&&n.filename&&(p=n.filename),p||l("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(g=>{let I=s(A=>A?E(A):l("ADM-ZIP: Wasn't able to write zip file"),"ret");o.writeFileToAsync(p,g,u,y,I)},l)})},"writeZipPromise"),toBufferPromise:s(function(){return new Promise((p,f)=>{i.toAsyncBuffer(p,f)})},"toBufferPromise"),toBuffer:s(function(p,f,u,y){return typeof p=="function"?(i.toAsyncBuffer(p,f,u,y),null):i.compressToBuffer()},"toBuffer")}}});var Ls={};Mn(Ls,{TestRunMonitor:()=>$e});module.exports=Cn(Ls);var ze=s(e=>new Promise(t=>setTimeout(t,e)),"awaitSleep");function It(e=5,t="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let r="";for(let n=e;n>0;--n)r+=t[Math.floor(Math.random()*t.length)]??"";return r}s(It,"randomString");var Xi=require("@playwright/test");var _i=require("@playwright/test");var gi=require("@playwright/test");var ui=require("@playwright/test");var Vi=require("@playwright/test");var Pi={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 Nt=oe(Ke());Nt.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var zn="claude_4",Vn={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}},Kn=s(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:zn},models:Vn,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),U=Kn(),Wi={claude_4:U.models.claude4sonnet,"claude_3.7":U.models.claude37sonnet,claude_sonnet_4_6:U.models.claudeSonnet46,claude_sonnet_5:U.models.claudeSonnet5,claude_opus_4_8:U.models.claudeOpus48,"gemini_2.5_pro":U.models.gemini25pro,"gemini_2.0_flash":U.models.gemini20flash,"gemini_2.5_flash_lite":U.models.gemini25flash_lite,"gemini_2.5_flash":U.models.gemini25flash,"gemini_3.5_flash":U.models.gemini35flash,"gemini_3.1_flash_lite":U.models.gemini31flashLite,gpt_4o_mini:U.models.gpt4omini,gpt_4o_nano:U.models.gpt4onano,gpt_41_nano:U.models.gpt41nano,gpt_5_mini:U.models.gpt5mini,gpt_5_nano:U.models.gpt5nano,gpt_41_mini:U.models.gpt41mini,gpt_41:U.models.gpt41,o4_mini:U.models.o4mini,o3_mini:U.models.o3mini};var mn=require("child_process"),be=require("crypto"),P=require("fs"),gn=require("fs/promises"),hn=require("stream/promises"),yn=require("http"),En=oe(require("net")),Tn=require("os"),K=require("path");function jn(e){if(e)return{...e,...e.tests?{tests:e.tests.map(t=>{let{errorMessage:r,...n}=t;return n})}:{}}}s(jn,"projectReportStatsForTelemetry");function wt(e,t,r){e.emit({outcome:t,stats:jn(r)})}s(wt,"emitReportProcessingStatsTelemetry");var Dt=["script","template"],Lt='<script id="playwrightReportBase64" type="application/zip">',Ot="</script>";var Br=require("htmlparser2"),Hr=oe(fr()),H=require("node:fs"),re=require("node:path"),Gr=require("node:os"),Wr=require("node:crypto");var X=oe(require("path")),et=require("fs");var Xe=require("path"),xe=require("fs");function mo(e,t,r=10){let n=e;for(let o=0;o<r;o++){let a=(0,Xe.join)(n,"package.json");if((0,xe.existsSync)(a))try{if(JSON.parse((0,xe.readFileSync)(a,"utf8")).name===t)return n}catch{}n=(0,Xe.join)(n,"..")}}s(mo,"findRepositoryRoot");function mr(e,t=10){return mo(e,"checksum-customer-engineering-workspace",t)}s(mr,"findCustomerEngineeringRoot");var tt=oe(Ke());var V=s((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 gr(e){if(e===void 0||e.trim()==="")return 5e7;let t=Number(e);return!Number.isInteger(t)||t<0?5e7:t}s(gr,"resolveMaxRRwebBytes");var go=__dirname,hr=X.join(__dirname,".."),Er=(0,et.existsSync)(hr)?hr:go;(0,tt.config)({path:X.resolve(Er,".env")});var yr=V(process.env.CHECKSUM_RUNTIME_DEV_MODE);function ho(){let e=__dirname;for(;!(0,et.existsSync)(X.join(e,"package.json"));)e=X.join(e,"..");return e}s(ho,"findRoot");var Ee=ho(),yo=mr(Ee,10);(0,tt.config)({path:[Er,yo].filter(e=>!!e).map(e=>X.resolve(e,".env")),override:!1});var Qe=V(process.env.CHECKSUM_RUNTIME_REPO_MODE),Eo=Qe?X.join(Ee,"package","pw-report-template.html"):X.join(Ee,"pw-report-template.html"),To=V(process.env.CHECKSUM_DEBUG_ANALYTICS),_o=V(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),bo=gr(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),ve={isDevMode:yr,isRepoMode:Qe,CI:!!process.env.CI,checksumRootFolderBypass:Qe&&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??(yr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Ee+"/checksumlib.js"},runtimeRoot:Ee,playwrightReporter:{htmlReportTemplatePath:Eo},bypassProxyForLocalhost:V(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:V(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:V(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{headless:!V(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:V(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:bo},monitoring:{debugAnalytics:To,logToConsole:_o,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:V(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:V(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:V(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:V(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:V(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 Il=require("@playwright/test/reporter");var ce=require("path");var rt=s((e,t,r)=>`v2:${So(e)}::${JSON.stringify([...t,r])}`,"computeVariantKey"),So=s(e=>(e??"").replace(/\\/g,"/"),"normalizeFilePath");var Ne=require("fs"),B=oe(require("typescript"));var nt=5,le={mint(){return It(nt)},parse(e){let t=le.tryParse(e);if(t===null)throw new TypeError(`Not a usable checksumTestId: ${JSON.stringify(e)}`);return t},tryParse(e){return typeof e!="string"||e.trim()===""?null:e},isSame(e,t){return e===t}};var Tr=" - ",_r=/(?:\.fix)?\.checksum\.(?:(?:spec|test)\.(?:ts|js|tsx|jsx)|md)$/i,Io=/^[A-Za-z0-9_-]+$/,Ro=new RegExp(`^[0-9A-Za-z]{${nt}}$`);function br(e){return Ao(e).id}s(br,"readTestIdFromFileName");function Ao(e){let t=Mo(e);if(t===null)return{title:Sr(e),id:null};let r=t.lastIndexOf(Tr);if(r===-1)return{title:t,id:Ro.test(t)?le.tryParse(t):null};let n=t.slice(r+Tr.length);return Io.test(n)?{title:t.slice(0,r),id:le.tryParse(n)}:{title:t,id:null}}s(Ao,"splitFileName");function Sr(e){let t=e.replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1)}s(Sr,"basename");function Mo(e){let t=Sr(e);return _r.test(t)?t.replace(_r,""):null}s(Mo,"stemOf");var ot=class{static{s(this,"FileContentReader")}read(t,r){if(!(!t||!(0,Ne.existsSync)(t)))try{let n=(0,Ne.readFileSync)(t,"utf-8"),o=B.createSourceFile(t,n,B.ScriptTarget.Latest,!0),a=new Map,i=s(c=>{if(B.isCallExpression(c)&&this.isTestCall(c.expression)){let d=c.arguments[0];if(d&&B.isCallExpression(d)&&B.isIdentifier(d.expression)&&d.expression.text==="defineChecksumTest"){let m=this.extractDefineChecksumTestArgs(d);m&&a.set(m.testTitle,m.checksumTestId)}}B.forEachChild(c,i)},"visit");return i(o),r&&a.has(r)?a.get(r):a.size>0?Array.from(a.values())[0]:void 0}catch{return}}isTestCall(t){return B.isIdentifier(t)&&t.text==="test"?!0:B.isPropertyAccessExpression(t)?B.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),i=le.tryParse(this.extractStringLiteral(o));if(a&&i)return{testTitle:a,checksumTestId:i}}extractStringLiteral(t){if(B.isStringLiteral(t)||B.isNoSubstitutionTemplateLiteral(t))return t.text}},Co=new ot;function Ir(e,t){return Co.read(e,t)??br(e)??void 0}s(Ir,"extractChecksumTestId");function we(e,t){return t.pwTestIdToChecksumTestId[e.playwrightTestId]||(e.filePath!==void 0?Ir(e.filePath,e.title):void 0)}s(we,"resolveChecksumTestId");var Rr=s((e,t)=>Object.values(t[e]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),st=s(e=>typeof e=="number"&&!isNaN(e)?e:0,"getStat");function it(e,t,r){let n=[],o=0,a=0,i=st(t.expected)+st(t.flaky),c=st(t.unexpected);for(let d of e){let m=xo(d,r);n.push(m),m.recovered&&a++,m.bug&&(o++,m.outcome==="expected"||m.outcome==="flaky"?i--:m.outcome==="unexpected"&&c--)}return{passed:i,failed:c,bug:o,recovered:a,tests:n}}s(it,"computeReportStats");function xo(e,t){let r=we({playwrightTestId:e.playwrightTestId,filePath:e.filePath,title:e.title},t),n=vo(e),o=No(e.annotations),a=Rr(e.playwrightTestId,t.playwrightIdToMetadata),i=wo(r,e,t),c=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:rt(e.filePath,e.titlePath,e.title),...e.filePath!==void 0?{filePath:e.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...e.projectName?{project:e.projectName}:{},...e.errorMessage?{errorMessage:e.errorMessage}:{},...i!==void 0?{usingChecksumTestIdPlaceholder:i}:{}}}s(xo,"rowToTestWithMetadata");function Ar(e,t){let r=e.files,n=s(c=>{let m=we({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},t)??`${c.location.file}::${c.title}`,h=rt(c.location.file,c.path??[],c.title);return`${m}::${c.projectName}::${h}`},"keyFor"),o=new Map;for(let c of r)for(let d of c.tests)o.set(n(d),d);let a=new Set(o.values()),i={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(d=>a.has(d));for(let d of c.tests)i.total++,d.outcome==="expected"?i.expected++:d.outcome==="unexpected"?i.unexpected++:d.outcome==="flaky"?i.flaky++:i.skipped++}e.files=r.filter(c=>c.tests.length>0),e.stats={...e.stats,...i}}s(Ar,"dedupeReportByChecksumTestId");var vo=s(e=>e.tags.includes("bug")||e.annotations.some(t=>t.type==="bug")||e.title.includes("@bug"),"detectBug"),No=s(e=>e.filter(t=>!!t?.type).map(t=>({type:t.type,description:t.description||""})),"normalizeAnnotations"),wo=s((e,t,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[t.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[e]||!1},"computeUsingPlaceholder");var Mr=s((e,t,r)=>{if(!e)return;let n=r||t,o;if((0,ce.isAbsolute)(e))o=e;else{let a=(0,ce.dirname)(t);o=(0,ce.resolve)(a,e)}return o.replace(n+"/","")},"toRelativeFilePath");var Cr=require("node:util");var de=8*1024,Te=`
|
|
4
|
+
\u2026 [truncated]`,Do=/[\u001b\u0080-\u009f]/g;function at(e){let t=e.replaceAll("\0","");return Lo((0,Cr.stripVTControlCharacters)(t))}s(at,"sanitizeTestErrorMessage");function Lo(e){return e.replace(Do,"")}s(Lo,"removeResidualVTControls");function De(e){let t=at(e);if(Buffer.byteLength(t,"utf8")<=de)return{value:t,truncated:!1};let r=de-Buffer.byteLength(Te,"utf8"),n="",o=0;for(let a of t){let i=Buffer.byteLength(a,"utf8");if(o+i>r)break;n+=a,o+=i}return{value:n+Te,truncated:!0}}s(De,"boundTestErrorMessage");var vr=require("node:crypto");var Oo=new Set(["failed","timedOut","interrupted"]),lt=new WeakMap;function Nr(){let e={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return lt.set(e,new Map),e}s(Nr,"createErrorDetailIndex");function wr(e,t){try{let r=Po(e);if(!r||Uo(r.tests))return!1;for(let n of r.tests){if(!ue(n))continue;let o=Ur(n.projectName),a=n.testId;if(o===void 0||!Le(a))continue;let i=Fo(n);if(!i)continue;let c=Bo(i);c.truncated&&(t.truncatedCount+=1),Wo(t,Pr(r.fileId,o,a),c.value,Go(i))}return!0}catch{return!1}}s(wr,"addTestFileErrorDetails");function Dr(e){return ue(e)&&Object.prototype.hasOwnProperty.call(e,"fileId")&&Object.prototype.hasOwnProperty.call(e,"tests")}s(Dr,"isTestFileErrorDetailCandidate");function Lr(e,t,r,n){let o=Ur(r);if(!Le(t)||o===void 0||!Le(n))return;let a=Pr(t,o,n);if(!e.ambiguousKeys.has(a))return e.messages.get(a)}s(Lr,"getTestErrorMessage");function Po(e){if(!ue(e))return;let t=e.fileId,r=e.tests;if(!(!Le(t)||!Array.isArray(r)))return{fileId:t,tests:r}}s(Po,"parseTestFile");function Uo(e){return e.length>0&&!e.some(ue)}s(Uo,"hasOnlyMalformedTests");function Fo(e){let t=e.results;if(!Array.isArray(t))return;let r=t.at(-1);if(!ue(r))return;let n=r.status;if(typeof n!="string"||!Oo.has(n))return;let o=r.errors;if(Array.isArray(o))for(let a of o){let i=ko(a);if(i)return i}}s(Fo,"extractFinalErrorDetail");function ko(e){if(typeof e=="string"){let n=Or(e);return n?{message:n}:void 0}if(!ue(e))return;let t=xr(e.message,e.value),r=xr(e.codeframe,e.snippet);return t?!r||t.includes(r)?{message:t}:{message:t,frame:r}:r?{frame:r}:void 0}s(ko,"normalizeError");function Bo(e){let{message:t,frame:r}=e;if(!t)return De(r??"");if(!r)return De(t);let n=Buffer.byteLength(t,"utf8");if(n>de)return De(t);let o=`
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
`)}a(Un,"getBufferString");var $="0123456789abcdef".split(""),Ym=[-2147483648,8388608,32768,128],Ye=[24,16,8,0],$n=[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]|=Ym[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+$n[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+$n[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+$n[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+$n[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 uh=He(zn(),1);var qc=/^(?:[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 tn(t){return typeof t=="string"&&qc.test(t)}a(tn,"validate");function rn(t){if(!tn(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(rn,"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 dh=new Uint8Array(16);function nn(){return crypto.getRandomValues(dh)}a(nn,"rng");function fh(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(fh,"f");function vs(t,e){return t<<e|t>>>32-e}a(vs,"ROTL");function Kc(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]=vs(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=vs(u,5)+fh(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=vs(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(Kc,"sha1");function ph(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(ph,"stringToBytes");var Jc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Zc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yc(t,e,r,n,i,s){let o=typeof r=="string"?ph(r):r,c=typeof n=="string"?rn(n):n;if(typeof n=="string"&&(n=rn(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(Yc,"v35");function Ss(t,e,r,n){return Yc(80,Kc,t,e,r,n)}a(Ss,"v5");Ss.DNS=Jc;Ss.URL=Zc;var xs={};function Qc(t,e,r){let n;if(t)n=Xc(t.random??t.rng?.()??nn(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=nn();hh(xs,i,s),n=Xc(s,xs.msecs,xs.seq,e,r)}return e??xt(n)}a(Qc,"v7");function hh(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(hh,"updateV7State");function Xc(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(Xc,"v7Bytes");var st=Qc;var el=Symbol.for("ls:tracing_async_local_storage"),Ht=Symbol.for("lc:context_variables"),tl=a(t=>{globalThis[el]=t},"setGlobalAsyncLocalStorageInstance"),It=a(()=>globalThis[el],"getGlobalAsyncLocalStorageInstance");var gh=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),yh=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),_h=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),As=a(()=>typeof Deno<"u","isDeno"),bh=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!As(),"isNode"),wh=a(()=>{let t;return gh()?t="browser":bh()?t="node":yh()?t="webworker":_h()?t="jsdom":As()?t="deno":t="other",t},"getEnv"),Is;function rl(){return Is===void 0&&(Is={library:"langchain-js",runtime:wh()}),Is}a(rl,"getRuntimeEnvironment");function Xe(t){try{return typeof process<"u"?process.env?.[t]:As()?Deno?.env.get(t):void 0}catch{return}}a(Xe,"getEnvironmentVariable");var Eh=class{static{a(this,"BaseCallbackHandlerMethodsClass")}};var _r=class extends Eh{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,us(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}},nl=a(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var il=/^(?:[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 Th(t){return typeof t=="string"&&il.test(t)}a(Th,"validate");var sn=Th;function vh(t){if(!sn(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(vh,"parse");var Gn=vh;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 Sh=new Uint8Array(16);function wr(){return crypto.getRandomValues(Sh)}a(wr,"rng");function xh(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Ih(t,e,r)}a(xh,"v4");function Ih(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(Ih,"_v4");var zt=xh;function Ah(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(Ah,"f");function Cs(t,e){return t<<e|t>>>32-e}a(Cs,"ROTL");function Ch(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]=Cs(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=Cs(u,5)+Ah(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=Cs(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(Ch,"sha1");var sl=Ch;function Rh(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(Rh,"stringToBytes");var Rs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Os="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function ks(t,e,r,n,i,s){let o=typeof r=="string"?Rh(r):r,c=typeof n=="string"?Gn(n):n;if(typeof n=="string"&&(n=Gn(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(ks,"v35");function Ms(t,e,r,n){return ks(80,sl,t,e,r,n)}a(Ms,"v5");Ms.DNS=Rs;Ms.URL=Os;var Ps=Ms;var Ns={};function Oh(t,e,r){let n;if(t)n=al(t.random??t.rng?.()??wr(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=wr();kh(Ns,i,s),n=al(s,Ns.msecs,Ns.seq,e,r)}return e??br(n)}a(Oh,"v7");function kh(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(kh,"updateV7State");function al(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(al,"v7Bytes");var Er=Oh;var ol="gen_ai.operation.name",cl="gen_ai.system",Ls="gen_ai.request.model",ll="gen_ai.response.model",Ds="gen_ai.usage.input_tokens",Us="gen_ai.usage.output_tokens",$s="gen_ai.usage.total_tokens",ul="gen_ai.request.max_tokens",dl="gen_ai.request.temperature",fl="gen_ai.request.top_p",pl="gen_ai.request.frequency_penalty",ml="gen_ai.request.presence_penalty",hl="gen_ai.response.finish_reasons",gl="gen_ai.prompt",yl="gen_ai.completion",_l="gen_ai.request.extra_query",bl="gen_ai.request.extra_body",wl="gen_ai.serialized.name",El="gen_ai.serialized.signature",Tl="gen_ai.serialized.doc",vl="gen_ai.response.id",Sl="gen_ai.response.service_tier",xl="gen_ai.response.system_fingerprint",Il="gen_ai.usage.input_token_details",Al="gen_ai.usage.output_token_details",Cl="langsmith.trace.session_id",Rl="langsmith.trace.session_name",Ol="langsmith.span.kind",kl="langsmith.trace.name",Ml="langsmith.metadata",Fs="langsmith.span.tags";var Pl="langsmith.request.streaming",Nl="langsmith.request.headers";var Bs="langsmith.usage_metadata";var Nh=a((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),Lh,Ll=Symbol.for("ls:fetch_implementation");var Dl=a(()=>globalThis[Ll]===void 0?!0:Lh??!1,"_shouldStreamForGlobalFetchImplementation"),Ul=a(t=>async(...e)=>{if(t||Z("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[Ll]??Nh)(...e);return(t||Z("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var an=a(()=>Z("PROJECT")??ye("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var $l={};function _e(t,e){let r=e?.code??t;$l[r]||($l[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"),Hl=O("0x9E3779B1"),zl=O("0x85EBCA77"),Dh=O("0xC2B2AE3D"),At=O("0x9E3779B185EBCA87"),Gt=O("0xC2B2AE3D27D4EB4F"),Gl=O("0x165667B19E3779F9"),Gs=O("0x85EBCA77C2B2AE63"),Uh=O("0x27D4EB2F165667C5"),$h=O("0x165667919E3779F9"),Fh=O("0x9FB21C651E98DF25");function Bh(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(Bh,"hexToBytes");var at=Bh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),vr=(O(1)<<O(128))-O(1),z=(O(1)<<O(64))-O(1),Kn=(O(1)<<O(32))-O(1),gt=64,Vl=gt/8,jh=8,Vn=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 js(t,e=0){return t[e]}a(js,"readUInt8");var Hh=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"),zh=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"),Gh=a((t,e)=>(t&Kn)*(e&Kn)&z,"XXH_mult32to64"),Sr=a(t=>{if(!t)throw new Error("Assert failed")},"assert");function Vh(t,e){return(t<<e|t>>O(32)-e)&Kn}a(Vh,"rotl32");function Wl(t,e,r){for(let n=0;n<Vl;n++){let i=Q(e,n*8),s=i^Q(r,n*8);t[n^1]+=i,t[n]+=Gh(s,s>>O(32))}return t}a(Wl,"XXH3_accumulate_512");function Fl(t,e,r,n){for(let i=0;i<n;i++)Wl(t,Y(e,i*gt),Y(r,i*8));return t}a(Fl,"XXH3_accumulate");function Wh(t,e){for(let r=0;r<Vl;r++){let n=Q(e,r*8),i=t[r];i=Hs(i,O(47)),i^=n,i*=Hl,t[r]=i&z}return t}a(Wh,"XXH3_scrambleAcc");function Wn(t,e){return ql(t[0]^Q(e,0),t[1]^Q(e,jh))}a(Wn,"XXH3_mix2Accs");function Bl(t,e,r){let n=r;return n+=Wn(t.slice(0),Y(e,0*Vn)),n+=Wn(t.slice(2),Y(e,4*Vn)),n+=Wn(t.slice(4),Y(e,8*Vn)),n+=Wn(t.slice(6),Y(e,12*Vn)),ot(n&z)}a(Bl,"XXH3_mergeAccs");function qh(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=Fl(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=Fl(t,Y(e,c*o),r,l),t=n(t,Y(e,e.byteLength-gt),Y(r,r.byteLength-gt-7))}return t}a(qh,"XXH3_hashLong");function Kh(t,e,r){let n=new BigUint64Array([Dh,At,Gt,Gl,Gs,zl,Uh,Hl]);Sr(t.length>128),n=qh(n,t,e,Wl,Wh),Sr(n.length*8==64);{let i=Bl(n,Y(e,11),O(t.byteLength)*At&z);return Bl(n,Y(e,e.byteLength-gt-11),~(O(t.byteLength)*Gt)&z)<<O(64)|i}}a(Kh,"XXH3_hashLong_128b");function ql(t,e){let r=t*e&vr;return r&z^r>>O(64)}a(ql,"XXH3_mul128_fold64");function jl(t,e,r){return ql((Q(t,0)^Q(e,0)+r)&z,(Q(t,8)^Q(e,8)-r)&z)}a(jl,"XXH3_mix16B");function qn(t,e,r,n,i){let s=t&z,o=t>>O(64)&z;return s+=jl(e,n,i),s^=Q(r,0)+Q(r,8),s&=z,o+=jl(r,Y(n,16),i),o^=Q(e,0)+Q(e,8),o&=z,o<<O(64)|s}a(qn,"XXH3_mix32B");function ot(t){return t^=t>>O(37),t*=$h,t&=z,t^=t>>O(32),t}a(ot,"XXH3_avalanche");function Jn(t){return t^=t>>O(33),t*=Gt,t&=z,t^=t>>O(29),t*=Gl,t&=z,t^=t>>O(32),t}a(Jn,"XXH3_avalanche64");function Jh(t,e,r){let n=t.byteLength;Sr(n>0&&n<=3);let i=O(js(t,n-1))|O(n<<8)|O(js(t,0)<<16)|O(js(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=(Vh(zh(i),O(13))^c)&z;return(Jn(l)&z)<<O(64)|Jn(o)}a(Jh,"XXH3_len_1to3_128b");function Hs(t,e){return t^t>>e}a(Hs,"xorshift64");function Zh(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),Hs(Hs(u&z,O(35))*Fh&z,O(28))|ot(u>>O(64))<<O(64)}}a(Zh,"XXH3_len_4to8_128b");function Yh(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&Kn)*(zl-O(1))<<O(64),l&=vr,l^=Hh(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(Yh,"XXH3_len_9to16_128b");function Xh(t,e){let r=t.byteLength;return Sr(r<=16),r>8?Yh(t,at,e):r>=4?Zh(t,at,e):r>0?Jh(t,at,e):Jn(e^Q(at,64)^Q(at,72))|Jn(e^Q(at,80)^Q(at,88))<<O(64)}a(Xh,"XXH3_len_0to16_128b");function zs(t){return~t+O(1)&z}a(zs,"inv64");function Qh(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=qn(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))*Gs+(O(t.byteLength)-r&z)*Gt;return o&=z,o=zs(ot(o)),s|o<<O(64)}a(Qh,"XXH3_len_17to128_128b");function eg(t,e,r){let n=O(t.byteLength)*At&z;for(let o=32;o<160;o+=32)n=qn(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=qn(n,Y(t,o-32),Y(t,o-16),Y(e,3+o-160),r);n=qn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),zs(r));let i=n+(n>>O(64))&z;i=ot(i);let s=(n&z)*At+(n>>O(64))*Gs+(O(t.byteLength)-r&z)*Gt;return s&=z,s=zs(ot(s)),i|s<<O(64)}a(eg,"XXH3_len_129to240_128b");function Kl(t,e=O(0)){let r=t.byteLength;return r<=16?Xh(t,e):r<=128?Qh(t,at,e):r<=240?eg(t,at,e):Kh(t,at,e)}a(Kl,"XXH3_128");function Jl(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(Jl,"xxh128ToBytes");var Zl=/^[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(!Zl.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 Zn(t){let e=typeof t=="string"?Date.parse(t):t;return Er({msecs:e,seq:0})}a(Zn,"uuid7FromTime");function Yl(t){if(!Zl.test(t))return null;let e=t[14];return parseInt(e,16)}a(Yl,"getUuidVersion");function tg(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(tg,"uuidToBytes");function rg(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(rg,"bytesToUuid");var ng=new TextEncoder;function ig(t){let e=ng.encode(t),r=Kl(e);return Jl(r)}a(ig,"_fastHash128");function xr(t,e){let r=`${t}:${e}`,n=ig(r),i=new Uint8Array(16);if(Yl(t)===7){let o=tg(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),rg(i)}a(xr,"nonCryptographicUuid7Deterministic");var Vs=a(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>Z(r)==="true"),"isEnvTracingEnabled");var qs=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Ws=Symbol.for("ls:tracing_async_local_storage"),sg=new qs,Ks=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Ws]??sg}initializeGlobalInstance(e){globalThis[Ws]===void 0&&(globalThis[Ws]=e)}},ag=new Ks;function Js(t=!1){let e=ag.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
6
|
+
`,a=Buffer.byteLength(o,"utf8"),i=Buffer.byteLength(r,"utf8");if(n+a+i<=de)return{value:`${t}${o}${r}`,truncated:!1};let c=a+Buffer.byteLength(Te,"utf8"),d=de-n;if(d<c)return{value:t,truncated:!0};let m=Ho(r,d-c);return{value:`${t}${o}${m}${Te}`,truncated:!0}}s(Bo,"boundNormalizedErrorDetail");function Ho(e,t){let r="",n=0;for(let o of e){let a=Buffer.byteLength(o,"utf8");if(n+a>t)break;r+=o,n+=a}return r}s(Ho,"utf8Prefix");function Go(e){let t=(0,vr.createHash)("sha256");return e.message&&t.update(e.message,"utf8"),e.message&&e.frame&&t.update(`
|
|
8
7
|
|
|
9
|
-
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}a(Js,"getCurrentRunTree");var De=He(require("node:fs"),1),Ue=He(require("node:fs/promises"),1),og=He(require("node:path"),1);var Qe=og;async function Yn(t){await Ue.mkdir(t,{recursive:!0})}a(Yn,"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 Xl(t){return Ue.readdir(t)}a(Xl,"readdir");async function Ql(t){return Ue.stat(t)}a(Ql,"stat");function Ar(t){return De.existsSync(t)}a(Ar,"existsSync");function eu(t){De.mkdirSync(t,{recursive:!0})}a(eu,"mkdirSync");function tu(t,e){De.writeFileSync(t,e)}a(tu,"writeFileSync");function ru(t,e){De.renameSync(t,e)}a(ru,"renameSync");function nu(t){De.unlinkSync(t)}a(nu,"unlinkSync");function Vt(t){return De.readFileSync(t,"utf-8")}a(Vt,"readFileSync");async function iu(t){await Ue.mkdir(t,{mode:448})}a(iu,"mkdirExclusive");function su(t){try{return De.statSync(t).mtimeMs}catch{return}}a(su,"statMtimeMs");async function Xn(t){await Ue.rm(t,{recursive:!0,force:!0})}a(Xn,"rmRecursive");function cg(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}a(cg,"isStale");var Qn=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)||eu(n);let i=`${e}.tmp`;try{tu(i,JSON.stringify({entries:r},null,2)),ru(i,e)}catch(s){throw Ar(i)&&nu(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())cg(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}},ei=new Qn;function au(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}a(au,"isAbortError");var on=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:on(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 ti="0.8.9";var ct,ug=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),dg=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),fg=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),lu=a(()=>typeof globalThis.Deno<"u","isDeno"),pg=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!lu(),"isNode"),cn=a(()=>ct||(typeof Bun<"u"?ct="bun":ug()?ct="browser":pg()?ct="node":dg()?ct="webworker":fg()?ct="jsdom":lu()?ct="deno":ct="other",ct),"getEnv"),Ys;function ri(){if(Ys===void 0){let t=cn(),e=hg();Ys={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:ti,...e}}return Ys}a(ri,"getRuntimeEnvironment");function Qs(){let t=mg(),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(Qs,"getLangSmithEnvVarsMetadata");function mg(){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(mg,"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 Xs;function hg(){if(Xs!==void 0)return Xs;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 Xs=e,e}a(hg,"getShas");function ou(){return ye("OTEL_ENABLED")==="true"||Z("OTEL_ENABLED")==="true"}a(ou,"getOtelEnabled");var cu=new Set(["langsmith","otel"]);function ni(t){if(t!==void 0)return t;let e=Z("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!cu.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...cu].sort().join(", ")}`);return ou()&&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 ou()?"otel":"langsmith"}a(ni,"resolveTracingMode");var ra=class{static{a(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&ni()==="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()}},na=class{static{a(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new ra})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},ia=class{static{a(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ea=Symbol.for("ls:otel_trace"),ta=Symbol.for("ls:otel_context"),uu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),gg=new na,yg=new ia,sa=class{static{a(this,"OTELProvider")}getTraceInstance(){return globalThis[ea]??gg}getContextInstance(){return globalThis[ta]??yg}initializeGlobalInstances(e){globalThis[ea]===void 0&&(globalThis[ea]=e.trace),globalThis[ta]===void 0&&(globalThis[ta]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[uu]=e}getDefaultOTLPTracerComponents(){return globalThis[uu]??void 0}},aa=new sa;function ii(){return aa.getTraceInstance()}a(ii,"getOTELTrace");function du(){return aa.getContextInstance()}a(du,"getOTELContext");function fu(){return aa.getDefaultOTLPTracerComponents()}a(fu,"getDefaultOTLPTracerComponents");var _g={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function bg(t){return _g[t]||t}a(bg,"getOperationName");function wg(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}a(wg,"isPrimitive");var si=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&&ii().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(Ol,r.run_type);let c=bg(r.run_type||"chain");e.setAttribute(ol,c)}"name"in r&&r.name&&e.setAttribute(kl,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Cl,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Rl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute(Ls,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Bs,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ds,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Us,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute($s,r.total_tokens),this.setInvocationParameters(e,r);let s=r.extra?.metadata||{};for(let[c,l]of Object.entries(s))l!=null&&e.setAttribute(`${Ml}.${c}`,wg(l)?String(l):JSON.stringify(l));let o=r.tags;if(o&&Array.isArray(o)?e.setAttribute(Fs,o.join(", ")):o&&e.setAttribute(Fs,String(o)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(wl,String(c.name)),c.signature&&e.setAttribute(El,String(c.signature)),c.doc&&e.setAttribute(Tl,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(cl,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(ul,n.max_tokens),n.temperature!==void 0&&e.setAttribute(dl,n.temperature),n.top_p!==void 0&&e.setAttribute(fl,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(pl,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(ml,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(Ls,n.model),n.stream!==void 0&&e.setAttribute(Pl,n.stream),n.extra_headers&&e.setAttribute(Nl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(_l,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(bl,JSON.stringify(n.extra_body))),e.setAttribute(gl,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(Ds,i[0]),e.setAttribute(Us,i[1]),e.setAttribute($s,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(ll,String(n.model)),n.id&&e.setAttribute(vl,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(hl,s.join(", "))}if(n.service_tier&&e.setAttribute(Sl,n.service_tier),n.system_fingerprint&&e.setAttribute(xl,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;e.setAttribute(Bs,JSON.stringify(s)),s.input_token_details&&e.setAttribute(Il,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(Al,JSON.stringify(s.output_token_details))}}e.setAttribute(yl,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 Eg=Object.prototype.toString,Tg=a(t=>Eg.call(t)==="[object Error]","isError"),vg=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 oa(t){if(!(t&&Tg(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:vg.has(r)}a(oa,"isNetworkError");function Sg(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(Sg,"validateRetries");function ai(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(ai,"validateNumberOption");var ca=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 xg(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(xg,"calculateDelay");function pu(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}a(pu,"calculateRemainingTime");async function Ig({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 ca)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),pu(n,c)<=0)throw s;let u=await i.shouldConsumeRetry(l),d=pu(n,c);if(d<=0||o<=0)throw s;if(s instanceof TypeError&&!oa(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=xg(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(Ig,"onAttemptFailure");async function la(t,e={}){if(e={...e},Sg(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,ai("factor",e.factor,{min:0,allowInfinity:!1}),ai("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),ai("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),ai("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 Ig({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}a(la,"pRetry");var oi=He(zn(),1),mu="default"in oi.default?oi.default.default:oi.default;var Ag=[408,425,429,500,502,503,504],ln=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 mu({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(()=>la(()=>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")&&!Ag.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 ua(t){return typeof t?._getType=="function"}a(ua,"isLangChainMessage");function da(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(da,"convertLangChainMessageToExample");var fa=a(function(){let{crypto:t}=globalThis;if(t?.randomUUID)return fa=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 Cg=/^[a-z][a-z0-9+.-]*:/i,hu=a(t=>Cg.test(t),"isAbsoluteURL"),Ae=a(t=>(Ae=Array.isArray,Ae(t)),"isArray"),pa=Ae;function Cr(t){return typeof t!="object"?{}:t??{}}a(Cr,"maybeObj");function ma(t){if(!t)return!0;for(let e in t)return!1;return!0}a(ma,"isEmptyObj");function gu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}a(gu,"hasOwn");var yu=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 _u=a(t=>{try{return JSON.parse(t)}catch{return}},"safeJSON");var bu=a(t=>new Promise(e=>setTimeout(e,t)),"sleep");var Ot="0.0.1";function Rg(){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(Rg,"getDetectedPlatform");var Og=a(()=>{let t=Rg();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":Eu(Deno.build.os),"X-Stainless-Arch":wu(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":Eu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":wu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=kg();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 kg(){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(kg,"getBrowserInfo");var wu=a(t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown","normalizeArch"),Eu=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"),Mg,Tu=a(()=>Mg??=Og(),"getPlatformHeaders");function vu(){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(vu,"getDefaultFetch");function Pg(...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(Pg,"makeReadableStream");function ha(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Pg({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}a(ha,"ReadableStreamFrom");async function Su(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(Su,"CancelReadableStream");var xu=a(({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ga="RFC3986",ya=a(t=>String(t),"default_formatter"),_a={RFC1738:a(t=>String(t).replace(/%20/g,"+"),"RFC1738"),RFC3986:ya},Iu="RFC1738";var ci=a((t,e)=>(ci=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ci(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 ba=1024,Au=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+=ba){let l=s.length>=ba?s.slice(c,c+ba):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===Iu&&(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 Cu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}a(Cu,"is_buffer");function wa(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(wa,"maybe_map");var Ru={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ou=a(function(t,e){Array.prototype.push.apply(t,Ae(e)?e:[e])},"push_to_array"),Dg,pe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Au,encodeValuesOnly:!1,format:ga,formatter:ya,indices:!1,serializeDate(t){return(Dg??=Function.prototype.call.bind(Date.prototype.toISOString))(t)},skipNulls:!1,strictNullHandling:!1};function Ug(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}a(Ug,"is_non_nullish_primitive");var Ea={};function ku(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(Ea))!==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(Ea)>"u"&&(T=0)}if(typeof u=="function"?S=u(e,S):S instanceof Date?S=y?.(S):r==="comma"&&Ae(S)&&(S=wa(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(Ug(S)||Cu(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=wa(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(Ea,v),Ou(C,ku(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(ku,"inner_stringify");function $g(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=ga;if(typeof t.format<"u"){if(!ci(_a,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=_a[r],i=pe.filter;(typeof t.filter=="function"||Ae(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Ru?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($g,"normalize_stringify_options");function Mu(t,e={}){let r=t,n=$g(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=Ru[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||Ou(o,ku(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(Mu,"stringify");function Pu(t){return Mu(t,{arrayFormat:"repeat"})}a(Pu,"stringifyQuery");var ui={off:0,error:200,warn:300,info:400,debug:500},Ta=a((t,e,r)=>{if(t){if(gu(ui,t))return t;Me(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ui))}`)}},"parseLogLevel");function un(){}a(un,"noop");function li(t,e,r){return!e||ui[t]>ui[r]?un:e[t].bind(e)}a(li,"makeLogFn");var Bg={error:un,warn:un,info:un,debug:un},Nu=new WeakMap;function Me(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Bg;let n=Nu.get(e);if(n&&n[0]===r)return n[1];let i={error:li("error",e,r),warn:li("warn",e,r),info:li("info",e,r),debug:li("debug",e,r)};return Nu.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 di(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(di,"defaultParseResponse");var jg=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},Lu=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)},dn,tr=class t extends Promise{static{a(this,"APIPromise")}constructor(e,r,n=di){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}),dn.set(this,void 0),jg(this,dn,e,"f")}_thenUnwrap(e){return new t(Lu(this,dn,"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(Lu(this,dn,"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)}};dn=new WeakMap;var Hg=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},zg=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)},fi,rr=class{static{a(this,"AbstractPage")}constructor(e,r,n,i){fi.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}),Hg(this,fi,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 zg(this,fi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fi=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},fn=class extends tr{static{a(this,"PagePromise")}constructor(e,r,n){super(e,r,async(i,s)=>new n(i,s.response,await di(i,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pi=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}}}},mi=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 hi=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 va=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 gi(t,e,r){return va(),new File(t,e??"unknown_file",r)}a(gi,"makeFile");function Du(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(Du,"getName");var Uu=a(t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function","isAsyncIterable");var $u=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"),Vg=a(t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&$u(t),"isFileLike"),Wg=a(t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function","isResponseLike");async function yi(t,e,r){if(va(),t=await t,Vg(t))return t instanceof File?t:gi([await t.arrayBuffer()],t.name);if(Wg(t)){let i=await t.blob();return e||=new URL(t.url).pathname.split(/[\\/]/).pop(),gi(await Sa(i),e,r)}let n=await Sa(t);if(e||=Du(t),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return gi(n,e,r)}a(yi,"toFile");async function Sa(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if($u(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Uu(t))for await(let r of t)e.push(...await Sa(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${qg(t)}`)}return e}a(Sa,"getBytes");function qg(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}a(qg,"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 Bu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}a(Bu,"encodeURIPath");var Fu=Object.freeze(Object.create(null)),Jg=a((t=Bu)=>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??Fu)??Fu)?.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
|
-
|
|
11
|
-
`)}
|
|
12
|
-
${o}
|
|
13
|
-
${f}`)}return o},"path"),"createPathTagFunction"),F=Jg(Bu);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",pi,{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",mi,{query:e,...r})}};var ju=Symbol("brand.privateNullableHeaders");function*Qg(t){if(!t)return;if(ju 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():pa(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=pa(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(Qg,"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 Qg(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{[ju]:!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",hi,{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 ay=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},Hu=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)},xa,Ia,_i,zu,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}={}){xa.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}),_i.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??Ia.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=Ta(s.logLevel,"ClientOptions.logLevel",this)??Ta($r("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??vu(),ay(this,_i,xu,"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 Pu(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ot}`}defaultIdempotencyKey(){return`stainless-node-retry-${fa()}`}makeStatusError(e,r,n,i){return Te.generate(e,r,n,i)}buildURL(e,r,n){let i=!Hu(this,xa,"m",zu).call(this)&&n||this.baseURL,s=hu(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ma(o)||!ma(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(on),g=Date.now();if(h instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Ct;let v=au(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 Su(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=>on(C).message),p=_u(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 fn(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 bu(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&&yu("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))}:{},...Tu()},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:ha(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)}:Hu(this,_i,"f").call(this,{body:e,headers:n})}};Ia=K,_i=new WeakMap,xa=new WeakSet,zu=a(function(){return this.baseURL!=="https://api.smith.langchain.com/"},"_Langsmith_baseURLOverridden");Object.defineProperty(K,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:Ia});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:yi});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 pn={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function Gu(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?pn.SMITHDB_ONLY:r&&n?pn.DUAL:pn.CLICKHOUSE_ONLY}a(Gu,"getQueryBackend");function wi(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(wi,"getInvalidPromptIdentifierMsg");var Aa=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}},Ca=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 Ei(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}a(Ei,"isLangSmithNotFoundError");function Vu(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}a(Vu,"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 Ca(i);if(t.status===409)throw new Aa(i);let s=new Error(i);throw s.status=t.status,s}a(L,"raiseForStatus");var Wu="ERR_CONFLICTING_ENDPOINTS",bi=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:Wu}),this.name="ConflictingEndpointsError"}};function qu(t){return typeof t=="object"&&t!==null&&t.code===Wu}a(qu,"isConflictingEndpointsError");function Ce(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(wi(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,s]=e.split("/",2);if(!i||!s)throw new Error(wi(t));return[i,s,n]}else{if(!e)throw new Error(wi(t));return["-",e,n]}}a(Ce,"parseHubIdentifier");var oy=10,cy=1e4,Ku="created_at";function ly(t){return new Promise(e=>setTimeout(e,t))}a(ly,"sleep");function uy(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}a(uy,"isEEXIST");function Ju(t){try{return Vt(Qe.join(t,Ku)).split(`
|
|
19
|
-
`)}catch{return}}a(Ju,"lockMetadataLines");function dy(t){let e=Ju(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return su(t)}a(dy,"lockCreatedAtMs");function fy(t){let e=Ju(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}a(fy,"lockOwner");async function py(t){let e=dy(t);return e===void 0||Date.now()-e<=cy?!1:(await Xn(t),!0)}a(py,"removeStaleLock");async function Zu(t,e){let r=`${t}.oauth.lock.lock`,n=Qe.dirname(r);n&&await Yn(n);let i=globalThis.crypto.randomUUID();for(;;){try{await iu(r)}catch(s){if(!uy(s))throw s;if(!await py(r)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await ly(Math.min(oy,Math.max(0,e-Date.now())))}continue}try{await Ir(Qe.join(r,Ku),`${new Date().toISOString()}
|
|
20
|
-
${i}
|
|
21
|
-
`)}catch(s){throw await Xn(r),s}break}return{async release(){fy(r)===i&&await Xn(r)}}}a(Zu,"acquireOAuthRefreshLock");var Ti="https://api.smith.langchain.com",my="langsmith-cli",hy=6e4,gy=1e4;function yy(){let t=cn();return t==="browser"||t==="webworker"}a(yy,"isBrowserLikeRuntime");function _y(){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(_y,"getProfileConfigPath");function by(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(by,"resolveProfileName");function wy(){if(yy())return;let t=_y();if(!(!t||!Ar(t)))try{let e=JSON.parse(Vt(t)),r=by(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}a(wy,"loadProfileState");function We(t){return t!=null&&t.trim()!==""}a(We,"hasValue");function Nt(t){return t?.trim().replace(/^["']|["']$/g,"")}a(Nt,"trimConfigValue");function Yu(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()+hy}a(Yu,"shouldRefreshProfileToken");function Ey(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(Ey,"normalizeConfigUrl");function Ty(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(Ty,"applyTokenResponse");function Xu(t){return t.reason??new Error("The operation was aborted.")}a(Xu,"getAbortReason");async function vy(t,e){if(!e)return t;if(e.aborted)throw Xu(e);let r,n=new Promise((i,s)=>{let o=a(()=>{s(Xu(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(vy,"waitForAbortSignal");function Qu(){let t=wy(),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 Ra(t):void 0}}a(Qu,"loadProfileClientConfig");var Ra=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=Sy(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Yu(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await vy(this.refreshPromise,r));let n=ed(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)??Ti,i=Date.now()+gy,s;try{if(s=await Zu(this.state.configPath,i),this.reloadProfile()&&!Yu(this.state.profile))return;let c=new URLSearchParams({grant_type:"refresh_token",client_id:my,refresh_token:this.state.profile.oauth?.refresh_token??r}),l=await e(`${Ey(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;Ty(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 Sy(t){let e=Nt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!Nt(t.oauth?.refresh_token))return ed(t)}a(Sy,"currentAuthHeaderFromProfile");function ed(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(ed,"authHeaderFromProfile");var td="[...]",xy={result:"[Circular]"},Si=[],Fr=[],Iy=new TextEncoder;function Ay(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}a(Ay,"defaultOptions");function vi(t){return Iy.encode(t)}a(vi,"encodeString");function rd(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(rd,"serializeWellKnownTypes");function Cy(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return rd(r)}}a(Cy,"createDefaultReplacer");function nd(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(nd,"estimateSerializedSize");function Re(t,e,r,n,i){try{let s=JSON.stringify(t,Cy(r),n);return vi(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
23
|
-
Context: ${e}`:""}`),vi("[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=Ay()),ka(t,"",0,[],void 0,0,i);let o;try{Fr.length===0?o=JSON.stringify(t,r,n):o=JSON.stringify(t,Ry(r),n)}catch{return vi("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Si.length!==0;){let c=Si.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return vi(o)}}a(Re,"serialize");function Oa(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),Si.push([n,r,e,i])):Fr.push([e,r,t]):(n[r]=t,Si.push([n,r,e]))}a(Oa,"setReplace");function ka(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){Oa(xy,t,e,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){Oa(td,t,e,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Oa(td,t,e,i);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)ka(t[c],c,c,n,t,s,o);else{t=rd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];ka(t[u],u,c,n,t,s,o)}}n.pop()}}a(ka,"decirc");function Ry(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(Ry,"replaceGetterValues");var id=require("node:worker_threads"),Ma=id.Worker,sd=!0;var Oy=`
|
|
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
|
-
`,Na=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(!sd||Ma===null)return this.disabled=!0,!1;try{let e=new Ma(Oy,{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()}},Pa=null;function ad(){return Pa===null&&(Pa=new Na),Pa}a(ad,"getSharedSerializeWorker");var ky=64*1024,My=2048;function od(t,e=ky,r=My){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(od,"hasLargeString");function Py(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(Py,"assertPullPublicPromptAllowed");function cd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}a(cd,"_ensureUTCTimestamp");function Br(t){return{...t,start_time:cd(t.start_time),end_time:cd(t.end_time)}}a(Br,"_normalizeRunTimestamps");function ld(t,e,r){if(r)return t;let n=ri(),i=e??Qs(),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(ld,"mergeRuntimeEnvIntoRun");var Ny=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"),Ly=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 Dy(t){let e=[];for await(let r of t)e.push(r);return e}a(Dy,"toArray");function xi(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}a(xi,"trimQuotes");var Uy=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 ud(t){return typeof t=="number"?Number(t.toFixed(4)):t}a(ud,"_formatFeedbackScore");function $y(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($y,"_checkBackendVersion");var Fy=24*1024*1024,md=1024*1024*1024,By=1e4,jy=100;function hd(t,e){new Headers({[t]:e})}a(hd,"assertValidHeader");function dd(t){for(let[e,r]of Object.entries(t??{}))hd(e,r)}a(dd,"assertValidHeaders");function fd(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){hd(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(fd,"normalizeHeaders");function Hy(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(Hy,"mergeCallerHeaders");var La=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??md}peek(){return this.items[0]}push(e){let r,n=new Promise(s=>{r=s}),i=nd(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||Ul(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(!od(e))return Re(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=ad()),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=Ny(e.tracingSamplingRate),this.apiUrl=xi(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=xi(e.apiKey??r.apiKey);if(this.apiKey=We(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=xi(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=xi(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new ln({...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??md;this.batchIngestCaller=new ln({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Uy,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 La(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=fd(o),dd(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=ni(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new si),this.cachedLSEnvVarsForMetadata=Qs(),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=ei:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=ei)}static getDefaultClientConfig(){let e=Qu(),r=Z("API_KEY"),n=Z("ENDPOINT"),i=Z("WORKSPACE_ID"),s=We(r),o=n??e.apiUrl??Ti,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:Ly(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 Hy(fd(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${ti}`,...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){dd(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??Fy}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??jy}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 Yn(e),t._fallbackDirsCreated.add(e)),s!==void 0&&s>0)try{let f=(await Xl(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json")),y=0;for(let h of f){let{size:g}=await Ql(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(Ei(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=ld(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(By),...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=>{$y(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(Gu(r.instance_flags)===pn.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=ii(),r=du();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=ld(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;Dl()&&!this.multipartStreamingDisabled&&cn()!=="bun"?(u=!0,l=await c(o)):l=await c(s),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Ti&&(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(Ei(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 Dy(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(pd(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;pd(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=>ua(o)?da(o):o),s=ua(r)?da(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:ud(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=ud(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){Py(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(Ei(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(Vu(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 fu()?.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 pd(t){return"dataset_id"in t||"dataset_name"in t}a(pd,"isExampleCreate");var ft=Symbol.for("lc:context_variables");var Ii=Symbol.for("langsmith:replica_trace_roots");function Da(t,e){if(ft in t)return t[ft][e]}a(Da,"getContextVar");function gd(t,e,r){let n=ft in t?t[ft]:{};n[e]=r,t[ft]=n}a(gd,"setContextVar");var mn=36,zy="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function yd(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Ps(r,zy)}a(yd,"getReplicaKey");function Gy(t){return t.replace(/[-:.]/g,"")}a(Gy,"stripNonAlphanumeric");function bd(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(bd,"getMicrosecondPrecisionDatestring");function Ua(t,e,r=1){let n=bd(t,r);return{dottedOrder:Gy(n)+e,microsecondPrecisionDatestring:n}}a(Ua,"convertToDottedOrderFormat");var Vy=new Set(["projectName","primary","updates","reroot"]);function Wy(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||Vy.has(r)&&(e[r]=t[r]);return e}a(Wy,"filterReplicaForHeaders");var Ai=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:Wy(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}),wd(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=bd(this.start_time,this.execution_order)),this.id||(this.id=Zn(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=Zy(this.replicas),!this.dotted_order){let{dottedOrder:c}=Ua(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:an(),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(Ky(u)){let y={...u},h=qy(y.callbacks)?y.callbacks.copy?.():void 0;h&&(Object.assign(h,{_parentRunId:s.id}),h.handlers?.find(Ed)?.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(-mn)===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(-mn):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Da(this,Ii)??{};n[e]=r,gd(this,Ii,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=yd({projectName:r,apiUrl:l,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(S,f.id)}let y;if(!o){let S=Da(this,Ii)??{},p=yd({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(-mn)===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(-mn),C=xr(I,r);return T.slice(0,-mn)+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=ri();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=Vs();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=Ai.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 Ai(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 wd(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}a(wd,"isRunTree");function Ed(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}a(Ed,"isLangChainTracerLike");function _d(t){return Array.isArray(t)&&t.some(e=>Ed(e))}a(_d,"containsLangChainTracerLike");function qy(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}a(qy,"isCallbackManagerLike");function Ky(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(_d(e?.handlers)||_d(e))}a(Ky,"isRunnableConfigLike");function Jy(){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){Yy(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(qu(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(Jy,"_getWriteReplicasFromEnv");function Zy(t){let e=t?t.map(r=>Array.isArray(r)?{projectName:r[0],updates:r[1]}:r):Jy();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}a(Zy,"_ensureWriteReplicas");function Yy(t){if(Object.keys(t).length>0&&Z("ENDPOINT"))throw new bi}a(Yy,"_checkEndpointEnvUnset");var Xy=a(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Fa(t,e){if(t)return new et({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Fa(e),child_runs:t.child_runs.map(r=>Fa(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:rl()},tracingEnabled:!1})}a(Fa,"convertRunToRunTree");function $a(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}a($a,"_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?Xy(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}=Ua(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=Fa(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=$a(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=$a(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=$a(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 vd={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 Td(t){return typeof t=="string"?t.trim():t==null?t:qe(t,t.toString())}a(Td,"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}=vd,Ba=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(vd.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: "${Td(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: "${Td(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 ja,Ha=a(()=>(ja===void 0&&(ja=new Rt(Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),ja),"getDefaultLangChainClientSingleton");var xd=new Set(["ls_agent_type"]);function Qy(t){let e;for(let r of t)for(let n of r)St.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Nn(e,n.message.usage_metadata));return e}a(Qy,"_getUsageMetadataFromGenerations");var hn=class za 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??an(),this.replicas=s,this.exampleId=r,this.client=i??Ha(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];let l=za.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Sd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Sd(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=Qy(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)||xd.has(o))&&(n[o]=c)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new za({...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 Js(!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 Sd(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)||xd.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(Sd,"_patchMissingTracingDefaults");var Ci=He(zn(),1);var gn;function e_(){return new("default"in Ci.default?Ci.default.default:Ci.default)({autoStart:!0,concurrency:1})}a(e_,"createQueue");function t_(){return typeof gn>"u"&&(gn=e_()),gn}a(t_,"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 gn=t_(),gn.add(async()=>{let r=It();r!==void 0?await r.run(void 0,async()=>t()):await t()})}a(ne,"consumeCallback");var Id=a(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Xe(e)==="true"),"isTracingEnabled");function Ga(t){let e=It();if(e!==void 0)return e.getStore()?.[Ht]?.[t]}a(Ga,"getContextVariable");var r_=Symbol("lc:configure_hooks"),Ad=a(()=>Ga(r_)||[],"_getConfigureHooks");var n_=class{static{a(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Ri=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)))}},i_=class extends Ri{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)))}},Cd=class extends Ri{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)))}},s_=class extends Ri{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)))}},a_=class extends Ri{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 yn extends n_{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 Cd(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=Un(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 Cd(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 s_(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 a_(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 i_(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 yn(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 yn,l.setHandlers(e?.map(Va)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(Va):r?.handlers,!1));let u=Xe("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=hn.getTraceableRunTree(),f=d?.tracingEnabled??Id();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 yn),u&&!l.handlers.some(b=>b.name===Ba.prototype.name)){let b=new Ba;l.addHandler(b,!0)}if(y&&!l.handlers.some(b=>b.name==="langchain_tracer")&&f){let b=new hn;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 Ad()){let p=S&&Xe(S)==="true"&&v,T,I=b!==void 0?Ga(b):void 0;I&&nl(I)?T=I:p&&(T=new v({})),T!==void 0&&(l||(l=new yn),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 hn?b.copyWithTracingConfig({metadata:h,tags:g}):b),l.inheritableHandlers=l.inheritableHandlers.map(b=>b instanceof hn?b.copyWithTracingConfig({metadata:h,tags:g}):b)),l}};function Va(t){return"name"in t?t:_r.fromMethods(t)}a(Va,"ensureHandler");var Od=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},o_=new Od,Rd=Symbol.for("lc:child_config"),c_=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return It()??o_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Rd]}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,[Rd]: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&&tl(t)}},_n=new c_;var l_=Object.prototype.hasOwnProperty;function Pd(t,e){return l_.call(t,e)}a(Pd,"hasOwnProperty");function Nd(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)Pd(t,r)&&e.push(r);return e}a(Nd,"_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 ki(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(ki,"isInteger");function Ld(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(Ld,"unescapePathComponent");function Oi(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Oi(t[r]))return!0}else if(typeof t=="object"){let r=Nd(t),n=r.length;for(var e=0;e<n;e++)if(Oi(t[r[e]]))return!0}}return!1}a(Oi,"hasUndefined");function Md(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(Md,"patchErrorMessageFormatter");var Dd=class extends Error{static{a(this,"PatchError")}constructor(t,e,r,n,i){super(Md(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=Md(t,{name:e,index:r,operation:n,tree:i})}};var Ud=V({JsonPatchError:a(()=>se,"JsonPatchError"),_areEquals:a(()=>bn,"_areEquals"),applyOperation:a(()=>ur,"applyOperation"),applyPatch:a(()=>Ni,"applyPatch"),applyReducer:a(()=>f_,"applyReducer"),deepClone:a(()=>u_,"deepClone"),getValueByPointer:a(()=>Mi,"getValueByPointer"),validate:a(()=>$d,"validate"),validator:a(()=>Pi,"validator")}),se=Dd,u_=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=Mi(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=Mi(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:bn(t[e],this.value)}},"test"),_get:a(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},d_={add:a(function(t,e,r){return ki(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 Mi(t,e){if(e=="")return t;var r={op:"_get",path:e};return ur(t,r),r.value}a(Mi,"getValueByPointer");function ur(t,e,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Pi(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=Mi(t,e.from),e.op==="move"&&(o.removed=t),o;if(e.op==="test"){if(o.test=bn(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=Pi;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Ld(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&&!ki(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);ki(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=d_[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 Ni(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(Ni,"applyPatch");function f_(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(f_,"applyReducer");function Pi(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")&&Oi(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=$d([{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(Pi,"validator");function $d(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ni(wt(e),wt(t),r||!0);else{r=r||Pi;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($d,"validate");function bn(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(!bn(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],!bn(t[o],e[o]))return!1;return!0}return t!==t&&e!==e}a(bn,"_areEquals");({...Ud});var b$=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 b_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,w_=[0,31,28,31,30,31,30,31,31,30,31,30,31],E_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,T_=/^(?=.{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,v_=/^(?:[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,S_=/^(?:(?:[^\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,x_=/^(?:(?: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,I_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,A_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,C_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,R_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,O_=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"),k_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,M_=/^((([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,P_=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 N_={date:Fd,time:Bd.bind(void 0,!1),"date-time":U_,duration:P_,uri:B_,"uri-reference":pt(v_),"uri-template":pt(S_),url:pt(x_),email:O_,hostname:pt(T_),ipv4:pt(k_),ipv6:pt(M_),regex:H_,uuid:pt(I_),"json-pointer":pt(A_),"json-pointer-uri-fragment":pt(C_),"relative-json-pointer":pt(R_)};function L_(t){return t%4===0&&(t%100!==0||t%400===0)}a(L_,"isLeapYear");function Fd(t){let e=t.match(b_);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&L_(r)?29:w_[n])}a(Fd,"date");function Bd(t,e){let r=e.match(E_);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(Bd,"time");var D_=/t|\s/i;function U_(t){let e=t.split(D_);return e.length==2&&Fd(e[0])&&Bd(!0,e[1])}a(U_,"date_time");var $_=/\/|:/,F_=/^(?:[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 B_(t){return $_.test(t)&&F_.test(t)}a(B_,"uri");var j_=/[^\\]\\Z/;function H_(t){if(j_.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}a(H_,"regex");var jd;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(jd||(jd={}));var Qd=He(Xd(),1);var ib=Object.defineProperty,sb=a((t,e,r)=>e in t?ib(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),ab=a((t,e,r)=>(sb(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function ob(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(ob,"bytePairMerge");function cb(t,e){return t.length===1?[e.get(t.join(","))]:ob(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}a(cb,"bytePairEncode");function lb(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}a(lb,"escapeRegex");var Ya=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=Qd.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=Ya.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=Ya.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(...cb(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)}},Xa=Ya;ab(Xa,"specialTokenRegex",t=>new RegExp(t.map(e=>lb(e)).join("|"),"g"));var nf=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var sf=["image","video","audio","text-plain","file"];var fb=["text","reasoning",...nf,...sf];var wb=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:om,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 am(_){_.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(am,"newTag");function is(_,m){var R=_.indexOf(":")<0?["",_]:_.split(":"),x=R[0],J=R[1];return m&&_==="xmlns"&&(x="xmlns",J=""),{prefix:x,local:J}}a(is,"qname");function ss(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var m=is(_.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(ss,"attrib");function Ut(_,m){if(_.opt.xmlns){var R=_.tag,x=is(_.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=is(Ze,!0),Ft=xe.prefix,cm=xe.local,Fo=Ft===""?"":R.ns[Ft]||"",os={name:Ze,value:$t,prefix:Ft,local:cm,uri:Fo};Ft&&Ft!=="xmlns"&&!Fo&&(q(_,"Unbound namespace prefix: "+JSON.stringify(Ft)),os.uri=Ft),_.tag.attributes[Ze]=os,N(_,"onattribute",os)}_.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 as(_){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(as,"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 om(_){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:(am(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),as(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,ss(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}ss(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}ss(m),x===">"?Ut(m):m.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(m.tagName)x===">"?as(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===">"?as(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(om,"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"),Eb=wb();var h3=require("@playwright/test");var s3={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 yf=He(io());yf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var Hb="claude_4",zb={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}},Gb=a(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:Hb},models:zb,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=Gb();var f3={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 Qp=require("child_process"),An=require("crypto"),ce=require("fs"),em=require("fs/promises"),tm=require("stream/promises"),rm=require("http"),nm=He(require("net")),im=require("os"),Be=require("path");function Vb(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}a(Vb,"projectReportStatsForTelemetry");function _f(t,e,r){t.emit({outcome:e,stats:Vb(r)})}a(_f,"emitReportProcessingStatsTelemetry");var bf=["script","template"],wf='<script id="playwrightReportBase64" type="application/zip">',Ef="</script>";var xp=require("htmlparser2"),Ip=He(ep()),be=require("node:fs"),pr=require("node:path"),Ap=require("node:os"),Cp=require("node:crypto");var vt=He(require("path")),po=require("fs");var uo=require("path"),Hi=require("fs");function dw(t,e,r=10){let n=t;for(let i=0;i<r;i++){let s=(0,uo.join)(n,"package.json");if((0,Hi.existsSync)(s))try{if(JSON.parse((0,Hi.readFileSync)(s,"utf8")).name===e)return n}catch{}n=(0,uo.join)(n,"..")}}a(dw,"findRepositoryRoot");function tp(t,e=10){return dw(t,"checksum-customer-engineering-workspace",e)}a(tp,"findCustomerEngineeringRoot");var mo=He(io());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 rp(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}a(rp,"resolveMaxRRwebBytes");var fw=__dirname,np=vt.join(__dirname,".."),sp=(0,po.existsSync)(np)?np:fw;(0,mo.config)({path:vt.resolve(sp,".env")});var ip=Le(process.env.CHECKSUM_RUNTIME_DEV_MODE);function pw(){let t=__dirname;for(;!(0,po.existsSync)(vt.join(t,"package.json"));)t=vt.join(t,"..");return t}a(pw,"findRoot");var Sn=pw(),mw=tp(Sn,10);(0,mo.config)({path:[sp,mw].filter(t=>!!t).map(t=>vt.resolve(t,".env")),override:!1});var fo=Le(process.env.CHECKSUM_RUNTIME_REPO_MODE),hw=fo?vt.join(Sn,"package","pw-report-template.html"):vt.join(Sn,"pw-report-template.html"),gw=Le(process.env.CHECKSUM_DEBUG_ANALYTICS),yw=Le(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),_w=rp(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),zi={isDevMode:ip,isRepoMode:fo,CI:!!process.env.CI,checksumRootFolderBypass:fo&&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??(ip?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Sn+"/checksumlib.js"},runtimeRoot:Sn,playwrightReporter:{htmlReportTemplatePath:hw},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:_w},monitoring:{debugAnalytics:gw,logToConsole:yw,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 V5=require("@playwright/test/reporter");var qr=require("path");var ho=a((t,e,r)=>`v2:${bw(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),bw=a(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var Gi=require("fs"),he=He(require("typescript"));var go=5,Wr={mint(){return Ho(go)},parse(t){let e=Wr.tryParse(t);if(e===null)throw new TypeError(`Not a usable checksumTestId: ${JSON.stringify(t)}`);return e},tryParse(t){return typeof t!="string"||t.trim()===""?null:t},isSame(t,e){return t===e}};var ap=" - ",op=/(?:\.fix)?\.checksum\.(?:(?:spec|test)\.(?:ts|js|tsx|jsx)|md)$/i,ww=/^[A-Za-z0-9_-]+$/,Ew=new RegExp(`^[0-9A-Za-z]{${go}}$`);function cp(t){return Tw(t).id}a(cp,"readTestIdFromFileName");function Tw(t){let e=vw(t);if(e===null)return{title:lp(t),id:null};let r=e.lastIndexOf(ap);if(r===-1)return{title:e,id:Ew.test(e)?Wr.tryParse(e):null};let n=e.slice(r+ap.length);return ww.test(n)?{title:e.slice(0,r),id:Wr.tryParse(n)}:{title:e,id:null}}a(Tw,"splitFileName");function lp(t){let e=t.replace(/\\/g,"/");return e.slice(e.lastIndexOf("/")+1)}a(lp,"basename");function vw(t){let e=lp(t);return op.test(e)?e.replace(op,""):null}a(vw,"stemOf");var yo=class{static{a(this,"FileContentReader")}read(e,r){if(!(!e||!(0,Gi.existsSync)(e)))try{let n=(0,Gi.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&&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=Wr.tryParse(this.extractStringLiteral(i));if(s&&o)return{testTitle:s,checksumTestId:o}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},Sw=new yo;function up(t,e){return Sw.read(t,e)??cp(t)??void 0}a(up,"extractChecksumTestId");function Vi(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?up(t.filePath,t.title):void 0)}a(Vi,"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=xw(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 xw(t,e){let r=Vi({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=Iw(t),i=Aw(t.annotations),s=bo(t.playwrightTestId,e.playwrightIdToMetadata),o=Cw(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:ho(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(xw,"rowToTestWithMetadata");function dp(t,e){let r=t.files,n=a(c=>{let u=Vi({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=ho(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(dp,"dedupeReportByChecksumTestId");var Iw=a(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),Aw=a(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),Cw=a((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var fp=a((t,e,r)=>{if(!t)return;let n=r||e,i;if((0,qr.isAbsolute)(t))i=t;else{let s=(0,qr.dirname)(e);i=(0,qr.resolve)(s,t)}return i.replace(n+"/","")},"toRelativeFilePath");var pp=require("node:util");var Kr=8*1024,xn=`
|
|
158
|
-
\u2026 [truncated]`,Rw=/[\u001b\u0080-\u009f]/g;function Eo(t){let e=t.replaceAll("\0","");return Ow((0,pp.stripVTControlCharacters)(e))}a(Eo,"sanitizeTestErrorMessage");function Ow(t){return t.replace(Rw,"")}a(Ow,"removeResidualVTControls");function Wi(t){let e=Eo(t);if(Buffer.byteLength(e,"utf8")<=Kr)return{value:e,truncated:!1};let r=Kr-Buffer.byteLength(xn,"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+xn,truncated:!0}}a(Wi,"boundTestErrorMessage");var hp=require("node:crypto");var kw=new Set(["failed","timedOut","interrupted"]),To=new WeakMap;function gp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return To.set(t,new Map),t}a(gp,"createErrorDetailIndex");function yp(t,e){try{let r=Mw(t);if(!r||Pw(r.tests))return!1;for(let n of r.tests){if(!Jr(n))continue;let i=Tp(n.projectName),s=n.testId;if(i===void 0||!qi(s))continue;let o=Nw(n);if(!o)continue;let c=Dw(o);c.truncated&&(e.truncatedCount+=1),Fw(e,Ep(r.fileId,i,s),c.value,$w(o))}return!0}catch{return!1}}a(yp,"addTestFileErrorDetails");function _p(t){return Jr(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}a(_p,"isTestFileErrorDetailCandidate");function bp(t,e,r,n){let i=Tp(r);if(!qi(e)||i===void 0||!qi(n))return;let s=Ep(e,i,n);if(!t.ambiguousKeys.has(s))return t.messages.get(s)}a(bp,"getTestErrorMessage");function Mw(t){if(!Jr(t))return;let e=t.fileId,r=t.tests;if(!(!qi(e)||!Array.isArray(r)))return{fileId:e,tests:r}}a(Mw,"parseTestFile");function Pw(t){return t.length>0&&!t.some(Jr)}a(Pw,"hasOnlyMalformedTests");function Nw(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!Jr(r))return;let n=r.status;if(typeof n!="string"||!kw.has(n))return;let i=r.errors;if(Array.isArray(i))for(let s of i){let o=Lw(s);if(o)return o}}a(Nw,"extractFinalErrorDetail");function Lw(t){if(typeof t=="string"){let n=wp(t);return n?{message:n}:void 0}if(!Jr(t))return;let e=mp(t.message,t.value),r=mp(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}a(Lw,"normalizeError");function Dw(t){let{message:e,frame:r}=t;if(!e)return Wi(r??"");if(!r)return Wi(e);let n=Buffer.byteLength(e,"utf8");if(n>Kr)return Wi(e);let i=`
|
|
159
|
-
|
|
160
|
-
`,s=Buffer.byteLength(i,"utf8"),o=Buffer.byteLength(r,"utf8");if(n+s+o<=Kr)return{value:`${e}${i}${r}`,truncated:!1};let c=s+Buffer.byteLength(xn,"utf8"),l=Kr-n;if(l<c)return{value:e,truncated:!0};let u=Uw(r,l-c);return{value:`${e}${i}${u}${xn}`,truncated:!0}}a(Dw,"boundNormalizedErrorDetail");function Uw(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(Uw,"utf8Prefix");function $w(t){let e=(0,hp.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($w,"digestNormalizedErrorDetail");function wp(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(wp,"normalizeErrorText");function Fw(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(Fw,"addErrorDetail");function Ep(t,e,r){return JSON.stringify([t,e,r])}a(Ep,"createIdentityKey");function mp(...t){for(let e of t){if(typeof e!="string")continue;let r=wp(e);if(r)return r}}a(mp,"firstMeaningfulString");function Jr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(Jr,"isRecord");function Tp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}a(Tp,"normalizeProjectName");function qi(t){return typeof t=="string"&&t.length>0}a(qi,"isNonEmptyString");var Bw=a(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),jw=a(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function vp(t,e=8388608){let r=Bw(e),n=0,i=t.tests?.map(s=>{if(s.errorMessage===void 0)return s;let o=jw(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(vp,"applyErrorDetailsPayloadBudget");var Sp=a(t=>bf.includes(t),"isPayloadTag"),zw=a((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let i=e?bp(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"),Ki=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,Ap.tmpdir)(),`pw-report-${(0,Cp.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 xp.Parser({onopentag:a((h,g)=>{Sp(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(Sp(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 Ip.default(e),n=r.getEntries(),i=gp(),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);_p(b)&&!yp(b,i)&&(c+=1)}catch{c+=1}}}if(!s||!o)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&dp(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(wf+"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(Ef),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)(zi.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=wo(zw(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:a(s=>fp(s,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),i=vp(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=Vi({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"},Gw={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},gz=Object.fromEntries(Object.entries(Gw).map(t=>t.reverse())),Vw={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"},yz=Object.fromEntries(Object.entries(Vw).map(t=>t.reverse()));var _z={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]},bz={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 es=require("fs"),Wp=require("path"),qp=require("stream");var Rp=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 Op="\x1B[31m",Ww="\x1B[33m",qw="\x1B[32m",Kw="\x1B[36m",Jw="\x1B[2m",Zw="\x1B[1m",In="\x1B[0m",Yw=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"),Xw=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Qw=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"),e0=a(t=>t==="ERROR"||t==="CRITICAL"?Op:t==="WARNING"?Ww:qw,"colorForSeverity"),t0=a(t=>{let e=String(t.severity??"INFO"),r=`${e0(e)}${e.padEnd(5)}${In}`,n=t.kind?`${Kw}${t.kind}${In}`:"",i=String(t.message??""),s=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Op}${d.type??"Error"}: ${d.message??""}${In}`})():"",o=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,f])=>!Xw.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])=>`${Jw}${d}=${In}${f}`).join(" ");return[r,Zw+n+In,i,u,s].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),r0=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"),kp=a(t=>{let e=Yw()?t0(t):Qw(r0(t));(0,So.writeSync)(1,e+`
|
|
163
|
-
`)},"emitEvent");var Mp=a(t=>{(0,So.writeSync)(2,t.endsWith(`
|
|
164
|
-
`)?t:`${t}
|
|
165
|
-
`)},"writeStderrLine");var n0=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"),i0=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"),s0=a((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??n0,n=t.label??"[wide-event]",i=t.sink??(c=>kp(c)),s=a(c=>{if(!e(c))return;let l={severity:Rp(c),message:c.message??r(c),...c};try{i(l)}catch(u){try{Mp(`${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={})=>i0(c,l,s),"wideEvent"),configureSink:a(c=>{i=c},"configureSink")}},"createWideEvents"),Pp=a(t=>t==="true"||t==="1","truthy"),Np=a(()=>Pp(process.env.CHECKSUM_WIDE_EVENTS)||Pp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),xo=s0({decide:a(()=>Np(),"decide")}),Io=xo.configureSink,Zr=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 Lp(t,e){let r;try{r=await t.json()}catch{r=void 0}return a0({ok:t.ok,status:t.status,body:r},e)}a(Lp,"assertOkJson");function a0(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let i=o0(r?.message);throw c0(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(a0,"assertJsonBody");function o0(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}a(o0,"extractMessage");function c0(t,e){return Object.assign(t,{status:e})}a(c0,"withStatus");var Ji=a(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var Zi={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 l0(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(l0,"clampEnvInt");var u0=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function d0(t){let e={...t},r=[];for(let[n,i,s]of u0)for(let o of i){let c=Math.floor(e[n]*s);e[o]>c&&(r.push(`${Zi[o].env} (${e[o]}ms) exceeds its bound under ${Zi[n].env} (${e[n]}ms); using ${c}ms`),e[o]=c)}return{tunables:e,warnings:r}}a(d0,"coerceScopeHierarchy");function Ao(t){let e={};for(let r of Object.keys(Zi)){let n=Zi[r];e[r]=l0(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,d0(e)}a(Ao,"resolveUploadTunablesDetailed");function f0(t){return Ao(t).tunables}a(f0,"resolveUploadTunables");var Dp=f0({});var Up=new WeakMap,Co=new WeakMap;function $p(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,Up.set(t,t.committedBytes),Co.set(t,0)}a($p,"beginUpload");function Ro(t){t.loadedBytes=0,Co.set(t,0)}a(Ro,"resetAttemptBytes");var Fp=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"),p0=Fp(Co),m0=Fp(Up);function Oo(t,e,r,n){return t.loadedBytes=e,p0(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,m0(t,i,r,n)}a(ko,"recordCommitted");var Xi=require("fs"),jp=require("stream");function Yi(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(Yi,"jitteredBackoffMs");async function Yr(t){await t.body?.cancel().catch(()=>{})}a(Yr,"drainBody");var No=a(t=>t===200||t===201,"isStored"),Hp=a(t=>t===308,"isResumeIncomplete"),h0=a(t=>t===404||t===410,"isSessionGoneStatus"),zp=a((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),g0=a((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function y0(t,e,r){let n=e,i=new TransformStream({transform(s,o){n+=s.byteLength,r?.(n),o.enqueue(s)}});return jp.Readable.toWeb(t).pipeThrough(i)}a(y0,"countingBody");var rt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{a(this,"ResumableUploadError")}},Gp=a(t=>t instanceof rt?t.status:void 0,"statusOf"),_0=a(t=>{let e=Gp(t);return e!==void 0&&h0(e)},"isSessionGone"),b0=a(t=>Ji(Gp(t)),"isPermanent");async function w0(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 Yr(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(w0,"initResumableSession");async function E0(t,e,r,n){let i=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await Yr(i),No(i.status))return{done:!0,offset:e};if(!Hp(i.status))throw new rt(`offset query failed with status ${i.status}`,i.status);return{done:!1,offset:zp(i.headers.get("Range"),0)}}a(E0,"queryCommittedOffset");async function Bp(t,e,{offset:r,endExclusive:n},i){let s=Math.max(0,(0,Xi.statSync)(t.filePath).size-r),o=Math.min(Math.max(0,n-r),s),c=r+o,l=o>0?(0,Xi.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":g0(r,c,t.size),"Content-Length":String(o)},duplex:"half",signal:i,...l?{body:y0(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await Yr(d),No(d.status))return{stored:!0,committed:t.size};if(Hp(d.status))return{stored:!1,committed:zp(d.headers.get("Range"),r)};throw new rt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}a(Bp,"putChunk");async function T0(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 Bp(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 Bp(t,e,{offset:t.size,endExclusive:t.size},n);if(!s)throw new rt("resumable upload did not finalize");t.onCommitted?.(t.size)}a(T0,"sendFrom");async function v0(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new rt("no resumable target provided");return e.url=await w0(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}a(v0,"openSession");async function S0(t,e,r,n){if(!r)return 0;let i=await E0(e,t.size,t.fetchImpl,n);if(!i.done)return t.onCommitted?.(i.offset),i.offset}a(S0,"resumePoint");async function x0(t,e,r){let n=await v0(t,e,r),i=await S0(t,n,e.used,r);if(e.used=!0,i===void 0){t.onCommitted?.(t.size);return}await T0(t,n,i,r)}a(x0,"runAttempt");function I0(t,e,r){return _0(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):b0(t)?"stop":"retry"}a(I0,"afterFailure");async function Vp(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await x0(t,e,t.makeSignal());return}catch(i){if(r=i,I0(i,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(Yi(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new rt(`resumable upload failed: ${String(r)}`)}a(Vp,"uploadResumable");var A0=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"),C0=a(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),Qi=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??Dp,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=Zr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,Wp.basename)(r),test_id:e.info.testId,project:e.info.project}),s=[];try{let c=(0,es.statSync)(r).size;e.sizeBytes=c,$p(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=A0(f),d.error=tt(f);let y=Ji(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,es.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=qp.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 Yr(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()},C0(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 Vp({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=Yi(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 Lp(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 ts(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(ts,"isUploadStalled");function rs(t,e,r){return t!==void 0&&r-t>e}a(rs,"hasElapsedSinceTestEnd");function Kp(t,e,r){return rs(e.testRunEndTime,e.finalizeBudgetMs,r)?!0:t===void 0?!1:t.complete||t.error?!0:ts([t],e.stallTimeoutMs,r)}a(Kp,"shouldStopWaitingForReport");function Jp(t){return t.abandonedAssets.length===0}a(Jp,"mayCleanUpSources");function R0(t,e,r){if((e.length===0||ts(t.assets,t.stallTimeoutMs,r))&&rs(t.testRunEndTime,t.finalizeBudgetMs,r))return"budget";if(rs(t.testRunEndTime,t.finalizeCeilingMs,r))return"budget-ceiling"}a(R0,"backstopReason");function Zp(t,e){let r=t.assets.filter(s=>!s.complete&&!s.error),n=a(s=>({reason:s,abandonedAssets:r}),"decide"),i=R0(t,r,e);if(i!==void 0)return n(i);if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!ts(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!rs(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}a(Zp,"decideFinalize");var Yp=require("module");var O0=(0,Yp.createRequire)(__filename);function Xp(t){let e,r;try{e=O0("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(Xp,"createMonitorFetch");var Lo=class{static{a(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
|
|
8
|
+
`,"utf8"),e.frame&&t.update(e.frame,"utf8"),t.digest("hex")}s(Go,"digestNormalizedErrorDetail");function Or(e){let t=at(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,"")}s(Or,"normalizeErrorText");function Wo(e,t,r,n){if(e.ambiguousKeys.has(t))return;let o=lt.get(e);if(o||(o=new Map,lt.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)}s(Wo,"addErrorDetail");function Pr(e,t,r){return JSON.stringify([e,t,r])}s(Pr,"createIdentityKey");function xr(...e){for(let t of e){if(typeof t!="string")continue;let r=Or(t);if(r)return r}}s(xr,"firstMeaningfulString");function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ue,"isRecord");function Ur(e){return e==null||e===""?"":typeof e=="string"?e:void 0}s(Ur,"normalizeProjectName");function Le(e){return typeof e=="string"&&e.length>0}s(Le,"isNonEmptyString");var $o=s(e=>Number.isSafeInteger(e)&&e>=0?Math.min(e,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),zo=s(e=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(e)}`,"utf8"),"serializedErrorMessagePropertyBytes");function Fr(e,t=8388608){let r=$o(t),n=0,o=e.tests?.map(a=>{if(a.errorMessage===void 0)return a;let i=zo(a.errorMessage);if(i<=r)return r-=i,a;n+=1;let c={...a};return delete c.errorMessage,c});return{stats:{...e,...o!==void 0?{tests:o}:{}},omittedCount:n}}s(Fr,"applyErrorDetailsPayloadBudget");var kr=s(e=>Dt.includes(e),"isPayloadTag"),Ko=s((e,t)=>e.files.flatMap(r=>r.tests.map(n=>{let o=t?Lr(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"),Oe=class e{constructor(t,r,n,o={},a={},i,c,d,m={}){this.reportHTMLFilePath=t;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=o;this.channel=i;this.checksumTestIdToUsingPlaceholder=m;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...a},this.checksumRoot=c||(0,re.dirname)((0,re.dirname)(t)),this.projectRoot=d||this.checksumRoot}static{s(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let t=0;try{t=(0,H.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,re.join)((0,Gr.tmpdir)(),`pw-report-${(0,Wr.randomUUID)()}.zip`),n=s(()=>{try{(0,H.existsSync)(r)&&(0,H.unlinkSync)(r)}catch{}},"cleanupFile"),o={sigterm:s(()=>{n(),process.exit(143)},"sigterm"),sigint:s(()=>{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 i=Date.now()-a;this.channel.debug("Modifying ZIP file...");let c=Date.now(),d=this.modifyZipFile(r),m=Date.now()-c;this.channel.debug("Writing output HTML...");let h=Date.now();await this.writeOutputWithStreamedZip(r);let T=Date.now()-h;return{report_html_bytes:t,extract_ms:i,modify_ms:m,write_ms:T,entry_count:d.entryCount,json_entry_count:d.jsonEntryCount,largest_entry_bytes:d.largestEntryBytes,largest_entry_name:d.largestEntryName,error_details_extracted:d.errorDetailsExtracted,error_details_truncated:d.errorDetailsTruncated,error_detail_parse_failures:d.errorDetailParseFailures,error_detail_identity_conflicts:d.errorDetailIdentityConflicts,error_details_payload_budget_omitted:d.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",o.sigterm),process.removeListener("SIGINT",o.sigint),process.removeListener("exit",o.exit);try{(0,H.existsSync)(r)&&(0,H.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,i=!1,c=[],d=0,m=(0,H.createWriteStream)(t);m.on("error",_=>{if(!a){a=!0;try{R.destroyed||R.destroy(),T.end()}catch{}n(_)}});let h=s(()=>{if(d<4)return;let _=c.join("");c.length=0,i||(_=_.replace("data:application/zip;base64,",""),i=!0);let p=Math.floor(_.length/4)*4,f=_.slice(0,p),u=_.slice(p);if(u.length>0?(c.push(u),d=u.length):d=0,f.length>0){let y=Buffer.from(f,"base64");m.write(y)}},"flushBuffer"),T=new Br.Parser({onopentag:s((_,p)=>{kr(_)&&p.id==="playwrightReportBase64"&&(o=!0)},"onopentag"),ontext:s(_=>{o&&(c.push(_),d+=_.length,d>1024*1024&&h())},"ontext"),onclosetag:s(_=>{if(kr(_)&&o&&!a){if(a=!0,d>0){let p=c.join("");if(i||(p=p.replace("data:application/zip;base64,","")),p.length>0){let f=Buffer.from(p,"base64");m.write(f)}}try{R.destroyed||R.destroy()}catch{}m.end(()=>r())}},"onclosetag"),onerror:s(_=>{if(!a){a=!0;try{T.end(),R.destroyed||R.destroy(),m.destroyed||m.destroy()}catch{}n(_)}},"onerror")}),R=(0,H.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});R.on("data",_=>T.write(_.toString())),R.on("end",()=>{if(T.end(),!a){a=!0;try{m.destroyed||m.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),R.on("error",_=>{if(!a){a=!0;try{T.end(),m.destroyed||m.destroy()}catch{}n(_)}})})}modifyZipFile(t){let r=new Hr.default(t),n=r.getEntries(),o=Nr(),a,i,c=0,d=0,m=0,h="";for(let R of n){if(R.isDirectory||!R.entryName.endsWith(".json"))continue;let _=R.getData().toString("utf8");if(d+=1,_.length>m&&(m=_.length,h=R.entryName),R.entryName==="report.json")a=JSON.parse(_),i=R;else{let p=this.replaceAttachmentPaths(_);R.setData(Buffer.from(p,"utf8"));try{let f=JSON.parse(p);Dr(f)&&!wr(f,o)&&(c+=1)}catch{c+=1}}}if(!a||!i)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&Ar(a,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(a),this.report=a;let T=this.extractStats(a,o);return i.setData(Buffer.from(JSON.stringify(a),"utf8")),r.writeZip(t),{entryCount:n.length,jsonEntryCount:d,largestEntryBytes:m,largestEntryName:h,errorDetailsExtracted:o.messages.size,errorDetailsTruncated:o.truncatedCount,errorDetailParseFailures:c,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,H.copyFileSync)(n,o);let a=(0,H.createWriteStream)(n);await new Promise((i,c)=>{a.on("error",c),a.write(r),a.write(Lt+"data:application/zip;base64,");let d=(0,H.createReadStream)(t,{highWaterMark:3*1024*1024});d.on("data",m=>{let T=(typeof m=="string"?Buffer.from(m):m).toString("base64");a.write(T)||d.pause()}),a.on("drain",()=>{d.resume()}),d.on("end",()=>{a.write(Ot),a.end(()=>i())}),d.on("error",m=>{try{a.destroyed||a.destroy()}catch{}c(m)}),a.on("error",m=>{try{d.destroyed||d.destroy()}catch{}c(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=s(a=>a.some(i=>i.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let a of this.report.files)for(let i of a.tests)if(i.testId===n&&i.projectName===r&&o(i.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,H.readFileSync)(ve.playwrightReporter.htmlReportTemplatePath,"utf-8")),e.templateCache}getReportsStats(){return this.stats}extractStats(t,r){if(!t.stats)return 0;let n=it(Ko(t,r),t.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:s(a=>Mr(a,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),o=Fr(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,re.basename)(t)}`:t}handleReportJSON(t){let r={},n=s(o=>{let a=o.testId,i=this.playwrightIdToMetadata[a];i&&(r[a]=i);let c=we({playwrightTestId:o.testId,filePath:o.location.file,title:o.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(o.checksumTestId=c),o.results.forEach(d=>{this.processAttachments(d.attachments)})},"getChecksumMetadataForPWTestId");t.files.forEach(o=>{o.tests.forEach(n)}),t.checksumMetadata=r}processAttachments(t){t.forEach(n=>this.updateAttachment(n));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 ct={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},jl={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},jo={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"},Zl=Object.fromEntries(Object.entries(jo).map(e=>e.reverse()));var Jl={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 He=require("fs"),an=require("path"),ln=require("stream");var $r=s(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 dt=require("fs");var zr="\x1B[31m",Zo="\x1B[33m",Jo="\x1B[32m",Yo="\x1B[36m",qo="\x1B[2m",Xo="\x1B[1m",_e="\x1B[0m",Qo=s(()=>{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"),es=new Set(["severity","message","kind","timestamp","_startedAtMs"]),ts=s(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"),rs=s(e=>e==="ERROR"||e==="CRITICAL"?zr:e==="WARNING"?Zo:Jo,"colorForSeverity"),ns=s(e=>{let t=String(e.severity??"INFO"),r=`${rs(t)}${t.padEnd(5)}${_e}`,n=e.kind?`${Yo}${e.kind}${_e}`:"",o=String(e.message??""),a=e.error&&typeof e.error=="object"?(()=>{let h=e.error;return` ${zr}${h.type??"Error"}: ${h.message??""}${_e}`})():"",i=["outcome","test_suite_run_id","status"],c=Object.entries(e).filter(([h,T])=>!es.has(h)&&T!=null&&h!=="error"&&typeof T!="object"),d=s(h=>{let T=i.indexOf(h);return T===-1?i.length:T},"rank"),m=c.sort(([h],[T])=>d(h)-d(T)).slice(0,8).map(([h,T])=>`${qo}${h}=${_e}${T}`).join(" ");return[r,Xo+n+_e,o,m,a].filter(h=>h&&h.trim()!=="").join(" ")},"formatPretty"),os=s(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"),Vr=s(e=>{let t=Qo()?ns(e):ts(os(e));(0,dt.writeSync)(1,t+`
|
|
9
|
+
`)},"emitEvent");var Kr=s(e=>{(0,dt.writeSync)(2,e.endsWith(`
|
|
10
|
+
`)?e:`${e}
|
|
11
|
+
`)},"writeStderrLine");var ss=s(e=>{let t=e.kind??"event",r=e.outcome?` ${e.outcome}`:"",n=typeof e.duration_ms=="number"?` ${e.duration_ms}ms`:"";return`${t}${r}${n}`.trim()},"defaultMessage"),is=s((e,t,r)=>{let n=Date.now(),o={timestamp:new Date().toISOString(),kind:e,...t},a=!1,i={set(c){return Object.assign(o,c),i},emit(c){a||(a=!0,c&&Object.assign(o,c),o.duration_ms===void 0&&(o.duration_ms=Date.now()-n),r(o))}};return i},"startHandle"),as=s((e={})=>{let t=e.decide??(()=>!0),r=e.deriveMessage??ss,n=e.label??"[wide-event]",o=e.sink??(c=>Vr(c)),a=s(c=>{if(!t(c))return;let d={severity:$r(c),message:c.message??r(c),...c};try{o(d)}catch(m){try{Kr(`${n} emit failed: ${String(m)}`)}catch{}}},"emit");return{emit:a,emitWideEvent:s((c,d={})=>{a({timestamp:new Date().toISOString(),kind:c,...d})},"emitWideEvent"),wideEvent:s((c,d={})=>is(c,d,a),"wideEvent"),configureSink:s(c=>{o=c},"configureSink")}},"createWideEvents"),jr=s(e=>e==="true"||e==="1","truthy"),Zr=s(()=>jr(process.env.CHECKSUM_WIDE_EVENTS)||jr(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),ut=as({decide:s(()=>Zr(),"decide")}),pt=ut.configureSink,pe=s((e,t={})=>ut.wideEvent(e,t),"wideEvent"),ne=s((e,t={})=>{ut.emitWideEvent(e,t)},"emitWideEvent"),J=s(e=>e instanceof Error?{type:e.name,message:e.message}:{type:"UnknownError",message:String(e)},"toErrorField");async function Jr(e,t){let r;try{r=await e.json()}catch{r=void 0}return ls({ok:e.ok,status:e.status,body:r},t)}s(Jr,"assertOkJson");function ls(e,t){let r=e.body&&typeof e.body=="object"?e.body:void 0;if(!e.ok){let o=cs(r?.message);throw ds(new Error(`${t.resource} failed (HTTP ${e.status})`+(o?`: ${o}`:".")),e.status)}if(!r)throw new Error(`${t.resource} (HTTP ${e.status}) returned a non-object body; expected JSON.`);let n=(t.requiredFields??[]).filter(o=>!r[o]);if(n.length>0)throw new Error(`${t.resource} (HTTP ${e.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}s(ls,"assertJsonBody");function cs(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join("; "):""}s(cs,"extractMessage");function ds(e,t){return Object.assign(e,{status:t})}s(ds,"withStatus");var Pe=s(e=>typeof e=="number"&&e>=400&&e<500&&e!==408&&e!==429,"isNonRetryableStatus");var Ue={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 us(e,t,r,n){if(e===void 0||e.trim()==="")return t;let o=Number(e);return Number.isInteger(o)?Math.min(n,Math.max(r,o)):t}s(us,"clampEnvInt");var ps=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function fs(e){let t={...e},r=[];for(let[n,o,a]of ps)for(let i of o){let c=Math.floor(t[n]*a);t[i]>c&&(r.push(`${Ue[i].env} (${t[i]}ms) exceeds its bound under ${Ue[n].env} (${t[n]}ms); using ${c}ms`),t[i]=c)}return{tunables:t,warnings:r}}s(fs,"coerceScopeHierarchy");function ft(e){let t={};for(let r of Object.keys(Ue)){let n=Ue[r];t[r]=us(e[n.env],n.fallback,n.min,n.max)}return t.resumableChunkBytes=Math.max(1,Math.floor(t.resumableChunkBytes/262144))*262144,fs(t)}s(ft,"resolveUploadTunablesDetailed");function ms(e){return ft(e).tunables}s(ms,"resolveUploadTunables");var Yr=ms({});var qr=new WeakMap,mt=new WeakMap;function Xr(e,t){e.loadedBytes=0,e.committedBytes??=0,e.lastProgress=t,qr.set(e,e.committedBytes),mt.set(e,0)}s(Xr,"beginUpload");function gt(e){e.loadedBytes=0,mt.set(e,0)}s(gt,"resetAttemptBytes");var Qr=s(e=>(t,r,n,o)=>{let a=e.get(t)??0;return r-a<n?!1:(t.lastProgress=o,e.set(t,r),!0)},"stamperFor"),gs=Qr(mt),hs=Qr(qr);function ht(e,t,r,n){return e.loadedBytes=t,gs(e,t,r,n)}s(ht,"recordSent");function yt(e,t,r,n){let o=Math.max(e.committedBytes??0,t);return e.committedBytes=o,hs(e,o,r,n)}s(yt,"recordCommitted");var ke=require("fs"),tn=require("stream");function Fe(e,{baseMs:t,capMs:r,random:n=Math.random}){let o=Math.min(r,t*2**(e-1));return o/2+n()*(o/2)}s(Fe,"jitteredBackoffMs");async function fe(e){await e.body?.cancel().catch(()=>{})}s(fe,"drainBody");var _t=s(e=>e===200||e===201,"isStored"),rn=s(e=>e===308,"isResumeIncomplete"),ys=s(e=>e===404||e===410,"isSessionGoneStatus"),nn=s((e,t)=>{let r=e?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:t},"nextOffsetFromRange"),Es=s((e,t,r)=>t<=e?`bytes */${r}`:`bytes ${e}-${t-1}/${r}`,"contentRangeFor");function Ts(e,t,r){let n=t,o=new TransformStream({transform(a,i){n+=a.byteLength,r?.(n),i.enqueue(a)}});return tn.Readable.toWeb(e).pipeThrough(o)}s(Ts,"countingBody");var Y=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{s(this,"ResumableUploadError")}},on=s(e=>e instanceof Y?e.status:void 0,"statusOf"),_s=s(e=>{let t=on(e);return t!==void 0&&ys(t)},"isSessionGone"),bs=s(e=>Pe(on(e)),"isPermanent");async function Ss(e,t,r,n){let o=await r(e,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":t,"Content-Length":"0"},signal:n});if(await fe(o),!_t(o.status))throw new Y(`resumable init failed with status ${o.status}`,o.status);let a=o.headers.get("Location");if(!a)throw new Y("resumable init returned no Location");return a}s(Ss,"initResumableSession");async function Is(e,t,r,n){let o=await r(e,{method:"PUT",headers:{"Content-Range":`bytes */${t}`},signal:n});if(await fe(o),_t(o.status))return{done:!0,offset:t};if(!rn(o.status))throw new Y(`offset query failed with status ${o.status}`,o.status);return{done:!1,offset:nn(o.headers.get("Range"),0)}}s(Is,"queryCommittedOffset");async function en(e,t,{offset:r,endExclusive:n},o){let a=Math.max(0,(0,ke.statSync)(e.filePath).size-r),i=Math.min(Math.max(0,n-r),a),c=r+i,d=i>0?(0,ke.createReadStream)(e.filePath,{start:r,end:c-1}):void 0;try{let m={method:"PUT",headers:{"Content-Range":Es(r,c,e.size),"Content-Length":String(i)},duplex:"half",signal:o,...d?{body:Ts(d,r,e.onSent)}:{}},h=await e.fetchImpl(t,m);if(await fe(h),_t(h.status))return{stored:!0,committed:e.size};if(rn(h.status))return{stored:!1,committed:nn(h.headers.get("Range"),r)};throw new Y(`resumable PUT failed with status ${h.status}`,h.status)}finally{d?.destroy()}}s(en,"putChunk");async function Rs(e,t,r,n){let o=r;for(;o<e.size;){let i=Math.min(o+e.chunkSizeBytes,e.size),{stored:c,committed:d}=await en(e,t,{offset:o,endExclusive:i},n);if(c){e.onCommitted?.(e.size);return}if(d<=o)throw new Y("resumable PUT made no forward progress");o=d,e.onCommitted?.(o)}let{stored:a}=await en(e,t,{offset:e.size,endExclusive:e.size},n);if(!a)throw new Y("resumable upload did not finalize");e.onCommitted?.(e.size)}s(Rs,"sendFrom");async function As(e,t,r){if(t.url)return t.url;if(!e.target.initUrl)throw new Y("no resumable target provided");return t.url=await Ss(e.target.initUrl,e.contentType,e.fetchImpl,r),t.used=!1,t.url}s(As,"openSession");async function Ms(e,t,r,n){if(!r)return 0;let o=await Is(t,e.size,e.fetchImpl,n);if(!o.done)return e.onCommitted?.(o.offset),o.offset}s(Ms,"resumePoint");async function Cs(e,t,r){let n=await As(e,t,r),o=await Ms(e,n,t.used,r);if(t.used=!0,o===void 0){e.onCommitted?.(e.size);return}await Rs(e,n,o,r)}s(Cs,"runAttempt");function xs(e,t,r){return _s(e)&&t.target.initUrl?(r.url=void 0,r.used=!1,"retry"):bs(e)?"stop":"retry"}s(xs,"afterFailure");async function sn(e){let t={url:e.target.sessionUrl,used:!1},r;for(let n=1;n<=e.maxAttempts&&!(e.now()>=e.deadlineAt);n++)try{await Cs(e,t,e.makeSignal());return}catch(o){if(r=o,xs(o,e,t)==="stop"||n>=e.maxAttempts)break;await e.sleep(Fe(n,{baseMs:1e3,capMs:16e3,...e.random?{random:e.random}:{}}))}throw r instanceof Error?r:new Y(`resumable upload failed: ${String(r)}`)}s(sn,"uploadResumable");var vs=s(e=>{if(typeof e!="object"||e===null)return"network_error";let t="name"in e&&typeof e.name=="string"?e.name:"";if(t==="TimeoutError")return"timeout";if(t==="AbortError")return"no_progress_abort";let r="cause"in e?e.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 o="message"in e&&typeof e.message=="string"?e.message:"";return o.startsWith("Upload failed with status")?"http_error":o.startsWith("get-upload-url")?"signed_url_error":o.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),Ns=s(e=>Math.max(1e3,Math.min(1e4,Math.floor(e/4))),"noProgressPollMs"),Be=class{constructor(t,r,n,o,a=!1,i={start:s(m=>{},"start"),complete:s(m=>{},"complete"),error:s((m,h)=>{},"error")},c,d={}){this.apiBaseURL=t;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=o;this.isolationMode=a;this.reporter=i;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=d.tunables??Yr,this.fetchImpl=d.fetchImpl??globalThis.fetch,this.now=d.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{s(this,"TestAssetUploader")}async uploadAsset(t){if(t.uploadStarted=!0,this.isolationMode){t.lastProgress=Date.now(),t.loadedBytes=0,t.sizeBytes=100,t.response=new Promise(i=>{setTimeout(()=>{t.complete=!0,t.lastProgress=Date.now(),t.loadedBytes=100,i({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=t.info,n=this.now()+this.ASSET_DEADLINE_MS,o=pe("asset_upload",{test_suite_run_id:this.sessionId,asset_type:t.info.type,file_name:t.info.fileName??(0,an.basename)(r),test_id:t.info.testId,project:t.info.project}),a=[];try{let c=(0,He.statSync)(r).size;t.sizeBytes=c,Xr(t,this.now()),o.set({size_bytes:c}),this.reporter.start(r);let d;for(let m=1;m<=this.MAX_ATTEMPTS&&!(this.now()>=n);m++){let h={attempt:m};try{let T=this.now();if(await this.getSignedURLForUpload(t),h.signed_url_ms=this.now()-T,!t.uploadURL)throw new Error("No upload URL returned");let R=this.now();h.resumable=t.resumable===!0,t.resumable?await this.putResumable(t,r,c,n):await this.putWithWatchdog(t,r,c),h.put_ms=this.now()-R,h.loaded_bytes=t.loadedBytes,h.committed_bytes=t.committedBytes,a.push(h),this.reporter.complete(r),t.complete=!0,o.emit({outcome:"success",attempt_count:a.length,attempts:a,loaded_bytes:t.loadedBytes,committed_bytes:t.committedBytes});return}catch(T){d=T,h.loaded_bytes=t.loadedBytes,h.committed_bytes=t.committedBytes,h.failure_reason=vs(T),h.error=J(T);let R=Pe(typeof T=="object"&&T!==null&&"status"in T?T.status:void 0);h.non_retryable=R,delete t.uploadURL;let _=R?"non_retryable":t.resumable?"resumable_owns_retries":m>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(h.retry_stop_reason=_,a.push(h),_)break;await this.backoff(m,n)}}this.reporter.error(r,d),t.error=!0,o.emit({outcome:"error",attempt_count:a.length,attempts:a,loaded_bytes:t.loadedBytes,committed_bytes:t.committedBytes,size_bytes:t.sizeBytes,deadline_exceeded:this.now()>=n,error:J(d)})}catch(i){this.reporter.error(r,i),t.error=!0,o.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:a.length,attempts:a,error:J(i)})}}async putWithWatchdog(t,r,n){let o=t.uploadURL;if(!o)throw new Error("No upload URL returned");let a=new AbortController,i=this.uploadTimeout??void 0;gt(t);let c=this.armNoProgressWatchdog(t,()=>a.abort()),d=i!==void 0?setTimeout(()=>a.abort(new DOMException("upload attempt timeout","TimeoutError")),i):void 0,m=(0,He.createReadStream)(r),h=0,T=this.MIN_PROGRESS_BYTES,R=this.now,_=new TransformStream({transform(u,y){h+=u.byteLength,t.sizeBytes=n,ht(t,h,T,R()),y.enqueue(u)}}),p=ln.Readable.toWeb(m).pipeThrough(_),f={method:"PUT",headers:{"Content-Type":ct[t.info.type]??""},body:p,duplex:"half",signal:a.signal};try{let u=await this.fetchImpl(o,f);if(!u.ok)throw await fe(u),Object.assign(new Error(`Upload failed with status ${u.status}`),{status:u.status});yt(t,n,this.MIN_PROGRESS_BYTES,this.now()),t.response=Promise.resolve(await u.text())}finally{clearInterval(c),clearTimeout(d),m.destroy()}}armNoProgressWatchdog(t,r){let n=-1,o=this.now();return setInterval(()=>{let a=Math.max(t.loadedBytes??0,t.committedBytes??0);a>n?(n=a,o=this.now()):this.now()-o>this.PUT_NO_PROGRESS_ABORT_MS&&r()},Ns(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(t,r,n,o){let a=t.uploadURL;if(!a)throw new Error("No upload URL returned");gt(t);let i=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,d,m=s(()=>(clearInterval(d),c=new AbortController,d=this.armNoProgressWatchdog(t,()=>c?.abort()),c.signal),"armAttempt");try{await sn({target:{initUrl:a},filePath:r,size:n,contentType:ct[t.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:s(()=>AbortSignal.any([m(),AbortSignal.timeout(i)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:o,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:s(h=>new Promise(T=>setTimeout(T,h)),"sleep"),onSent:s(h=>ht(t,h,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:s(h=>yt(t,h,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(d)}t.response=Promise.resolve("OK")}async backoff(t,r){let n=Fe(t,{baseMs:1e3,capMs:16e3}),o=Math.max(0,Math.min(n,r-this.now()));o>0&&await new Promise(a=>setTimeout(a,o))}async getSignedURLForUpload(t){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let o=JSON.stringify(t.info),a=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(t)}`,i={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(a,{method:"POST",headers:i,body:o,signal:r.signal}),{url:d,resumable:m}=await Jr(c,{resource:"get-upload-url",requiredFields:["url"]});t.uploadURL=d,t.resumable=m===!0}catch(o){throw delete t.uploadURL,o}finally{clearTimeout(n)}}};function Ge(e,t,r=Date.now()){let n=e.filter(a=>!a.complete&&!a.error);if(n.length===0)return!1;let o=n.reduce((a,i)=>Math.max(a,i.lastProgress??0),0);return o>0&&r-o>t}s(Ge,"isUploadStalled");function We(e,t,r){return e!==void 0&&r-e>t}s(We,"hasElapsedSinceTestEnd");function cn(e,t,r){return We(t.testRunEndTime,t.finalizeBudgetMs,r)?!0:e===void 0?!1:e.complete||e.error?!0:Ge([e],t.stallTimeoutMs,r)}s(cn,"shouldStopWaitingForReport");function dn(e){return e.abandonedAssets.length===0}s(dn,"mayCleanUpSources");function ws(e,t,r){if((t.length===0||Ge(e.assets,e.stallTimeoutMs,r))&&We(e.testRunEndTime,e.finalizeBudgetMs,r))return"budget";if(We(e.testRunEndTime,e.finalizeCeilingMs,r))return"budget-ceiling"}s(ws,"backstopReason");function un(e,t){let r=e.assets.filter(a=>!a.complete&&!a.error),n=s(a=>({reason:a,abandonedAssets:r}),"decide"),o=ws(e,r,t);if(o!==void 0)return n(o);if(!(e.processingInProgress||!e.doneWaitingForReport)&&!(r.length>0&&!Ge(e.assets,e.stallTimeoutMs,t))&&!(e.pendingWatchCount>0&&!We(e.testRunEndTime,e.watchTimeoutMs,t)))return r.length>0?n("stall"):e.pendingWatchCount>0?n("watch-timeout"):n("complete")}s(un,"decideFinalize");var pn=require("module");var Ds=(0,pn.createRequire)(__filename);function fn(e){let t,r;try{t=Ds("undici"),r=new t.Agent({connect:{timeout:e.connectTimeoutMs},headersTimeout:e.headersTimeoutMs,bodyTimeout:e.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4})}catch(o){return ne("monitor_dispatcher_unavailable",{outcome:"error",error:J(o)}),process.emitWarning("@checksum-ai/runtime: undici dispatcher unavailable; upload timeouts fall back to the platform defaults",{detail:String(o)}),globalThis.fetch}let n=t.fetch;return(o,a)=>{let i={...a,dispatcher:r};return n(o,i)}}s(fn,"createMonitorFetch");var bt=class{static{s(this,"CLIChannel")}constructor(){}sendToCLI(...t){let r=`{trm}${t.map(n=>n.toString()).join(`,
|
|
166
12
|
`)}{/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}`)}},ns=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 Qi(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:Xp(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,em.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=zi.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,Qp.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=Zr("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 Ki(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,_f(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&&Kp(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e)&&this.settleReport();let r=Zp({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 cs(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,An.randomBytes)(8).toString("hex")}.json`;e=(0,Be.join)((0,im.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(Jp(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,rm.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;case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async calculateFileSha1Streaming(e){let r=(0,An.createHash)("sha1"),n=(0,ce.createReadStream)(e);return await(0,tm.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 cs(1e3),n=Zr("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,An.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=nm.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let i=n.address().port;n.close(()=>{e(i)})})})}},sm;try{sm=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new ns(sm,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
|
-
*/
|
|
13
|
+
`)}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}`)}},$e=class{constructor(t,r=!1){this.config=t;this.isolationMode=r;this.tunablesResolution=ft(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 bt,pt(n=>this.channel.wideEvent(n)),this.testAssetUploader=new Be(t.apiURL,t.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:s(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:s(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,P.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:s((n,o)=>this.channel.trace("Upload Failed",{filename:n,error:o}),"error")},t.sessionId,{fetchImpl:fn(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}`),ne("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{s(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"),i=JSON.parse(a);await this.handleReport(i)}catch(a){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(a)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(t){try{let r=await(0,gn.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,K.dirname)(t);await this.channel.log("Serving report in browser: "+r);let n=ve.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,mn.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:i,projectRoot:c,isUploadReport:d,dedupeByChecksumTestId:m}=t;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,K.dirname)(r),d);let h=pe("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!d});try{let T=await this.readMetadataFile(n),R=new Oe(r,this.config.sessionId,this.pwTestIdToChecksumTestId,T,{hosted:!this.isolationMode,...m?{dedupeByChecksumTestId:m}:{}},this.channel,i,c,this.checksumTestIdToUsingPlaceholder),_=this.initAsset({type:"report",path:""});this.reportAsset=_;try{let u=await R.process();_.info.path=R.getProcessedFilePath(),h.set({processed_path:_.info.path,...u}),this.uploadAsset(_)}catch(u){this.channel.debug("Error processing report, "+u.message),_.error=!0,h.set({error:J(u)})}let p=R.getReportsStats();this.stats=p,wt(h,_.error?"error":"success",p),this.channel.debug("Checking watch assets");let f=this.watchAssets.filter(u=>!(u.type!=="trace"||R.testHasTrace(u.testId??"",u.project??"")));f.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(f.map(u=>u.path)))),this.watchAssets=this.watchAssets.filter(u=>u.type!=="trace"||R.testHasTrace(u.testId??"",u.project??""))}catch(T){this.channel.debug("Error processing report, "+this.stringify(T)),this.reportAsset&&(this.reportAsset.error=!0),h.emit({outcome:"error",error:J(T)})}finally{if((a==="always"||a==="on-failure"&&o)&&await this.serveReport(r),n&&(0,P.existsSync)(n))try{(0,P.unlinkSync)(n)}catch(R){console.error(`Error deleting checksum metadata file ${n}: ${R.message}`)}}}uploadReportData(t,r){let n=(0,K.join)(t,"data");try{let o=(0,P.readdirSync)(n),a=r?[".webm"]:[".zip",".webm"],i=o.filter(c=>!a.includes((0,K.extname)(c)));this.channel.debug("Preparing to upload report data files,"+i);for(let c of i)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(o){this.channel.debug(`Error reading/adding report data files from dir ${n}`+o.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 t=Date.now();!this.doneWaitingForReport&&cn(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},t)&&this.settleReport();let r=un({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},t);if(!r){await ze(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,t)}stopWaitingForReport(t){this.doneWaitingForReport=!0,this.reportOutcome=t}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let t="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,be.randomBytes)(8).toString("hex")}.json`;t=(0,K.join)((0,Tn.tmpdir)(),n),(0,P.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.reportOutcome==="uploaded"?"true":"false"}:${t}`)}finalizeRun(t,r){t.reason==="stall"&&this.emitStallDetected(t.abandonedAssets,r),t.abandonedAssets.forEach(i=>{i.error=!0});let n=this.assets.some(i=>i.error)?"uploads-complete-with-errors":"uploads-complete",o=this.assets.filter(i=>i.error);ne("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(i=>i.complete).length,errored:o.length,stalled:t.abandonedAssets.length>0,stalled_count:t.abandonedAssets.length,finalize_reason:t.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:o.map(i=>this.assetSnapshot(i,r))});let a=n==="uploads-complete"?{}:{uploadErrors:o.map(i=>{try{return JSON.stringify(i)}catch{return i.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r,finalizeReason:t.reason,abandonedAssets:t.abandonedAssets.map(i=>this.assetSnapshot(i,r))};if(dn(t))try{this.cleanUp()}catch(i){this.channel.debug("cleanUp failed (ignored): "+i?.message)}else this.channel.debug(`skipping cleanUp: ${t.abandonedAssets.length} asset(s) abandoned (${t.reason})`);this.channel.event(n,JSON.stringify(a))}assetSnapshot(t,r){return{file_name:t.info.fileName??(0,K.basename)(t.info.path),asset_type:t.info.type,test_id:t.info.testId,loaded_bytes:t.loadedBytes,committed_bytes:t.committedBytes,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,K.dirname)(r.info.path);break}t&&(0,P.rmSync)(t,{recursive:!0,force:!0})}emitStallDetected(t,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,ne("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:t.length,pending_assets:t.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let t=await this.acquirePortNumber();this.channel.event("port",t.toString()),this.server=(0,yn.createServer)((r,n)=>{let o=s(i=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(i)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let a="";r.on("data",i=>{a+=i.toString()}),r.on("end",()=>{let i;try{i=JSON.parse(a)}catch{o("Invalid body");return}let{type:c,payload:d,watch:m}=i;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(d)}`),c){case"asset":if(!d.path||!d.type){o("Missing arguments");return}m?this.watchAsset(d):this.processAsset(d);break;case"testInfo":if(!d.pwTestId||!d.checksumTestId){o("Missing arguments");return}this.pwTestIdToChecksumTestId[d.pwTestId]=d.checksumTestId,d.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[d.checksumTestId]=d.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let h=d;if(!h.checksumTestId||!d.data){o("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...h}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(d));break;case"runProgress":this.forwardProgress(d);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=s(()=>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)})}}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=s(async()=>{await this.waitForFileComplete(t.path)&&(this.processAsset(t),this.watchAssets=this.watchAssets.filter(o=>o.path!==t.path))},"waitForCompletion");if((0,P.existsSync)(t.path))r();else{let n=(0,K.dirname)(t.path),o=(0,K.basename)(t.path),a=!1,i=(0,P.watch)(n,(c,d)=>{(async()=>{if(!(d!==o||a))try{this.channel.debug("Watched file changed "+t.path),a=!0,await r()}finally{i.close()}})()})}}waitForFileComplete(t,r=1e3,n=6e4,o=1){return new Promise(a=>{let i=Date.now(),c=0,d=o,m=s(()=>{if(!(0,P.existsSync)(t)){this.channel.debug(`Asset required for upload doesn't exist anymore ${t}`),a(!1);return}let h=(0,P.statSync)(t).size;if(h===c){if(d>0){this.channel.debug(`File size has not changed, verifying stabilization, ${t}, size: ${h}, equalSizeValidationCountLeft: ${d}`),d--,setTimeout(m,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${t}, size: ${h}`),a(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${t}, previous size: ${c}, current size: ${h}`),Date.now()-i>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${t}`),a(!0);return}c=h,setTimeout(m,r)},"checkFile");m()})}processAsset(t){switch(t.type){case"trace":return this.processTrace(t.path,t.testId);case"har":return;case"rrweb-recording":case"esra":case"test-files":return this.addAsset(t);default:return}}async calculateFileSha1Streaming(t){let r=(0,be.createHash)("sha1"),n=(0,P.createReadStream)(t);return await(0,hn.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 ze(1e3),n=pe("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,P.renameSync)(t,o);let c="checksum-playwright-trace:"+Date.now().toString()+(0,be.randomBytes)(1024).toString("hex");(0,P.writeFileSync)(t,c)}let i=await s(async()=>await this.calculateFileSha1Streaming(t)+(0,K.extname)(t),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${i}, sending for upload...`),this.addAsset({type:"report-data-file",path:o,...r!==void 0?{testId:r}:{},fileName:i}),n.emit({outcome:"success",file_name:i})}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:J(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=En.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let o=n.address().port;n.close(()=>{t(o)})})})}},_n;try{_n=JSON.parse(process.argv[2]??"")}catch(e){console.error("Error starting test run monitor",e),process.exit(1)}new $e(_n,process.argv[3]==="isolated");0&&(module.exports={TestRunMonitor});
|