momentic-mobile 0.4.6 → 0.4.7

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/bin/cli.js CHANGED
@@ -20,7 +20,7 @@ ${this.decisions.map(e=>e.toString()).join(`
20
20
  `).slice(o).filter(Boolean).join(`
21
21
  `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Ea(e,...t))}error(e,...t){this._log("error",Ea(e,...t))}info(e,...t){this._log("info",Ea(e,...t))}log(e,...t){this._log("log",Ea(e,...t))}warn(e,...t){this._log("warn",Ea(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function gb(r){let e=globalThis.console,t=new bl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
22
22
  `);process.stderr.write(`${o}
23
- `),globalThis.console=e}}var rp=" ".repeat(6);import VO from"fetch-retry";import jO from"os";import hb,{multistream as WO}from"pino";import $O from"pino-pretty";import qO from"pino-std-serializers";var Wo=new Map,KO=!0,fb="Log throttle exceeded",YO=100,XO=5e3,JO=VO(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),np=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??jO.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=KO?hb(a):hb(a,WO([{stream:$O({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await JO(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:qn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===fb)return!0;let t=Date.now();return t-this.lastWindowStart>XO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,fb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<YO?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(ya[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=qO.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:iy({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,Wo.set("app",this),Wo.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=ay[e]):(this.minLevelValue=ya[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},$o=({app:r,hostname:e,disableConsoleLogs:t})=>(Wo.has(r)||Wo.set(r,new np({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Wo.get(r));async function Sb(){await Promise.all([...Wo.values()].map(r=>r.flush()))}import{hostname as ZO}from"os";var rr=$o({app:"cli",hostname:ZO(),disableConsoleLogs:!0}).child({cliVersion:"0.4.6"});function op(r){if(!r)return;r=r.toLowerCase();let e=dl.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function yb({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return gb(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var Ta=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=qo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=qo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=qo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=qo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=qo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=qo.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),QO||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import eL from"fs";import{tmpdir as tL}from"os";import rL from"path";import{registry as va}from"playwright-core/lib/server";import bb from"proper-lockfile";var Eb=rL.join(tL(),"momenticBrowserInstallation");var ip=["chrome","chromium","chrome-for-testing","ffmpeg"],nL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Tb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function vb(r){let e=Tb[nL[r]??""]??"",t=va.findExecutable(e);return!t||t.installType==="none"?!1:ap(t)}function ap(r){let e=r.executablePath();return eL.existsSync(e)}function oL(r,e){let t=Tb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=va.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&ap(n)))return n}async function iL({browser:r,force:e}){let t=oL(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await va.installDeps([t],!1),await va.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=va.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!ap(o);)R.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function El({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?ip:Array.from(new Set(r));try{await bb.lock(Eb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await iL({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await bb.unlock(Eb,{realpath:!1})}if(o)throw o}import{createServer as aL}from"http";async function Tl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await vl(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function vl(r){return new Promise((e,t)=>{let n=aL();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import zQ from"blocked-at";import GQ from"why-is-node-running";import kk from"fs";import{tmpdir as Uk}from"os";import Fk from"path";import{remote as Bk}from"webdriverio";import{createInstanceClient as Pk}from"@limrun/api";import{execSync as Ik}from"child_process";import QQ,{multistream as t7}from"pino";import n7 from"pino-pretty";var a7=5*1024,sL="...[truncated]",s7=Buffer.byteLength(sL,"utf8");import{PostHog as S7}from"posthog-node";var fn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ab=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(Ab(p));l=()=>c(Ab(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new fn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}import{PostHog as C7}from"posthog-node";import{execSync as lL}from"child_process";import Ko from"os";import cL from"v8";var wb,Pr,Cb=Ko.platform(),uL=Ko.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{}),Rb=r=>{try{let e={},t=!1,n=dL(),o=pL(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=cL.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),Kn&&R.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function xb(r){if(!Mr)return Rb(r),{interval:setInterval(()=>Rb(r),2e4),cpuMetadata:uL,platform:Cb}}function dL(){let r=Ko.totalmem(),e=Cb==="darwin"?mL():(()=>{let n=Ko.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function pL(){let r=Ko.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Pr)return Pr=t,null;let n={user:t.user-Pr.user,nice:t.nice-Pr.nice,sys:t.sys-Pr.sys,idle:t.idle-Pr.idle,irq:t.irq-Pr.irq,total:t.total-Pr.total};return wb={measurementTime:e,intervalMs:e-Pr.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Pr=t,wb}function mL(){try{let r=lL("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ko.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Al=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function gL(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function wl(r,e){let t=gL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var eE="=",Ml=";",yp=",";var tE=8192;var Zo={};fx(Zo,{getKeyPairs:()=>qL,parseKeyPairsIntoRecord:()=>KL,parsePairKeyValue:()=>rE,serializeKeyPairs:()=>$L});Me();var WL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function $L(r){return r.reduce(function(e,t){var n=""+e+(e!==""?yp:"")+t;return n.length>tE?e:n},"")}function qL(r){return r.getAllEntries().map(function(e){var t=WL(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Ml+o.metadata.toString()),i})}function rE(r){var e=r.split(Ml);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(eE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=lp(e.join(Ml))),{key:o,value:i,metadata:a}}}}}function KL(r){return typeof r!="string"||r.length===0?{}:r.split(yp).map(function(e){return rE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var _l;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(_l||(_l={}));var YL=",",XL=["OTEL_SDK_DISABLED"];function JL(r){return XL.indexOf(r)>-1}var ZL=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function QL(r){return ZL.indexOf(r)>-1}var eN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function tN(r){return eN.indexOf(r)>-1}var bp=1/0,Ep=128,rN=128,nN=128,Tp={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:Le.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:rN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:nN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:_l.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function oN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function iN(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function aN(r,e,t,n){n===void 0&&(n=YL);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var sN={ALL:Le.ALL,VERBOSE:Le.VERBOSE,DEBUG:Le.DEBUG,INFO:Le.INFO,WARN:Le.WARN,ERROR:Le.ERROR,NONE:Le.NONE};function lN(r,e,t){var n=t[r];if(typeof n=="string"){var o=sN[n.toUpperCase()];o!=null&&(e[r]=o)}}function nE(r){var e={};for(var t in Tp){var n=t;switch(n){case"OTEL_LOG_LEVEL":lN(n,e,r);break;default:if(JL(n))oN(n,e,r);else if(QL(n))iN(n,e,r);else if(tN(n))aN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function gt(){var r=nE(process.env);return Object.assign({},Tp,r)}function oE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Pl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=oE(r.charCodeAt(n)),i=oE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var iE="1.25.1";var cN="deployment.environment";var uN="process.runtime.name";var dN="service.name";var pN="service.instance.id";var mN="telemetry.sdk.name",gN="telemetry.sdk.language",hN="telemetry.sdk.version";var aE=cN;var sE=uN;var Il=dN;var lE=pN;var _a=mN,Pa=gN,Ia=hN;var fN="nodejs";var cE=fN;var Qo,Ol=(Qo={},Qo[_a]="opentelemetry",Qo[sE]="node",Qo[Pa]=cE,Qo[Ia]=iE,Qo);var SN=9,yN=6,bN=Math.pow(10,yN),EN=Math.pow(10,SN);function uE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*bN);return[t,n]}function dE(r){return r[0]*EN+r[1]}function Oa(r){return r[0]*1e6+r[1]/1e3}var Xn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Xn||(Xn={}));var pE=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var TN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},vN=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},mE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new pE}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,vN([this._that],TN(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var wt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(wt||(wt={}));var AN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var Xte=function(r){AN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function gE(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var or;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(or||(or={}));var hE=function(){function r(){this.kind=or.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));var wN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function RN(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var vp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RN(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=gE(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ap=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new vp(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new vp(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new vp(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.HISTOGRAM,dataPoints:n.map(function(i){var a=wN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var wp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Rp=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Cp=function(){function r(e,t,n,o){e===void 0&&(e=new CN),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var CN=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Rp([n,this._counts.length-t],wp(this._counts.slice(t)),!1)),o.splice.apply(o,Rp([0,t],wp(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Rp([],wp(this._counts),!1))},r}();var fE=52,xN=2146435072,MN=1048575,xp=1023,Ll=-xp+1,Nl=xp,La=Math.pow(2,-1022);function Dl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&xN)>>20;return n-xp}function kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&MN)*Math.pow(2,32);return o+n}function Na(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function yE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var _N=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Sn=function(r){_N(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var EE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<La)return this._minNormalLowerBoundaryIndex();var t=Dl(e),n=this._rightShift(kl(e)-1,fE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Sn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Sn("overflow: "+e+" is > maximum lower boundary: "+n);return Na(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=Ll>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Nl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var TE=function(){function r(e){this._scale=e,this._scaleFactor=Na(Math.LOG2E,e),this._inverseFactor=Na(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=La)return this._minNormalLowerBoundaryIndex()-1;if(kl(e)===0){var t=Dl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Sn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return La;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Sn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return Ll<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Nl+1<<this._scale)-1},r}();var vE=-10,AE=20,PN=Array.from({length:31},function(r,e){return e>10?new TE(e-10):new EE(e-10)});function Mp(r){if(r>AE||r<vE)throw new Sn("expected scale >= "+vE+" && <= "+AE+", got: "+r);return PN[r+10]}var IN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ul=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),ON=20,LN=160,_p=2,NN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=LN),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Cp),u===void 0&&(u=new Cp),d===void 0&&(d=Mp(ON)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<_p&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+_p),this._maxSize=_p)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=yE(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Mp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Ul.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Ul.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Ul(0,-1);var o=t-n;return new Ul(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var wE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new NN(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=IN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var DN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Pp=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=uE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var RE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Pp(e)},r.prototype.merge=function(e,t){var n=Oa(t.sampleTime)>=Oa(e.sampleTime)?t:e;return new Pp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Oa(t.sampleTime)>=Oa(e.sampleTime)?t:e;return new Pp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.GAUGE,dataPoints:n.map(function(i){var a=DN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var kN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Da=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ip=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Da(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Da(t.startTime,this.monotonic,o,t.reset):new Da(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Da(t.startTime,this.monotonic,o,!0):new Da(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.SUM,dataPoints:n.map(function(i){var a=kN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Jn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Or=function(){function r(){}return r.Drop=function(){return LE},r.Sum=function(){return NE},r.LastValue=function(){return DE},r.Histogram=function(){return kE},r.ExponentialHistogram=function(){return UN},r.Default=function(){return FN},r}();var CE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hE,e}(Or);var xE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ip(!0),e.NON_MONOTONIC_INSTANCE=new Ip(!1),e}(Or);var ME=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new RE,e}(Or);var _E=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ap([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Or);var PE=function(r){Jn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Ap(this._boundaries,this._recordMinMax)},e}(Or);var IE=function(r){Jn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new wE(this._maxSize,this._recordMinMax)},e}(Or);var OE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return NE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return DE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new PE(t.advice.explicitBucketBoundaries):kE}return z.warn("Unable to recognize instrument type: "+t.type),LE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Or);var LE=new CE,NE=new xE,DE=new ME,kE=new _E,UN=new IE,FN=new OE;Me();function Fl(){return"unknown_service:"+process.argv0}var yn=function(){return yn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},yn.apply(this,arguments)},BN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},zN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},HN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Op=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return z.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[Il]=Fl(),e[Pa]=Ol[Pa],e[_a]=Ol[_a],e[Ia]=Ol[Ia],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return BN(this,void 0,void 0,function(){return zN(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=yn(yn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=HN(a,2),l=c[0],u=c[1];return yn(yn(yn(yn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var Zn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Zn||(Zn={}));Me();var GN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},VN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Lp=function(){return nr.CUMULATIVE},UE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},FE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function jN(){var r=gt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Lp:e==="delta"?UE:e==="lowmemory"?FE:(z.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),Lp)}function WN(r){return r!=null?r===Zn.DELTA?UE:r===Zn.LOWMEMORY?FE:Lp:jN()}function $N(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Or.Default()}}var BE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=$N(t),this._aggregationTemporalitySelector=WN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return GN(this,void 0,void 0,function(){return VN(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var qN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zE=1e4,HE=5,GE=1e3,VE=5e3,jE=1.5;function ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=qN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Dp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function kp(r){return typeof r=="number"?r<=0?Up(r,zE):r:KN()}function KN(){var r,e=Number((r=gt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:gt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Up(e,zE):e}function Up(r,e){return z.warn("Timeout must be greater than 0",r),e}function WE(r){var e=[429,502,503,504];return e.includes(r)}function $E(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var qE=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new mE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=kp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Xn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Xn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Xn.SUCCESS})}).catch(function(n){t({code:Xn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Me();import*as Fp from"url";import*as zl from"http";import*as Hl from"https";import*as KE from"zlib";import{Readable as XN}from"stream";var bn;(function(r){r.NONE="none",r.GZIP="gzip"})(bn||(bn={}));var YN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ei=function(r){YN(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Bl=function(){return Bl=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Bl.apply(this,arguments)};function Bp(r,e,t,n,o){var i=r.timeoutMillis,a=new Fp.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new ei("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Bl({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?zl.request:Hl.request,g=function(h,f){switch(h===void 0&&(h=HE),f===void 0&&(f=GE),l=m(p,function(b){var x="";b.on("data",function(A){return x+=A}),b.on("aborted",function(){if(u){var A=new ei("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)z.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&WE(b.statusCode)&&h>0){var A=void 0;f=jE*f,b.headers["retry-after"]?A=$E(b.headers["retry-after"]):A=Math.round(Math.random()*(VE-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var T=new ei(b.statusMessage,b.statusCode,x);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new ei("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new ei("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case bn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=JN(e);E.on("error",o).pipe(KE.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function JN(r){var e=new XN;return e.push(r),e.push(null),e}function zp(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Fp.URL(r.url),t=e.protocol==="http:"?zl.Agent:Hl.Agent;return new t(Bl({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Hp(r){if(r)return r;var e=gt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||gt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===bn.GZIP?bn.GZIP:bn.NONE}Me();var ZN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Gl=function(r){ZN(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,ka(t.headers),Zo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=zp(t),i.compression=Hp(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Bp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(qE);function XE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function QN(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function JE(r){var e=XE(r);return QN(e)}function eD(r){var e=XE(r);return e.toString()}var tD=typeof BigInt<"u"?eD:dE;function YE(r){return r}function ZE(r){if(r!==void 0)return Pl(r)}var rD={encodeHrTime:JE,encodeSpanContext:Pl,encodeOptionalSpanContext:ZE};function QE(r){var e,t;if(r===void 0)return rD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?JE:tD,encodeSpanContext:o?YE:Pl,encodeOptionalSpanContext:o?YE:ZE}}var nD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function eT(r){return{name:r.name,version:r.version}}function ti(r){return Object.keys(r).map(function(e){return tT(e,r[e])})}function tT(r,e){return{key:r,value:rT(e)}}function rT(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(rT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=nD(t,2),o=n[0],i=n[1];return tT(o,i)})}}:{}}function nT(r){return{attributes:ti(r.attributes),droppedAttributesCount:0}}Me();function iT(r,e){var t=QE(e);return{resource:nT(r.resource),schemaUrl:void 0,scopeMetrics:oD(r.scopeMetrics,t)}}function oD(r,e){return Array.from(r.map(function(t){return{scope:eT(t.scope),metrics:t.metrics.map(function(n){return iD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function iD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=cD(r.aggregationTemporality);switch(r.dataPointType){case wt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:oT(r,e)};break;case wt.GAUGE:t.gauge={dataPoints:oT(r,e)};break;case wt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:sD(r,e)};break;case wt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:lD(r,e)};break}return t}function aD(r,e,t){var n={attributes:ti(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ht.INT:n.asInt=r.value;break;case Ht.DOUBLE:n.asDouble=r.value;break}return n}function oT(r,e){return r.dataPoints.map(function(t){return aD(t,r.descriptor.valueType,e)})}function sD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function lD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function cD(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function aT(r,e){return{resourceMetrics:r.map(function(t){return iT(t,e)})}}var Gp={serializeRequest:function(r){var e=aT(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var sT="0.52.1";var lT=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ri=function(){return ri=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ri.apply(this,arguments)},cT="v1/metrics",uD="http://localhost:4318/"+cT,dD={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+sT},pD=function(r){lT(e,r);function e(t){var n=r.call(this,t,Gp,"application/json")||this;return n.headers=ri(ri(ri(ri({},n.headers),dD),Zo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Dp(gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):gt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Np(gt().OTEL_EXPORTER_OTLP_ENDPOINT,cT):uD},e}(Gl),uT=function(r){lT(e,r);function e(t){return r.call(this,new pD(t),t)||this}return e}(BE);var ni;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ni||(ni={}));var Lr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Lr||(Lr={}));Me();var mD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),dT=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},pT=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hD=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},fD=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function mT(r){return r!=null}function Vl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function gT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Vp=function(r){mD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function En(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Vp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function hT(r){return dT(this,void 0,void 0,function(){var e=this;return pT(this,function(t){return[2,Promise.all(r.map(function(n){return dT(e,void 0,void 0,function(){var o,i;return pT(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function fT(r){return r.status==="rejected"}function jp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,hD([],gD(e(n)),!1))}),t}function ST(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=fD(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function yT(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function bT(r,e){return r.toLowerCase()===e.toLowerCase()}Me();var ir;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(ir||(ir={}));var Wp=function(){function r(){this.kind=ir.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Me();var me;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(me||(me={}));function Nr(r,e,t){var n,o,i,a;return yD(r)||z.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Ht.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function ET(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function TT(r,e){return bT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var SD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function yD(r){return r.match(SD)!=null}var bD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function ED(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var jl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=ED(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=yT(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Wl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jl(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new jl(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new jl(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.HISTOGRAM,dataPoints:n.map(function(i){var a=bD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var $p=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qp=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Kp=function(){function r(e,t,n,o){e===void 0&&(e=new TD),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var TD=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,qp([n,this._counts.length-t],$p(this._counts.slice(t)),!1)),o.splice.apply(o,qp([0,t],$p(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(qp([],$p(this._counts),!1))},r}();var vT=52,vD=2146435072,AD=1048575,Yp=1023,$l=-Yp+1,ql=Yp,Ua=Math.pow(2,-1022);function Kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&vD)>>20;return n-Yp}function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&AD)*Math.pow(2,32);return o+n}function Fa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function wT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var wD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Tn=function(r){wD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var CT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ua)return this._minNormalLowerBoundaryIndex();var t=Kl(e),n=this._rightShift(Yl(e)-1,vT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Tn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Tn("overflow: "+e+" is > maximum lower boundary: "+n);return Fa(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=$l>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return ql>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var xT=function(){function r(e){this._scale=e,this._scaleFactor=Fa(Math.LOG2E,e),this._inverseFactor=Fa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ua)return this._minNormalLowerBoundaryIndex()-1;if(Yl(e)===0){var t=Kl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Tn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ua;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Tn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return $l<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(ql+1<<this._scale)-1},r}();var MT=-10,_T=20,RD=Array.from({length:31},function(r,e){return e>10?new xT(e-10):new CT(e-10)});function Xp(r){if(r>_T||r<MT)throw new Tn("expected scale >= "+MT+" && <= "+_T+", got: "+r);return RD[r+10]}var CD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Xl=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),xD=20,MD=160,Jp=2,PT=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=MD),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Kp),u===void 0&&(u=new Kp),d===void 0&&(d=Xp(xD)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Jp&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Jp),this._maxSize=Jp)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=wT(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Xp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Xl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Xl.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Xl(0,-1);var o=t-n;return new Xl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var Zp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PT(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=CD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Me();var _D=cp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function IT(r){return r.setValue(_D,!0)}Me();function OT(){return function(r){z.error(PD(r))}}function PD(r){return typeof r=="string"?r:JSON.stringify(ID(r))}function ID(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var OD=OT();function Jl(r){try{OD(r)}catch{}}var LT="1.30.1";var LD="process.runtime.name";var ND="service.name";var DD="telemetry.sdk.name",kD="telemetry.sdk.language",UD="telemetry.sdk.version";var NT=LD;var DT=ND;var Ba=DD,za=kD,Ha=UD;var FD="nodejs";var kT=FD;var oi,Qn=(oi={},oi[Ba]="opentelemetry",oi[NT]="node",oi[za]=kT,oi[Ha]=LT,oi);function Ga(r){r.unref()}var WD=9,$D=6,qD=Math.pow(10,$D),eie=Math.pow(10,WD);function eo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*qD);return[t,n]}function ii(r){return r[0]*1e6+r[1]/1e3}var Va;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Va||(Va={}));Me();function UT(r,e){return new Promise(function(t){Jo.with(IT(Jo.active()),function(){r.export(e,function(n){t(n)})})})}var FT={_export:UT};var KD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zl=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=eo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Qp=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zl(e)},r.prototype.merge=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Zl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Zl(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.GAUGE,dataPoints:n.map(function(i){var a=KD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var YD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ai=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ql=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ai(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ai(t.startTime,this.monotonic,o,t.reset):new ai(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new ai(t.startTime,this.monotonic,o,!0):new ai(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.SUM,dataPoints:n.map(function(i){var a=YD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var to=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ar=function(){function r(){}return r.Drop=function(){return WT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return XD},r.Default=function(){return JD},r}();var BT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wp,e}(ar);var zT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ql(!0),e.NON_MONOTONIC_INSTANCE=new Ql(!1),e}(ar);var HT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Qp,e}(ar);var GT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var ja=function(r){to(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Wl(this._boundaries,this._recordMinMax)},e}(ar);var VT=function(r){to(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Zp(this._maxSize,this._recordMinMax)},e}(ar);var jT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return $T;case me.GAUGE:case me.OBSERVABLE_GAUGE:return qT;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new ja(t.advice.explicitBucketBoundaries):KT}return z.warn("Unable to recognize instrument type: "+t.type),WT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var WT=new BT,$T=new zT,qT=new HT,KT=new GT,XD=new VT,JD=new jT;var YT=function(r){return ar.Default()},XT=function(r){return ni.CUMULATIVE};var em=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},tm=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},JT=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ZD=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ZT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:YT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:XT,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return em(this,void 0,void 0,function(){var t,n,o,i,a,s;return tm(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(ZD([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],JT(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=JT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(jp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(jp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return em(this,void 0,void 0,function(){return tm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,En(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return em(this,void 0,void 0,function(){return tm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,En(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var QD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ec=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},tc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ek=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},rm=function(r){QD(e,r);function e(t){var n,o,i,a,s=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return ec(this,void 0,void 0,function(){var t;return tc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,En(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Vp?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Jl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return ec(this,void 0,void 0,function(){var o,i,a,s,c,l;return tc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=z).error.apply(l,tk(["PeriodicExportingMetricReader: metrics collection errors"],ek(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),z.debug("Error while resolving async portion of resource: ",s),Jl(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,FT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Va.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Ga(this._interval)},e.prototype.onForceFlush=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(ZT);Me();Me();function rc(){return"unknown_service:"+process.argv0}var vn=function(){return vn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},vn.apply(this,arguments)},rk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nk=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ok=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nc=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return z.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[DT]=rc(),e[za]=Qn[za],e[Ba]=Qn[Ba],e[Ha]=Qn[Ha],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return rk(this,void 0,void 0,function(){return nk(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=vn(vn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=ok(a,2),l=c[0],u=c[1];return vn(vn(vn(vn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var QT=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var ro=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oc=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=Jo.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ht.INT&&!Number.isInteger(e)&&(z.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,eo(Date.now()))},r}();var ev=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(oc);var tv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var rv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(oc);var nv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var ic=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var ov=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var iv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var av=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);function Wa(r){return r instanceof ic}var sv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Nr(e,me.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new rv(o,n)},r.prototype.createHistogram=function(e,t){var n=Nr(e,me.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new nv(o,n)},r.prototype.createCounter=function(e,t){var n=Nr(e,me.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new tv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Nr(e,me.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new ev(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Nr(e,me.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new iv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Nr(e,me.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new ov(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Nr(e,me.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new av(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var ac=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Nr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var ik=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),lv=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ak=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return lv(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return lv(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var yr=function(r){ik(e,r);function e(){return r.call(this,Vl)||this}return e}(ak);var sk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new yr,this._cumulativeMemoStorage=new yr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Vl(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=sk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new yr,e},r}();var nm=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},cv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lc=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===ni.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=lk(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=nm(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new yr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=nm(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var s=cv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=nm(e.keys()),s=a.next();!s.done;s=a.next()){var c=cv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function lk(r){return Array.from(r.entries())}var ck=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),uk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uv=function(r){ck(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new sc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new lc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new yr;Array.from(t.entries()).forEach(function(a){var s=uk(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ac);Me();function om(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
23
+ `),globalThis.console=e}}var rp=" ".repeat(6);import VO from"fetch-retry";import jO from"os";import hb,{multistream as WO}from"pino";import $O from"pino-pretty";import qO from"pino-std-serializers";var Wo=new Map,KO=!0,fb="Log throttle exceeded",YO=100,XO=5e3,JO=VO(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),np=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??jO.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=KO?hb(a):hb(a,WO([{stream:$O({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await JO(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:qn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===fb)return!0;let t=Date.now();return t-this.lastWindowStart>XO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,fb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<YO?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(ya[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=qO.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:iy({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,Wo.set("app",this),Wo.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=ay[e]):(this.minLevelValue=ya[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},$o=({app:r,hostname:e,disableConsoleLogs:t})=>(Wo.has(r)||Wo.set(r,new np({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Wo.get(r));async function Sb(){await Promise.all([...Wo.values()].map(r=>r.flush()))}import{hostname as ZO}from"os";var rr=$o({app:"cli",hostname:ZO(),disableConsoleLogs:!0}).child({cliVersion:"0.4.7"});function op(r){if(!r)return;r=r.toLowerCase();let e=dl.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function yb({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return gb(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var Ta=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=qo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=qo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=qo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=qo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=qo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=qo.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),QO||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import eL from"fs";import{tmpdir as tL}from"os";import rL from"path";import{registry as va}from"playwright-core/lib/server";import bb from"proper-lockfile";var Eb=rL.join(tL(),"momenticBrowserInstallation");var ip=["chrome","chromium","chrome-for-testing","ffmpeg"],nL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Tb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function vb(r){let e=Tb[nL[r]??""]??"",t=va.findExecutable(e);return!t||t.installType==="none"?!1:ap(t)}function ap(r){let e=r.executablePath();return eL.existsSync(e)}function oL(r,e){let t=Tb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=va.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&ap(n)))return n}async function iL({browser:r,force:e}){let t=oL(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await va.installDeps([t],!1),await va.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=va.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!ap(o);)R.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function El({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?ip:Array.from(new Set(r));try{await bb.lock(Eb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await iL({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await bb.unlock(Eb,{realpath:!1})}if(o)throw o}import{createServer as aL}from"http";async function Tl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await vl(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function vl(r){return new Promise((e,t)=>{let n=aL();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import zQ from"blocked-at";import GQ from"why-is-node-running";import kk from"fs";import{tmpdir as Uk}from"os";import Fk from"path";import{remote as Bk}from"webdriverio";import{createInstanceClient as Pk}from"@limrun/api";import{execSync as Ik}from"child_process";import QQ,{multistream as t7}from"pino";import n7 from"pino-pretty";var a7=5*1024,sL="...[truncated]",s7=Buffer.byteLength(sL,"utf8");import{PostHog as S7}from"posthog-node";var fn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ab=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(Ab(p));l=()=>c(Ab(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new fn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}import{PostHog as C7}from"posthog-node";import{execSync as lL}from"child_process";import Ko from"os";import cL from"v8";var wb,Pr,Cb=Ko.platform(),uL=Ko.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{}),Rb=r=>{try{let e={},t=!1,n=dL(),o=pL(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=cL.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),Kn&&R.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function xb(r){if(!Mr)return Rb(r),{interval:setInterval(()=>Rb(r),2e4),cpuMetadata:uL,platform:Cb}}function dL(){let r=Ko.totalmem(),e=Cb==="darwin"?mL():(()=>{let n=Ko.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function pL(){let r=Ko.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Pr)return Pr=t,null;let n={user:t.user-Pr.user,nice:t.nice-Pr.nice,sys:t.sys-Pr.sys,idle:t.idle-Pr.idle,irq:t.irq-Pr.irq,total:t.total-Pr.total};return wb={measurementTime:e,intervalMs:e-Pr.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Pr=t,wb}function mL(){try{let r=lL("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ko.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Al=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function gL(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function wl(r,e){let t=gL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var eE="=",Ml=";",yp=",";var tE=8192;var Zo={};fx(Zo,{getKeyPairs:()=>qL,parseKeyPairsIntoRecord:()=>KL,parsePairKeyValue:()=>rE,serializeKeyPairs:()=>$L});Me();var WL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function $L(r){return r.reduce(function(e,t){var n=""+e+(e!==""?yp:"")+t;return n.length>tE?e:n},"")}function qL(r){return r.getAllEntries().map(function(e){var t=WL(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Ml+o.metadata.toString()),i})}function rE(r){var e=r.split(Ml);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(eE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=lp(e.join(Ml))),{key:o,value:i,metadata:a}}}}}function KL(r){return typeof r!="string"||r.length===0?{}:r.split(yp).map(function(e){return rE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var _l;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(_l||(_l={}));var YL=",",XL=["OTEL_SDK_DISABLED"];function JL(r){return XL.indexOf(r)>-1}var ZL=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function QL(r){return ZL.indexOf(r)>-1}var eN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function tN(r){return eN.indexOf(r)>-1}var bp=1/0,Ep=128,rN=128,nN=128,Tp={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:Le.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:bp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Ep,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:rN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:nN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:_l.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function oN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function iN(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function aN(r,e,t,n){n===void 0&&(n=YL);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var sN={ALL:Le.ALL,VERBOSE:Le.VERBOSE,DEBUG:Le.DEBUG,INFO:Le.INFO,WARN:Le.WARN,ERROR:Le.ERROR,NONE:Le.NONE};function lN(r,e,t){var n=t[r];if(typeof n=="string"){var o=sN[n.toUpperCase()];o!=null&&(e[r]=o)}}function nE(r){var e={};for(var t in Tp){var n=t;switch(n){case"OTEL_LOG_LEVEL":lN(n,e,r);break;default:if(JL(n))oN(n,e,r);else if(QL(n))iN(n,e,r);else if(tN(n))aN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function gt(){var r=nE(process.env);return Object.assign({},Tp,r)}function oE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Pl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=oE(r.charCodeAt(n)),i=oE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var iE="1.25.1";var cN="deployment.environment";var uN="process.runtime.name";var dN="service.name";var pN="service.instance.id";var mN="telemetry.sdk.name",gN="telemetry.sdk.language",hN="telemetry.sdk.version";var aE=cN;var sE=uN;var Il=dN;var lE=pN;var _a=mN,Pa=gN,Ia=hN;var fN="nodejs";var cE=fN;var Qo,Ol=(Qo={},Qo[_a]="opentelemetry",Qo[sE]="node",Qo[Pa]=cE,Qo[Ia]=iE,Qo);var SN=9,yN=6,bN=Math.pow(10,yN),EN=Math.pow(10,SN);function uE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*bN);return[t,n]}function dE(r){return r[0]*EN+r[1]}function Oa(r){return r[0]*1e6+r[1]/1e3}var Xn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Xn||(Xn={}));var pE=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var TN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},vN=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},mE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new pE}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,vN([this._that],TN(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var wt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(wt||(wt={}));var AN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var Xte=function(r){AN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function gE(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var or;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(or||(or={}));var hE=function(){function r(){this.kind=or.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));var wN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function RN(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var vp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RN(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=gE(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ap=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new vp(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new vp(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new vp(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.HISTOGRAM,dataPoints:n.map(function(i){var a=wN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var wp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Rp=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Cp=function(){function r(e,t,n,o){e===void 0&&(e=new CN),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var CN=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Rp([n,this._counts.length-t],wp(this._counts.slice(t)),!1)),o.splice.apply(o,Rp([0,t],wp(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Rp([],wp(this._counts),!1))},r}();var fE=52,xN=2146435072,MN=1048575,xp=1023,Ll=-xp+1,Nl=xp,La=Math.pow(2,-1022);function Dl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&xN)>>20;return n-xp}function kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&MN)*Math.pow(2,32);return o+n}function Na(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function yE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var _N=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Sn=function(r){_N(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var EE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<La)return this._minNormalLowerBoundaryIndex();var t=Dl(e),n=this._rightShift(kl(e)-1,fE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Sn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Sn("overflow: "+e+" is > maximum lower boundary: "+n);return Na(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=Ll>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Nl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var TE=function(){function r(e){this._scale=e,this._scaleFactor=Na(Math.LOG2E,e),this._inverseFactor=Na(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=La)return this._minNormalLowerBoundaryIndex()-1;if(kl(e)===0){var t=Dl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Sn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return La;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Sn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return Ll<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Nl+1<<this._scale)-1},r}();var vE=-10,AE=20,PN=Array.from({length:31},function(r,e){return e>10?new TE(e-10):new EE(e-10)});function Mp(r){if(r>AE||r<vE)throw new Sn("expected scale >= "+vE+" && <= "+AE+", got: "+r);return PN[r+10]}var IN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ul=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),ON=20,LN=160,_p=2,NN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=LN),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Cp),u===void 0&&(u=new Cp),d===void 0&&(d=Mp(ON)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<_p&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+_p),this._maxSize=_p)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=yE(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Mp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Ul.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Ul.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Ul(0,-1);var o=t-n;return new Ul(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var wE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new NN(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=IN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var DN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Pp=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=uE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var RE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Pp(e)},r.prototype.merge=function(e,t){var n=Oa(t.sampleTime)>=Oa(e.sampleTime)?t:e;return new Pp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Oa(t.sampleTime)>=Oa(e.sampleTime)?t:e;return new Pp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.GAUGE,dataPoints:n.map(function(i){var a=DN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var kN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Da=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ip=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Da(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Da(t.startTime,this.monotonic,o,t.reset):new Da(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Da(t.startTime,this.monotonic,o,!0):new Da(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:wt.SUM,dataPoints:n.map(function(i){var a=kN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Jn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Or=function(){function r(){}return r.Drop=function(){return LE},r.Sum=function(){return NE},r.LastValue=function(){return DE},r.Histogram=function(){return kE},r.ExponentialHistogram=function(){return UN},r.Default=function(){return FN},r}();var CE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hE,e}(Or);var xE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ip(!0),e.NON_MONOTONIC_INSTANCE=new Ip(!1),e}(Or);var ME=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new RE,e}(Or);var _E=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ap([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Or);var PE=function(r){Jn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Ap(this._boundaries,this._recordMinMax)},e}(Or);var IE=function(r){Jn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new wE(this._maxSize,this._recordMinMax)},e}(Or);var OE=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return NE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return DE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new PE(t.advice.explicitBucketBoundaries):kE}return z.warn("Unable to recognize instrument type: "+t.type),LE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Or);var LE=new CE,NE=new xE,DE=new ME,kE=new _E,UN=new IE,FN=new OE;Me();function Fl(){return"unknown_service:"+process.argv0}var yn=function(){return yn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},yn.apply(this,arguments)},BN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},zN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},HN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Op=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return z.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[Il]=Fl(),e[Pa]=Ol[Pa],e[_a]=Ol[_a],e[Ia]=Ol[Ia],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return BN(this,void 0,void 0,function(){return zN(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=yn(yn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=HN(a,2),l=c[0],u=c[1];return yn(yn(yn(yn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var Zn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Zn||(Zn={}));Me();var GN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},VN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Lp=function(){return nr.CUMULATIVE},UE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},FE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function jN(){var r=gt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Lp:e==="delta"?UE:e==="lowmemory"?FE:(z.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),Lp)}function WN(r){return r!=null?r===Zn.DELTA?UE:r===Zn.LOWMEMORY?FE:Lp:jN()}function $N(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Or.Default()}}var BE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=$N(t),this._aggregationTemporalitySelector=WN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return GN(this,void 0,void 0,function(){return VN(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var qN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zE=1e4,HE=5,GE=1e3,VE=5e3,jE=1.5;function ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=qN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Dp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function kp(r){return typeof r=="number"?r<=0?Up(r,zE):r:KN()}function KN(){var r,e=Number((r=gt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:gt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Up(e,zE):e}function Up(r,e){return z.warn("Timeout must be greater than 0",r),e}function WE(r){var e=[429,502,503,504];return e.includes(r)}function $E(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var qE=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new mE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=kp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Xn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Xn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Xn.SUCCESS})}).catch(function(n){t({code:Xn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Me();import*as Fp from"url";import*as zl from"http";import*as Hl from"https";import*as KE from"zlib";import{Readable as XN}from"stream";var bn;(function(r){r.NONE="none",r.GZIP="gzip"})(bn||(bn={}));var YN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ei=function(r){YN(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Bl=function(){return Bl=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Bl.apply(this,arguments)};function Bp(r,e,t,n,o){var i=r.timeoutMillis,a=new Fp.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new ei("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Bl({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?zl.request:Hl.request,g=function(h,f){switch(h===void 0&&(h=HE),f===void 0&&(f=GE),l=m(p,function(b){var x="";b.on("data",function(A){return x+=A}),b.on("aborted",function(){if(u){var A=new ei("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)z.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&WE(b.statusCode)&&h>0){var A=void 0;f=jE*f,b.headers["retry-after"]?A=$E(b.headers["retry-after"]):A=Math.round(Math.random()*(VE-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var T=new ei(b.statusMessage,b.statusCode,x);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new ei("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new ei("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case bn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=JN(e);E.on("error",o).pipe(KE.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function JN(r){var e=new XN;return e.push(r),e.push(null),e}function zp(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Fp.URL(r.url),t=e.protocol==="http:"?zl.Agent:Hl.Agent;return new t(Bl({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Hp(r){if(r)return r;var e=gt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||gt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===bn.GZIP?bn.GZIP:bn.NONE}Me();var ZN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Gl=function(r){ZN(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,ka(t.headers),Zo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=zp(t),i.compression=Hp(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Bp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(qE);function XE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function QN(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function JE(r){var e=XE(r);return QN(e)}function eD(r){var e=XE(r);return e.toString()}var tD=typeof BigInt<"u"?eD:dE;function YE(r){return r}function ZE(r){if(r!==void 0)return Pl(r)}var rD={encodeHrTime:JE,encodeSpanContext:Pl,encodeOptionalSpanContext:ZE};function QE(r){var e,t;if(r===void 0)return rD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?JE:tD,encodeSpanContext:o?YE:Pl,encodeOptionalSpanContext:o?YE:ZE}}var nD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function eT(r){return{name:r.name,version:r.version}}function ti(r){return Object.keys(r).map(function(e){return tT(e,r[e])})}function tT(r,e){return{key:r,value:rT(e)}}function rT(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(rT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=nD(t,2),o=n[0],i=n[1];return tT(o,i)})}}:{}}function nT(r){return{attributes:ti(r.attributes),droppedAttributesCount:0}}Me();function iT(r,e){var t=QE(e);return{resource:nT(r.resource),schemaUrl:void 0,scopeMetrics:oD(r.scopeMetrics,t)}}function oD(r,e){return Array.from(r.map(function(t){return{scope:eT(t.scope),metrics:t.metrics.map(function(n){return iD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function iD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=cD(r.aggregationTemporality);switch(r.dataPointType){case wt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:oT(r,e)};break;case wt.GAUGE:t.gauge={dataPoints:oT(r,e)};break;case wt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:sD(r,e)};break;case wt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:lD(r,e)};break}return t}function aD(r,e,t){var n={attributes:ti(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ht.INT:n.asInt=r.value;break;case Ht.DOUBLE:n.asDouble=r.value;break}return n}function oT(r,e){return r.dataPoints.map(function(t){return aD(t,r.descriptor.valueType,e)})}function sD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function lD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function cD(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function aT(r,e){return{resourceMetrics:r.map(function(t){return iT(t,e)})}}var Gp={serializeRequest:function(r){var e=aT(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var sT="0.52.1";var lT=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ri=function(){return ri=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ri.apply(this,arguments)},cT="v1/metrics",uD="http://localhost:4318/"+cT,dD={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+sT},pD=function(r){lT(e,r);function e(t){var n=r.call(this,t,Gp,"application/json")||this;return n.headers=ri(ri(ri(ri({},n.headers),dD),Zo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Dp(gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):gt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Np(gt().OTEL_EXPORTER_OTLP_ENDPOINT,cT):uD},e}(Gl),uT=function(r){lT(e,r);function e(t){return r.call(this,new pD(t),t)||this}return e}(BE);var ni;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ni||(ni={}));var Lr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Lr||(Lr={}));Me();var mD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),dT=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},pT=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hD=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},fD=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function mT(r){return r!=null}function Vl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function gT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Vp=function(r){mD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function En(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Vp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function hT(r){return dT(this,void 0,void 0,function(){var e=this;return pT(this,function(t){return[2,Promise.all(r.map(function(n){return dT(e,void 0,void 0,function(){var o,i;return pT(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function fT(r){return r.status==="rejected"}function jp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,hD([],gD(e(n)),!1))}),t}function ST(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=fD(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function yT(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function bT(r,e){return r.toLowerCase()===e.toLowerCase()}Me();var ir;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(ir||(ir={}));var Wp=function(){function r(){this.kind=ir.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Me();var me;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(me||(me={}));function Nr(r,e,t){var n,o,i,a;return yD(r)||z.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Ht.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function ET(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function TT(r,e){return bT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var SD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function yD(r){return r.match(SD)!=null}var bD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function ED(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var jl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=ED(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=yT(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Wl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jl(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new jl(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new jl(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.HISTOGRAM,dataPoints:n.map(function(i){var a=bD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var $p=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qp=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Kp=function(){function r(e,t,n,o){e===void 0&&(e=new TD),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var TD=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,qp([n,this._counts.length-t],$p(this._counts.slice(t)),!1)),o.splice.apply(o,qp([0,t],$p(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(qp([],$p(this._counts),!1))},r}();var vT=52,vD=2146435072,AD=1048575,Yp=1023,$l=-Yp+1,ql=Yp,Ua=Math.pow(2,-1022);function Kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&vD)>>20;return n-Yp}function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&AD)*Math.pow(2,32);return o+n}function Fa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function wT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var wD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Tn=function(r){wD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var CT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ua)return this._minNormalLowerBoundaryIndex();var t=Kl(e),n=this._rightShift(Yl(e)-1,vT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Tn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Tn("overflow: "+e+" is > maximum lower boundary: "+n);return Fa(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=$l>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return ql>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var xT=function(){function r(e){this._scale=e,this._scaleFactor=Fa(Math.LOG2E,e),this._inverseFactor=Fa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ua)return this._minNormalLowerBoundaryIndex()-1;if(Yl(e)===0){var t=Kl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Tn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ua;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Tn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return $l<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(ql+1<<this._scale)-1},r}();var MT=-10,_T=20,RD=Array.from({length:31},function(r,e){return e>10?new xT(e-10):new CT(e-10)});function Xp(r){if(r>_T||r<MT)throw new Tn("expected scale >= "+MT+" && <= "+_T+", got: "+r);return RD[r+10]}var CD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Xl=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),xD=20,MD=160,Jp=2,PT=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=MD),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Kp),u===void 0&&(u=new Kp),d===void 0&&(d=Xp(xD)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Jp&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Jp),this._maxSize=Jp)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=wT(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Xp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Xl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Xl.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Xl(0,-1);var o=t-n;return new Xl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var Zp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PT(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=CD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Me();var _D=cp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function IT(r){return r.setValue(_D,!0)}Me();function OT(){return function(r){z.error(PD(r))}}function PD(r){return typeof r=="string"?r:JSON.stringify(ID(r))}function ID(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var OD=OT();function Jl(r){try{OD(r)}catch{}}var LT="1.30.1";var LD="process.runtime.name";var ND="service.name";var DD="telemetry.sdk.name",kD="telemetry.sdk.language",UD="telemetry.sdk.version";var NT=LD;var DT=ND;var Ba=DD,za=kD,Ha=UD;var FD="nodejs";var kT=FD;var oi,Qn=(oi={},oi[Ba]="opentelemetry",oi[NT]="node",oi[za]=kT,oi[Ha]=LT,oi);function Ga(r){r.unref()}var WD=9,$D=6,qD=Math.pow(10,$D),eie=Math.pow(10,WD);function eo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*qD);return[t,n]}function ii(r){return r[0]*1e6+r[1]/1e3}var Va;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Va||(Va={}));Me();function UT(r,e){return new Promise(function(t){Jo.with(IT(Jo.active()),function(){r.export(e,function(n){t(n)})})})}var FT={_export:UT};var KD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zl=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=eo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Qp=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zl(e)},r.prototype.merge=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Zl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Zl(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.GAUGE,dataPoints:n.map(function(i){var a=KD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var YD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ai=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ql=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ai(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ai(t.startTime,this.monotonic,o,t.reset):new ai(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new ai(t.startTime,this.monotonic,o,!0):new ai(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Lr.SUM,dataPoints:n.map(function(i){var a=YD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var to=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ar=function(){function r(){}return r.Drop=function(){return WT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return XD},r.Default=function(){return JD},r}();var BT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wp,e}(ar);var zT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ql(!0),e.NON_MONOTONIC_INSTANCE=new Ql(!1),e}(ar);var HT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Qp,e}(ar);var GT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var ja=function(r){to(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Wl(this._boundaries,this._recordMinMax)},e}(ar);var VT=function(r){to(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Zp(this._maxSize,this._recordMinMax)},e}(ar);var jT=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return $T;case me.GAUGE:case me.OBSERVABLE_GAUGE:return qT;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new ja(t.advice.explicitBucketBoundaries):KT}return z.warn("Unable to recognize instrument type: "+t.type),WT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var WT=new BT,$T=new zT,qT=new HT,KT=new GT,XD=new VT,JD=new jT;var YT=function(r){return ar.Default()},XT=function(r){return ni.CUMULATIVE};var em=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},tm=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},JT=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ZD=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ZT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:YT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:XT,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return em(this,void 0,void 0,function(){var t,n,o,i,a,s;return tm(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(ZD([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],JT(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=JT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(jp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(jp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return em(this,void 0,void 0,function(){return tm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,En(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return em(this,void 0,void 0,function(){return tm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,En(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var QD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ec=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},tc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ek=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},rm=function(r){QD(e,r);function e(t){var n,o,i,a,s=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return ec(this,void 0,void 0,function(){var t;return tc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,En(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Vp?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Jl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return ec(this,void 0,void 0,function(){var o,i,a,s,c,l;return tc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=z).error.apply(l,tk(["PeriodicExportingMetricReader: metrics collection errors"],ek(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),z.debug("Error while resolving async portion of resource: ",s),Jl(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,FT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Va.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Ga(this._interval)},e.prototype.onForceFlush=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(ZT);Me();Me();function rc(){return"unknown_service:"+process.argv0}var vn=function(){return vn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},vn.apply(this,arguments)},rk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nk=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ok=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nc=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return z.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[DT]=rc(),e[za]=Qn[za],e[Ba]=Qn[Ba],e[Ha]=Qn[Ha],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return rk(this,void 0,void 0,function(){return nk(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=vn(vn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=ok(a,2),l=c[0],u=c[1];return vn(vn(vn(vn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var QT=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var ro=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oc=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=Jo.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ht.INT&&!Number.isInteger(e)&&(z.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,eo(Date.now()))},r}();var ev=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(oc);var tv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var rv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(oc);var nv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var ic=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var ov=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var iv=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var av=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);function Wa(r){return r instanceof ic}var sv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Nr(e,me.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new rv(o,n)},r.prototype.createHistogram=function(e,t){var n=Nr(e,me.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new nv(o,n)},r.prototype.createCounter=function(e,t){var n=Nr(e,me.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new tv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Nr(e,me.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new ev(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Nr(e,me.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new iv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Nr(e,me.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new ov(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Nr(e,me.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new av(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var ac=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Nr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var ik=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),lv=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ak=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return lv(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return lv(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var yr=function(r){ik(e,r);function e(){return r.call(this,Vl)||this}return e}(ak);var sk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new yr,this._cumulativeMemoStorage=new yr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Vl(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=sk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new yr,e},r}();var nm=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},cv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lc=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===ni.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=lk(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=nm(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new yr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=nm(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var s=cv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=nm(e.keys()),s=a.next();!s.done;s=a.next()){var c=cv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function lk(r){return Array.from(r.entries())}var ck=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),uk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uv=function(r){ck(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new sc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new lc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new yr;Array.from(t.entries()).forEach(function(a){var s=uk(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ac);Me();function om(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
24
24
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
25
25
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
26
26
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
@@ -4099,9 +4099,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!ao(o.url,this.logger)){
4099
4099
  `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[l],f=Er(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(tR)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),T=Array.from(h.matchAll(NF)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);T.reverse();let M=h.replace(/ id="[0-9]+"/g,"");u.push(M);for(let W of x)p.push(W.id),m.push(W);for(let W of T){let B=m[m.length-1];B&&B.tagName===W&&m.pop()}let w=m.some(W=>kF.includes(W.tagName)),D=c[l+1]??"",V=Er(D),ee=Array.from(D.matchAll(tR)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),he=ee.some(W=>oR.includes(W)),st=ee.some(W=>DF.includes(W));d+V>=i&&(g=!0),d>=n&&(he&&!w||T.some(W=>UF.includes(W)))&&(g=!0),d>=o&&st&&!w&&(g=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
4100
4100
  `),tokenLength:d}),s.forEach((h,f)=>{let E=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:E,maxId:b},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var zF=75e4,Gc=3e5;async function uo(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=t,l=r.tree,u=r.serializedTree,d=Er(u);if(d>zF)try{let p=Hc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await GF({...r,tokenLimit:Gc-1e4,chunks:p.chunks}),u=l.serialize();let m=Er(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(Gc*Rn),u=l.serialize();let m=Er(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>Gc)try{if(o){let p=Hc({serializedTree:u,options:nR,logger:i}),m=BF();l=await k(HF({...r,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=Er(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=g}else{let p=Hc({serializedTree:u,options:rR,logger:i});l=await k(VF({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=Er(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(Gc*Rn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function HF({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:ge(c)}),u=[];return t.forEach((p,m)=>{l.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function GF(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:ge(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function VF(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:c}=t,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:ge(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function rg(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return ur({action:async()=>jF(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function jF(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await qa({orgId:p,s:E,context:n,localTools:g,signal:f,logger:l})),a&&(E=$F(E,a));let{serializedTree:x,tree:A}=await Br(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),T,M=Date.now(),w;for(;!T&&Date.now()-M<3e3;){f.throwIfAborted();try{T=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(ce){w=ce}}if(!T)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${w?.message}`);let D=x,V=!1,ee=`data:image/jpeg;base64,${T.toString("base64")}`;D=await uo({type:"locator",description:E,screenshot:ee,serializedTree:x,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:l,orgId:p}}),D!==x&&(V=!0);let he=await h.getElementLocation({browserState:D,goal:E,screenshot:ee,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:ge(l),useMemory:b});l.debug({usedRag:V,result:he},"Got locator result");let st=he.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:st,pageState:D,ragUsed:V,thoughts:he.thoughts}),!st)throw new Io(`Could not find any relevant element: ${he.thoughts}`,he.updatedMemory?{type:"GCS_TRACES",traces:he.updatedMemory}:void 0);let{resolution:W,target:B,frameConfig:ae}=await m.createTargetFromA11yId({id:he.id,requirements:he.requirements,additionalElements:he.additionalElements,description:E,targetSource:"AI",logger:l});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new C("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return b&&(he.updatedMemory?B.memory={type:"GCS_TRACES",traces:he.updatedMemory}:s&&(B.memory=s)),{thoughts:he.thoughts,target:B,resolution:W,frameConfig:ae,screenshot:ee}}var WF=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],iR="<select> element:",aR="text input or contenteditable element:",sR="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",lR="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",tg=[iR,aR,sR,lR,...WF];function cR(r,e){if(r===e)return!0;for(let t of tg){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(tg.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!tg.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function $F(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${iR} ${r}`;case"TYPE":return`${aR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${sR}
4101
4101
  ${r}`;case"ELEMENT_CHECK":return`${lR}
4102
- ${r}`;default:return r}}var qF=15;async function Vc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=qF}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Rc(c),u=0,d=Date.now(),p,m,g;try{await ur({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await X(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await ur({action:async()=>{let b=await uR(s,t,n.abortSignal);return m&&m.serializedTree===b.serializedTree&&m.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(m=b,dR({command:r,state:b,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s}),p?.updatedMemory&&Tc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await ur({action:async()=>dR({command:r,state:await uR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function uR(r,e,t){let[n,o]=await Promise.all([Br(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function dR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",A=g;x!=="VISION_ONLY"&&(A=await uo({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(D,V)=>d.getVisualAssertionResult(D,V):(D,V)=>d.getAssertionResult(D,V))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ge(l)});return(w.result||i)&&w.relevantElements&&(m.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await KF(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function KF(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await k(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var YF=75e4,jc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function pR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await XF(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof jc?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function XF(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(JF(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function JF(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>ZF(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function ZF(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await qa({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await Br(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(p)>YF)throw new jc;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:ge(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as gR}from"lodash-es";async function hR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>gh(e.cache)?e.cache:void 0,a=i(),s=gR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=Kv(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&As(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!m&&(g.target=pm(g.target),g.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!rn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=eB(t.assertion),l,u=!1,d=gR(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>QF(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ea(t),targetName:"target"}});return l={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(s.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),l={...m,thoughts:g}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof C)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function QF(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Lt(c,500,!0)},!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Lt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},nn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:nn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:nn*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Yv[n.condition]:Xv[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${l}`):i=new C("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Wc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function eB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function fR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as tB}from"jimp";async function es(r,e){let t=await r.screenshot(e),n=await tB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as SR}from"jimp";import ng from"jpeg-js";import rB from"pixelmatch";async function yR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!rn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async ee=>es(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await es(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let ie=`${l.width}x${l.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ie}) does not match saved screenshot dimensions (${ee}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await SR.fromBuffer(l.buffer),p={width:l.width,height:l.height},m=await SR.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,b=Math.abs(p.height-g.height),x=Math.abs(p.width-g.width);if(f>E){let ie=d.cover({w:g.width,h:g.height});l.buffer=await ie.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let ie=m.cover({w:p.width,h:p.height});u.buffer=await ie.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,w=rB(ng.decode(u.buffer).data,ng.decode(l.buffer).data,A.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>T*100,V=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${T*100}%.`;if(h&&(V+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",V);return{fail:D,thoughts:V,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:ng.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var nB=3e4;async function $c({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??nB/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let s=a.toString(),c;if(ci(r.url)&&(c=r.url),t&&ui(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let m=s?`${c}?${s}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var oB=5e3;async function TR({timeout:r=nn,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await bR(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await X(s,e.signal),s=Math.min(Math.floor(s*1.5),oB);else return i}return i=await bR(e),i}async function bR({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(ER,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(ER,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?oo.CONTAINS:io.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function ER({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var iB=3e4;async function vR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??iB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(ci(r.url)&&(s=r.url),t&&ui(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var qc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([Br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await uo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([Br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await uo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(a)},langfuseSessionId:s})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Br(this.browser,e)}async locateElement(e){return await rg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await s(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new C("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await ur({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Wu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Ku(i)||$u(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Yu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Rr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await X(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=AR(e.cache);if((!b||l)&&!xu(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!cR(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=T=>!!T&&As(T),A=!0;if(!x(b)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await pR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:m,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let T;try{T=await rg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:m,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof Io&&D.updatedLocatorMemory){let V={id:-1,...i,memory:D.updatedLocatorMemory};Ec({cmd:c,key:d,newTarget:V,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,g),w=await a(M);return Ec({cmd:c,key:d,newTarget:T.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=ge(g)),{result:w,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let M=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,g),w=await a(M);if(Rt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.6"]),Ec({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),A){let D=T.decisions.filter(V=>V.matched);if(D.length!==1)g.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let V=D[0].type;n.recordTargetAutoHeal({healType:V})}}return{result:w,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),Rt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.6"]);let M=!1;if((T instanceof Rr||Wu(T)||Ku(T)||Yu(T)||pf(T)||$u(T)||mf(T))&&(M=!0),T instanceof C&&!M)throw g.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){g.info({err:T},"Failed to execute action with cached target, retrying with AI");let w;return b.memory&&lh(b.memory)&&(w=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:w,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return es(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Ph(n)?await this.browser.waitForDOMStability({timeout:fe}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Q}),this.options?.autoFollowNewTabs&&await eR({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{bc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Mm(e)}}async resolveCommandTemplateStrings(e,t){return yc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?Vc({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Vc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=ib(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ge(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!ci(n.url)&&!ui(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Ar(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=x}let f=this.browser.getViewport()?.height??cn.height,E=this.browser.getViewport()?.width??cn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:x=>this.browser.click(x,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return xc(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(g,h,f,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=A}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!rn(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ea(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Dr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=AR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:A,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:M=>this.browser.typeIntoTarget(n.value,M,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:ea(n)}});h=A,f=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return xc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!rn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!rn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return xc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new sB,h=aB(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await $c({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Xs(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await vR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return yR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await WA({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Dr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=AS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??nn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(fR(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let b=await Vc({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&Tc(n,E.cache?.memory.traces,a)}}let f=await hR({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await ur({action:async()=>TR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Cn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Nm(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Cn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Oc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Oc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new Cn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Cn(n.requestMatcher),async(h,f)=>{let E=await Dr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=zS.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new Fc({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}};import{cloneDeep as lB}from"lodash-es";import MR from"truncate-json";var wR=1e3,RR=5e6,cB=5*1024*1024;function _R(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=MR(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":CR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":CR(n),_R(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function CR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function xR(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function Kc(r,e){let t=lB(r);if(_R(t,e),t.length>wR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,wR);let n=xR(t,e);if(n.length>RR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>RR;)t.pop(),n=xR(t,e);let{jsonString:o}=MR(n,cB);try{return tr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as uB}from"async_hooks";var ts=new uB;function dB(r){ts.enterWith({activeTracers:[r]})}function pB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function mB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ts.run({activeTracers:n},e)}var Jr={globalAls:ts,initializeRootTracerContext:dB,withChildTracer:pB,withChildTracerAsync:mB};var po=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return Jr.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await Jr.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg})):a=await Jr.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await k(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function we(){let r=Jr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new po}async function PR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=gB(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function gB(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as OB}from"fs";import{tmpdir as LB}from"os";import FR from"path";import{diff as PB}from"deep-object-diff";import{cloneDeep as IB}from"lodash-es";import LR from"fontoxpath";import hB from"@prettier/plugin-xml";import fB from"prettier";import{DOMParser as SB,XMLSerializer as yB}from"slimdom";var bB=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function rs(r){let e=r.toLowerCase();return e.endsWith("webview")||bB.has(e)}function EB(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var TB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),vB=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),AB=new Set(["text","hint"]),wB=new Set(["live-region","drawing-order"]),RB=new Set(["displayed","enabled"]);function CB(r,e){let t={};for(let[n,o]of Object.entries(e))TB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||vB.has(n)&&o==="false"||AB.has(n)&&o===""||RB.has(n)&&o==="true"||wB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function IR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let m=p.name,g=p.value;g!=null&&(l[m]=String(g))}let u=CB(e.tagName,l);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),rs(e.tagName)){let p=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4102
+ ${r}`;default:return r}}var qF=15;async function Vc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=qF}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Rc(c),u=0,d=Date.now(),p,m,g;try{await ur({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await X(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await ur({action:async()=>{let b=await uR(s,t,n.abortSignal);return m&&m.serializedTree===b.serializedTree&&m.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(m=b,dR({command:r,state:b,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s}),p?.updatedMemory&&Tc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await ur({action:async()=>dR({command:r,state:await uR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function uR(r,e,t){let[n,o]=await Promise.all([Br(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function dR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",A=g;x!=="VISION_ONLY"&&(A=await uo({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(D,V)=>d.getVisualAssertionResult(D,V):(D,V)=>d.getAssertionResult(D,V))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ge(l)});return(w.result||i)&&w.relevantElements&&(m.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await KF(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function KF(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await k(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var YF=75e4,jc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function pR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await XF(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof jc?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function XF(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(JF(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function JF(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>ZF(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function ZF(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await qa({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await Br(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(p)>YF)throw new jc;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:ge(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as gR}from"lodash-es";async function hR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>gh(e.cache)?e.cache:void 0,a=i(),s=gR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=Kv(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&As(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!m&&(g.target=pm(g.target),g.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!rn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=eB(t.assertion),l,u=!1,d=gR(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>QF(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ea(t),targetName:"target"}});return l={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(s.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),l={...m,thoughts:g}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof C)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function QF(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Lt(c,500,!0)},!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Lt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},nn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:nn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:nn*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Yv[n.condition]:Xv[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Wc(c,n.value,n.operation,!!n.negated)){let l=n.negated?oo[n.operation]:io[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${l}`):i=new C("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Wc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function eB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function fR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as tB}from"jimp";async function es(r,e){let t=await r.screenshot(e),n=await tB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as SR}from"jimp";import ng from"jpeg-js";import rB from"pixelmatch";async function yR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!rn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async ee=>es(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await es(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let ie=`${l.width}x${l.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ie}) does not match saved screenshot dimensions (${ee}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await SR.fromBuffer(l.buffer),p={width:l.width,height:l.height},m=await SR.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,b=Math.abs(p.height-g.height),x=Math.abs(p.width-g.width);if(f>E){let ie=d.cover({w:g.width,h:g.height});l.buffer=await ie.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let ie=m.cover({w:p.width,h:p.height});u.buffer=await ie.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,w=rB(ng.decode(u.buffer).data,ng.decode(l.buffer).data,A.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>T*100,V=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${T*100}%.`;if(h&&(V+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",V);return{fail:D,thoughts:V,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:ng.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var nB=3e4;async function $c({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??nB/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let s=a.toString(),c;if(ci(r.url)&&(c=r.url),t&&ui(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let m=s?`${c}?${s}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var oB=5e3;async function TR({timeout:r=nn,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await bR(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await X(s,e.signal),s=Math.min(Math.floor(s*1.5),oB);else return i}return i=await bR(e),i}async function bR({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(ER,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(ER,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?oo.CONTAINS:io.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function ER({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var iB=3e4;async function vR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??iB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(ci(r.url)&&(s=r.url),t&&ui(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var qc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([Br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await uo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([Br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await uo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(a)},langfuseSessionId:s})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Br(this.browser,e)}async locateElement(e){return await rg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await s(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new C("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await ur({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Wu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Ku(i)||$u(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Yu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Rr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await X(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=AR(e.cache);if((!b||l)&&!xu(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!cR(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=T=>!!T&&As(T),A=!0;if(!x(b)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await pR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:m,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let T;try{T=await rg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:m,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof Io&&D.updatedLocatorMemory){let V={id:-1,...i,memory:D.updatedLocatorMemory};Ec({cmd:c,key:d,newTarget:V,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,g),w=await a(M);return Ec({cmd:c,key:d,newTarget:T.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=ge(g)),{result:w,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let M=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,g),w=await a(M);if(Rt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.7"]),Ec({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),A){let D=T.decisions.filter(V=>V.matched);if(D.length!==1)g.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let V=D[0].type;n.recordTargetAutoHeal({healType:V})}}return{result:w,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),Rt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.7"]);let M=!1;if((T instanceof Rr||Wu(T)||Ku(T)||Yu(T)||pf(T)||$u(T)||mf(T))&&(M=!0),T instanceof C&&!M)throw g.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){g.info({err:T},"Failed to execute action with cached target, retrying with AI");let w;return b.memory&&lh(b.memory)&&(w=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:w,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return es(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Ph(n)?await this.browser.waitForDOMStability({timeout:fe}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Q}),this.options?.autoFollowNewTabs&&await eR({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{bc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Mm(e)}}async resolveCommandTemplateStrings(e,t){return yc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?Vc({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Vc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=ib(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ge(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!ci(n.url)&&!ui(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Ar(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=x}let f=this.browser.getViewport()?.height??cn.height,E=this.browser.getViewport()?.width??cn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:x=>this.browser.click(x,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return xc(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(g,h,f,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=A}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!rn(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ea(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Dr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=AR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:A,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:M=>this.browser.typeIntoTarget(n.value,M,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:ea(n)}});h=A,f=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return xc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!rn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!rn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return xc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new sB,h=aB(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await $c({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Xs(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await vR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return yR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await WA({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Dr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=AS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??nn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(fR(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let b=await Vc({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&Tc(n,E.cache?.memory.traces,a)}}let f=await hR({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await ur({action:async()=>TR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Cn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Nm(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Cn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Oc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Oc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new Cn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Cn(n.requestMatcher),async(h,f)=>{let E=await Dr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=zS.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new Fc({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}};import{cloneDeep as lB}from"lodash-es";import MR from"truncate-json";var wR=1e3,RR=5e6,cB=5*1024*1024;function _R(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=MR(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":CR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":CR(n),_R(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function CR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function xR(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function Kc(r,e){let t=lB(r);if(_R(t,e),t.length>wR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,wR);let n=xR(t,e);if(n.length>RR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>RR;)t.pop(),n=xR(t,e);let{jsonString:o}=MR(n,cB);try{return tr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as uB}from"async_hooks";var ts=new uB;function dB(r){ts.enterWith({activeTracers:[r]})}function pB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function mB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ts.run({activeTracers:n},e)}var Jr={globalAls:ts,initializeRootTracerContext:dB,withChildTracer:pB,withChildTracerAsync:mB};var po=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return Jr.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await Jr.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg})):a=await Jr.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await k(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function we(){let r=Jr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new po}async function PR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=gB(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function gB(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as OB}from"fs";import{tmpdir as LB}from"os";import FR from"path";import{diff as PB}from"deep-object-diff";import{cloneDeep as IB}from"lodash-es";import LR from"fontoxpath";import hB from"@prettier/plugin-xml";import fB from"prettier";import{DOMParser as SB,XMLSerializer as yB}from"slimdom";var bB=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function rs(r){let e=r.toLowerCase();return e.endsWith("webview")||bB.has(e)}function EB(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var TB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),vB=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),AB=new Set(["text","hint"]),wB=new Set(["live-region","drawing-order"]),RB=new Set(["displayed","enabled"]);function CB(r,e){let t={};for(let[n,o]of Object.entries(e))TB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||vB.has(n)&&o==="false"||AB.has(n)&&o===""||RB.has(n)&&o==="true"||wB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function IR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let m=p.name,g=p.value;g!=null&&(l[m]=String(g))}let u=CB(e.tagName,l);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),rs(e.tagName)){let p=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4103
4103
  ${p}
4104
- `));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let m=p.nodeType;if(m===3){let g=p.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(m===1){let g=p,h=n.createElement(EB(g.tagName));IR(r,g,h),t.appendChild(h)}}}function xB(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;IR(a,e,s);let c=new yB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function OR(r,e){let t=new SB,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=xB(t,i,o,e);return{xml:await fB.format(c,{parser:"xml",plugins:[hB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function MB(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Yc(r,e){let t=r.idToElement.get(e);if(t)return MB(t)}function og(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Si(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function ig(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function DR({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Si(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Yc(t.graph,r.id)??"",a=og(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=ig(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:m,requirements:g})=>{let h=t.graph.idToElement.get(m);if(!h)return;let f=Yc(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:ig(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return rs(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var NR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Si(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function kR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=we();if(e.type==="WEBVIEW")return _B(e,r);let a=LR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let m of p){let g=LR.evaluateXPathToFirstNode(m.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);NR(g,m.requirements)}})}let s=Si(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");NR(a,e.requirements,e.bounds);let c;for(let[p,m]of n.idToElement.entries())if(m===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=og(n,c)??l,u=Yc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function _B(r,e){let{stateManager:t,logger:n,signal:o}=e,i=we(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function ag(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Qs(e)&&(e[t]={...e[t],[n]:Js.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function UR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Bt=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ge(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=DR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=IB(l),m;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});m=h.thoughts;let f=await t(h.resolvedTarget);return ag({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:A}=await kR({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),T=UR(A),M=PB(p,T);return M&&Object.keys(M).length>0&&this.logger.info({cacheDiffs:M},"Successfully resolved target with cache"),x.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:T}}),E=await t(h);return ag({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Rt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.6"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&Rt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.6"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function NB(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var yi=class extends Bt{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=FR.join(LB(),"momentic","downloads"),s=FR.join(a,this.orgId,i);return OB(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await we().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=we(),n=NB(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var _n=class extends Bt{async doPress({keycode:e,longPress:t}){await we().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var BR=25,Xc=class extends Bt{async doType(e){let t=we();if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await we().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i,resolution:a}=t;await i.browser.typeIntoTarget(e.text,a,{clearContent:e.clearContent,delay:e.keyPressDelayMs??BR,forceClearContent:e.forceClearContent})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new yi(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=we(),n=e.keyPressDelayMs??BR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<2e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=we();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new _n(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var sg=.8,bi=.2,DB=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Jc=class extends Bt{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=DB.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*bi),n=Math.floor(e.height*bi);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*bi),l=Math.floor(s*bi);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=we();if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>we().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*bi),s=Math.floor(i*bi);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??sg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??sg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=sg,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{randomUUID as kB}from"crypto";import os from"fs";import{tmpdir as UB}from"os";import Ei from"path";var Zc=class extends Bt{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${Ei.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(os.existsSync(n))o=n;else if(os.existsSync(Ei.join("/",n)))o=Ei.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{os.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Ei.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{os.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Ei.extname(t)||".apk",o=Ei.join(UB(),`momentic-apk-${kB()}${n}`);return os.writeFileSync(o,e),o}};import{existsSync as FB,readFileSync as BB}from"fs";import zB from"zod";var HB=zB.string().url();async function zR(r){if(HB.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!FB(r))throw new Error(`File does not exist at path: ${r}`);return BB(r).toString("base64")}import{execSync as VR}from"child_process";import jB from"pixelmatch";import{_android as WB,chromium as $B}from"playwright";import{PNG as jR}from"pngjs";import{z as $e}from"zod";var HR=$e.array($e.object({proc:$e.string(),webview:$e.string(),info:$e.object({"Android-Package":$e.string(),Browser:$e.string(),"Protocol-Version":$e.string(),"User-Agent":$e.string(),"V8-Version":$e.string(),"WebKit-Version":$e.string(),webSocketDebuggerUrl:$e.string()}),pages:$e.array($e.object({description:$e.string(),devtoolsFrontendUrl:$e.string(),id:$e.string(),title:$e.string(),type:$e.string(),url:$e.string(),webSocketDebuggerUrl:$e.string()})),webviewName:$e.string()}));var Qc=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,p;if(l)p=l;else{t.warn("No playwright device provided, using ADB to find device");let g=(await WB.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);p=g[0]}return new r({driver:e,context:d,logger:t,device:p,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=1){let t=we(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await we().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1,u=(d,p)=>{let m=Buffer.from(d,"base64"),g=Buffer.from(p,"base64"),h=jR.sync.read(m),f=jR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,x=Buffer.alloc(E*b*4);return jB(h.data,f.data,x,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){l=!0;break}c=d,await X(250,t)}l||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(rs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Si(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await we().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await we().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await OR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await we().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let s;if(i==="com.android.chrome"?(this.logger.info({webviewInfo:a},`Connecting Playwright to Android Chrome: ${o.webview}`),s=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info({webviewInfo:a},`Connecting Playwright to webview: ${o.webview}`),s=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!s)continue;a.browserController=s,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await we().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=VR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await we().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),HR.parse(t).filter(o=>{if(!o.webviewName)return!0;let i=o.pages.filter(a=>{if(!a.title)return!1;let s=a.url;return!(!s||s===""||s.startsWith("about:blank")||s.startsWith("chrome-error:"))});return i||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await we().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await Qa.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new qc({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new hl})})}async connectPlaywrightToWebview(e,t){return we().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(l=>!(l.pkg()!==e||"_socketName"in l&&typeof l._socketName=="string"&&l._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await we().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await $B.connectOverCDP({endpointURL:o,timeout:8e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=VR(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Ti=class r extends Bt{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c,limbarClient:l,playwrightDevice:u}){let d={controller:s},p=await Qc.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),m=new r({driver:e,generator:t,stateManager:p,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await m.initializeSettings(),m}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${KB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await yc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{bc(e.command,n)}}async executeCommandHelper({command:e}){let t=we();switch(e.type){case"TAP":return new yi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new Xc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Rc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await X(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let m=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ge(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(m.result)return{success:m.result,message:m.thoughts};{let g=`AssertionFailureError: ${m.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Jc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Dr({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new YB,i=qB(fetch,o),a=Date.now(),s=await $c({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Xs(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new _n(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
4104
+ `));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let m=p.nodeType;if(m===3){let g=p.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(m===1){let g=p,h=n.createElement(EB(g.tagName));IR(r,g,h),t.appendChild(h)}}}function xB(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;IR(a,e,s);let c=new yB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function OR(r,e){let t=new SB,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=xB(t,i,o,e);return{xml:await fB.format(c,{parser:"xml",plugins:[hB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function MB(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Yc(r,e){let t=r.idToElement.get(e);if(t)return MB(t)}function og(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Si(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function ig(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function DR({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Si(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Yc(t.graph,r.id)??"",a=og(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=ig(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:m,requirements:g})=>{let h=t.graph.idToElement.get(m);if(!h)return;let f=Yc(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:ig(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return rs(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var NR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Si(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function kR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=we();if(e.type==="WEBVIEW")return _B(e,r);let a=LR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let m of p){let g=LR.evaluateXPathToFirstNode(m.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);NR(g,m.requirements)}})}let s=Si(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");NR(a,e.requirements,e.bounds);let c;for(let[p,m]of n.idToElement.entries())if(m===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=og(n,c)??l,u=Yc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function _B(r,e){let{stateManager:t,logger:n,signal:o}=e,i=we(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function ag(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Qs(e)&&(e[t]={...e[t],[n]:Js.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function UR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Bt=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ge(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=DR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=IB(l),m;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});m=h.thoughts;let f=await t(h.resolvedTarget);return ag({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:A}=await kR({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),T=UR(A),M=PB(p,T);return M&&Object.keys(M).length>0&&this.logger.info({cacheDiffs:M},"Successfully resolved target with cache"),x.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:T}}),E=await t(h);return ag({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Rt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.7"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&Rt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.7"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function NB(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var yi=class extends Bt{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=FR.join(LB(),"momentic","downloads"),s=FR.join(a,this.orgId,i);return OB(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await we().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=we(),n=NB(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var _n=class extends Bt{async doPress({keycode:e,longPress:t}){await we().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var BR=25,Xc=class extends Bt{async doType(e){let t=we();if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await we().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i,resolution:a}=t;await i.browser.typeIntoTarget(e.text,a,{clearContent:e.clearContent,delay:e.keyPressDelayMs??BR,forceClearContent:e.forceClearContent})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new yi(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=we(),n=e.keyPressDelayMs??BR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<2e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=we();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new _n(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var sg=.8,bi=.2,DB=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Jc=class extends Bt{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=DB.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*bi),n=Math.floor(e.height*bi);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*bi),l=Math.floor(s*bi);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=we();if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>we().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*bi),s=Math.floor(i*bi);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??sg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??sg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=sg,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{randomUUID as kB}from"crypto";import os from"fs";import{tmpdir as UB}from"os";import Ei from"path";var Zc=class extends Bt{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${Ei.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(os.existsSync(n))o=n;else if(os.existsSync(Ei.join("/",n)))o=Ei.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{os.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Ei.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{os.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Ei.extname(t)||".apk",o=Ei.join(UB(),`momentic-apk-${kB()}${n}`);return os.writeFileSync(o,e),o}};import{existsSync as FB,readFileSync as BB}from"fs";import zB from"zod";var HB=zB.string().url();async function zR(r){if(HB.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!FB(r))throw new Error(`File does not exist at path: ${r}`);return BB(r).toString("base64")}import{execSync as VR}from"child_process";import jB from"pixelmatch";import{_android as WB,chromium as $B}from"playwright";import{PNG as jR}from"pngjs";import{z as $e}from"zod";var HR=$e.array($e.object({proc:$e.string(),webview:$e.string(),info:$e.object({"Android-Package":$e.string(),Browser:$e.string(),"Protocol-Version":$e.string(),"User-Agent":$e.string(),"V8-Version":$e.string(),"WebKit-Version":$e.string(),webSocketDebuggerUrl:$e.string()}),pages:$e.array($e.object({description:$e.string(),devtoolsFrontendUrl:$e.string(),id:$e.string(),title:$e.string(),type:$e.string(),url:$e.string(),webSocketDebuggerUrl:$e.string()})),webviewName:$e.string()}));var Qc=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,p;if(l)p=l;else{t.warn("No playwright device provided, using ADB to find device");let g=(await WB.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);p=g[0]}return new r({driver:e,context:d,logger:t,device:p,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=1){let t=we(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await we().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1,u=(d,p)=>{let m=Buffer.from(d,"base64"),g=Buffer.from(p,"base64"),h=jR.sync.read(m),f=jR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,x=Buffer.alloc(E*b*4);return jB(h.data,f.data,x,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){l=!0;break}c=d,await X(250,t)}l||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(rs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Si(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await we().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await we().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await OR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await we().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let s;if(i==="com.android.chrome"?(this.logger.info({webviewInfo:a},`Connecting Playwright to Android Chrome: ${o.webview}`),s=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info({webviewInfo:a},`Connecting Playwright to webview: ${o.webview}`),s=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!s)continue;a.browserController=s,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await we().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=VR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await we().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),HR.parse(t).filter(o=>{if(!o.webviewName)return!0;let i=o.pages.filter(a=>{if(!a.title)return!1;let s=a.url;return!(!s||s===""||s.startsWith("about:blank")||s.startsWith("chrome-error:"))});return i||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await we().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await Qa.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new qc({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new hl})})}async connectPlaywrightToWebview(e,t){return we().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(l=>!(l.pkg()!==e||"_socketName"in l&&typeof l._socketName=="string"&&l._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await we().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await $B.connectOverCDP({endpointURL:o,timeout:8e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=VR(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Ti=class r extends Bt{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c,limbarClient:l,playwrightDevice:u}){let d={controller:s},p=await Qc.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),m=new r({driver:e,generator:t,stateManager:p,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await m.initializeSettings(),m}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${KB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await yc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{bc(e.command,n)}}async executeCommandHelper({command:e}){let t=we();switch(e.type){case"TAP":return new yi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new Xc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Rc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await X(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let m=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ge(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(m.result)return{success:m.result,message:m.thoughts};{let g=`AssertionFailureError: ${m.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Jc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Dr({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new YB,i=qB(fetch,o),a=Date.now(),s=await $c({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Xs(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new _n(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
4105
4105
  `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new _n(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new _n(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new Zc(this.constructPerformerParams()).doInstallApk(e);case"ADD_FILE":{let n=await zR(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await PR({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function WR({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,m=r.handshake.query?.fileName,g=m?.endsWith("test.yaml")?m.slice(0,-"test.yaml".length):m,h=Cr.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,x=h.settings?.defaultApkFilePath?.trim(),A=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:A});let M={...(await u(A,e)).emulator,...h.settings?.emulator},w;if(M.region==="local"){if(!M.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");w={avdId:M.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:x||void 0}}else w={region:M.region,apkToInstall:E?{channel:E,tag:b}:void 0};let D=Date.now(),{driver:V,cleanup:ie,emulatorName:ee,adbPort:he,limbarClient:st,limbarToken:W,limbarUrl:B,playwrightDevice:ae}=await t({socket:r,logger:e,creationOpts:w}),ce=await Sc({driver:V,onLogs:Eo=>{r.emit("logcatLogs",Eo)}});e.info({adbPort:he,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:ee},"Android emulator session initiated"),e=e.child({emulator:ee});let Ze=await o(A,e),Ce=await i(A,e),zt=await a(A,e),St=await s(A),Pe=c?await c(A):void 0,qe={};h.settings?.defaultEnv&&(qe=(await St.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let pr=new zo({variablesFromEnvironment:qe,envName:h.settings?.defaultEnv,testName:g}),Ct=await Ti.init({driver:V,generator:Ze,logger:e,limbarClient:st,playwrightDevice:ae,options:{emulator:M},fixtures:{storage:St,browserEnricher:zt,browserGenerator:Ce,localCodeEvalTools:Pe,testContext:pr},orgId:A,adbPort:he,abortController:new AbortController});if(!r.connected)throw await ce(),await ie(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Hr=XB({socket:r,testContext:pr}),bo=async()=>{clearInterval(Hr);try{await ce(),await ie(),await Ct.cleanup()}catch(Eo){e.warn({err:Eo},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:Ct,cleanup:bo,emulatorName:ee,local:M.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:B,limbarToken:W}),{sessionId:d,testId:f,orgId:A,emulatorName:ee,logger:e}}function XB({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function $R({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var JB=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},qR={event:"cancel",createHandler:JB};var ZB=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let s=await i.controller.getA11yTree();o({a11yTree:s})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},KR={event:"fetchA11yTree",createHandler:ZB};import{diff as hz}from"deep-object-diff";import{cloneDeep as fz}from"lodash-es";function YR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await k(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function XR(r){let e=Date.now(),t=r.fixtures.controller;try{return await QB(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function QB({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await ez({step:n,params:e}),s={};Object.entries(a).forEach(([p,m])=>{s[p]=JSON.stringify(m)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),aA({result:c,...iA(d)}),c}async function ez({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await Dr({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as JR}from"crypto";async function ZR({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(l){i.warn({err:l},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let l=await a.executeCommand({command:e.command});c={...e,status:l.success?"SUCCESS":"FAILED",message:l.message,startTime:o,endTime:Date.now(),data:l.output}}catch(l){l instanceof Error&&l.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:l},"Failed to execute preset step"),c={...e,status:"FAILED",message:l instanceof Error?l.message:String(l),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let l=JR(),u=await a.getScreenshotBase64();c.afterSnapshot=l,n.attachAfterScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(u,"base64")})}catch(l){i.warn({err:l},"Failed to take after screenshot")}if(s){let l=JR();c.beforeSnapshot=l,n.attachBeforeScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(s,"base64")})}}}return c}import{streamText as dz}from"ai";import{randomUUID as pz}from"crypto";var eu=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as cz,stepCountIs as uz}from"ai";var QR="get_emulator_state",tu="finish";import eC from"dedent";var rz=eC`
4106
4106
  You cannot interact with the user directly. If you feel like you need to ask the user for clarification, or you are stuck, call the "finish" tool with success=false. Never output text without calling a tool.
4107
4107
  `,tC=r=>eC`
@@ -4139,7 +4139,7 @@ Momentic users value the following:
4139
4139
  ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function Jz(r){let e=Yz(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${wi}`)),n=AbortSignal.timeout(2e3),o;try{o=await Vz(t,{absolute:!1,cwd:hg(),dotRelative:!1,maxDepth:gg,nodir:!0,signal:n})}catch(a){throw R.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${fg} is misconfigured.`),a}let i=[];for(let a of o){let s=ho.join(hg(),a),c=Sg(s);c&&i.push({configFilePath:s,config:c,rootDir:fC(s)})}return i}async function Zz(r){if(r){r=ho.resolve(r);let t=Sg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:ho.dirname(r)}]}if(Bz(fg)){let t=await Jz(fg);if(t)return t}return Xz()}function bC(r,e){let t=SC.stringify(r);Gz(e,t)}import{z as yg}from"zod";var EC="test-results";var mOe=yg.object({width:yg.number(),height:yg.number()});import{execFile as Qz}from"node:child_process";import{promisify as e1}from"node:util";import t1 from"simple-git";var Ie=t1(),TC=e1(Qz);async function r1(r){let e=await Oe(r,Ie.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
4140
4140
  `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function n1(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await TC("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await TC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function o1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return n1(r,e,t);if(o)return}catch{}}function iu(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function i1(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function a1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function s1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function l1(r){let[e,t,n,o]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?iu(t):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function c1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?iu(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function u1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?iu(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function d1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Oe(r,Ie.revparse(["HEAD"])),Oe(r,Ie.revparse(["--short","HEAD"])),Oe(r,Ie.revparse(["--abbrev-ref","HEAD"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"])),e?Oe(r,Ie.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),r1(r)]),d=l?await Oe(r,Ie.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?iu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await o1(r,i,u)??E??void 0;return{ciProvider:"none",gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function p1(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function m1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ls(r,e){let t=i1();if(!t)return d1(r,e);switch(t){case"GithubActions":return a1(r);case"GitlabCI":return s1(r);case"CircleCI":return l1(r);case"Buildkite":return c1(r);case"AzureDevOps":return u1(r);case"GCPCloudBuild":return p1()}}async function g1(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function h1(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(t,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function f1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await h1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await g1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ri(r,e,t){let n=await m1(t),o=await ls(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await f1(r,e,i);return{...n,...o,...a}}import{diff as vC}from"deep-object-diff";import In from"fs";import{cloneDeep as S1}from"lodash-es";import au from"path";import{v4 as y1}from"uuid";import cs from"yaml";function AC({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!In.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=In.readFileSync(i,"utf-8"),s=cs.parse(a),c={...s,...r,schemaVersion:e},l=no({fileType:xe.MOBILE_MODULE,...da.parse(c),steps:Sr.array().parse(r.steps)}),u=vC(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=cs.stringify(l);In.writeFileSync(i,d,"utf-8"),Pn(i,n.config)}function wC({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=us(i,o),s={...a,...e},c=no({fileType:xe.MOBILE_MODULE,...nl.parse(s)}),l=vC(c,a);if(l&&Object.keys(l).length===0)return;let u=cs.stringify(c);In.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${Wr(e.name)}.module.yaml`;if(d=au.join(au.dirname(i),p),In.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);In.renameSync(i,d)}Pn(d||i,n.config)}async function RC({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Wr(r),s=au.join(o,`${a}.module.yaml`),c=y1(),{stepsToSave:l}=await An({steps:n}),u={schemaVersion:sn,moduleId:c,description:e,enabled:t},d={fileType:xe.MOBILE_MODULE,...u,steps:l},p=cs.stringify(FS.parse(d));return In.writeFileSync(s,p,"utf-8"),Pn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function us(r,e){let t=In.readFileSync(r,"utf-8"),n=cs.parse(t);try{return{...nl.parse(n),name:au.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function bg(r,e,t,n){let o=us(r.fullFilePath,t),{resolvedSteps:i}=await vc({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async s=>{let c=e.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${s}`);return us(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,description:o.description||void 0,steps:i};return n&&(n[r.id]=S1(a)),a}async function CC(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await bg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as b1}from"crypto";import fo from"fs";import Eg from"path";import su from"yaml";function xC({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Wr(r)}.test.yaml`,s=Eg.join(o,a);if(fo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:xe.MOBILE_TEST,id:b1(),description:e,schemaVersion:nd,settings:n,steps:t},l=su.stringify(c);return fo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function E1(r){if(!fo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=fo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
4141
4141
  `),t=su.parse(e),n=ol.parse(t);if(n.fileType!==xe.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function lu(r,e,t){let n=E1(r),o;try{o=Cr.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await eA({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return us(c,e)}});return{...o,steps:i.steps}}async function MC({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=Eg.isAbsolute(r)?r:Eg.join(n,r);if(!fo.existsSync(a))throw new Error(`Test file not found: ${a}`);let s=fo.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
4142
- `),c=su.parse(s),l=ol.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await An({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=su.stringify(ol.parse(d));for(let m of u?.moduleUpdates??[])AC({content:m,schemaVersion:nd,momenticFiles:i,project:o});fo.writeFileSync(a,p,"utf-8"),Pn(a,o.config)}import{randomUUID as T1}from"crypto";import On from"fs";import Ci from"path";var _C=new Set([".DS_Store","__MACOSX"]),PC={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function v1(r,e,t){if(PC[t]){let i=PC[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var Tg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function IC(r,e){try{let t=Ci.join(e,"metadata.json");return Sl.parse(JSON.parse(On.readFileSync(t,"utf-8")))}catch{throw new Tg(r,e)}}function OC(r,e,t){let n=T1(),o=r.child({runGroupId:n});On.rmSync(e,{recursive:!0,force:!0});let i=On.readdirSync(t).filter(c=>!_C.has(c)).map(c=>Ci.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);On.mkdirSync(e,{recursive:!0});let a={...IC(t,i[0]),id:n};for(let c of i){let l=Ci.join(c,"runs");if(!On.existsSync(l))continue;let u=IC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=v1(a,u,m)}let d=On.readdirSync(l);for(let p of d){if(_C.has(p))continue;let m=Ci.join(l,p),g=Ci.join(e,"runs",p);On.cpSync(m,g,{recursive:!0})}}let s=Ci.join(e,"metadata.json");On.writeFileSync(s,JSON.stringify(a,null,2))}import NC from"adm-zip";import xg from"fs";import{z as _1}from"zod";var U="v1",vg="mobile-cli",So="0.4.6";var A1=9e4,w1=3,R1=1500,C1=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function x1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Ag=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return So&&(e[gl]=So),vg&&(e[hy]=vg),e}async sendRequest(e,t){let{retries:n=w1,requestTimeoutMs:o=A1,initialRetryDelayMs:i=R1,maxRetryDelayMs:a=C1,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(p){u=p;try{s?.(u)}catch{}if(p instanceof Tr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new fn),c===0)throw u;let m=l-c,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let p=await x1(u);throw new Tr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},zr=class extends Ag{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[gy]:this.mode??""}}};import{createAnthropic as M1}from"@ai-sdk/anthropic";var cu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[gl]:So??"",...t&&{[Sy]:t},...n||{}};return o&&(a[fy]=JSON.stringify(o)),M1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var yo=class extends zr{agentConfig;constructor(e,t){let n={...pS,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Qf.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:So,...e},signal:t.abortSignal});return Zf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return _1.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ty.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return qd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ey.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return by.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return qd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return yy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ad.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return vy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return od.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Pf.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return If.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ju.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return dS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return xf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return ih.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return cu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as wg}from"zod";var vr=class extends zr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{R.warn(`API key check failed: ${t.message}`)}});return Dy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Iy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return wy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ay.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ny.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ky.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Jy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Kf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return By.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return zy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Hy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return eb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Jd.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ba.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Jd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return wg.record(wg.string(),wg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Gy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Vy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return jy.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Wy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Rg(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var uu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var xi=class extends zr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ah.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Mi=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as P1,en as I1}from"@faker-js/faker";var _i="v1",Pi=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new P1({locale:I1}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${_i}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Tr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${_i}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${_i}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${_i}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${_i}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${_i}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function LC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var du=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await LC(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var Ii=class extends zr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return SS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return cu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function pu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new fl:new Cg(r,e,t,o)}var Cg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Kd(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&um({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await An({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import mu from"path";function O1(r){let e=new NC,t=mu.join(r,"metadata.json"),n=Sl.parse(JSON.parse(xg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of xg.readdirSync(mu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new NC(mu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(mu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function gu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!xg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new du(e);try{let{runGroupId:i,buffer:a}=O1(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import L1 from"adm-zip";import ht from"fs";import Vt from"path";var ds=class r{constructor(e){this.filePath=e;ht.rmSync(this.filePath,{recursive:!0,force:!0}),ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){ht.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(ht.existsSync(t))return ht.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{ht.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return ht.createWriteStream(t)}createRunArchive(e){return new Mg(Vt.join(this.filePath,"runs"),e)}},Mg=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),ht.rmSync(this.tempPath,{recursive:!0,force:!0}),ht.rmSync(this.finalPath,{recursive:!0,force:!0}),ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(ht.existsSync(t))return ht.readFileSync(t)}mkdir(e){ht.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ds(Vt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);ht.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return ht.createWriteStream(t)}close(){let e=new L1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();ht.writeFileSync(this.finalPath,t),ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import vu from"fs";import XC from"body-parser";import eH from"cors";import tH from"dedent";import{Router as U1}from"express";import Nt from"fs";import{globSync as F1}from"glob";import ut from"path";import hu from"fs";import N1 from"path";var D1=new Ic(30,60*1e3),Og="https://api.momentic.ai",Pg,kC=r=>{Og=r},Lg=()=>Og,ps=()=>Pg;var Oi,Ig,DC,UC=async r=>{if(Pg&&Oi&&DC)return Oi;let e=new vr({baseUrl:Og,apiKey:r,logger:R});Pg=e;try{let t=await e.getAuthInfo();return Oi=t.orgId,Ig=t.userId,DC=r,Oi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Li=()=>{if(!Oi)throw new Error("Your organization ID is invalid.");return Oi},fu=()=>{if(!Ig)throw new Error("Your user ID is invalid.");return Ig};var Ng,_g,FC=(r,e)=>{Ng=r,_g?.abort(),_g=new AbortController;let t=_g.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=N1.resolve(r.rootDir,o.envFile);try{if(hu.lstatSync(i).isSymbolicLink())return;hu.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{k1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},ze=()=>Ng;function k1({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(D1.increment("setLocalProject")&&R.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),Ng=await Promise.resolve(e(n.configFilePath)))};hu.watchFile(o,{persistent:!1},i);let a=()=>{hu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ve(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var gs=U1();function ms(r){let e=ze(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function B1(r){let e=ze(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function z1(r,e){let t=Nt.statSync(r),n=B1(r);return Hd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}gs.post("/",Ve(async(r,e,t)=>{let n;try{n=ey.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ms(n);if(!Nt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Nt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=ze(),s=Array.from(a.config.exclude??[]).concat(cl),l=F1("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ut.join(o,d);return z1(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));gs.put("/",Ve(async(r,e,t)=>{let n;try{n=ty.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ms(n);if(Nt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Nt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));gs.patch("/",Ve(async(r,e,t)=>{let n,o;try{let l=ry.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=ms(n),a=ms(o);if(!Nt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Nt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let s=ut.dirname(a);Nt.existsSync(s)||Nt.mkdirSync(s,{recursive:!0}),Nt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));gs.delete("/",Ve(async(r,e,t)=>{let n,o=!0;try{let c=ny.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=ms(n);if(!Nt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Nt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Nt.rmSync(i,{recursive:!0,force:!0});else{if(Nt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Nt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Dg=gs;import{Router as V1}from"express";import{hostname as H1}from"os";var G1="0.4.6",hs=$o({app:"desktop-server",hostname:H1(),disableConsoleLogs:!0}).child({cliVersion:G1});(async()=>{try{let r=await ls(hs);r.gitBranchName&&hs.addBinding("branch",r.gitBranchName)}catch{}})();var BC=V1();BC.get("/",async(r,e)=>{let t=ze(),n=ps();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ri(hs,n,t);e.status(200).json(o)});var kg=BC;import rH from"events";import JC,{Router as nH}from"express";import oH from"http";import iH from"path";var Su=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var zC=new Su;import{Router as W1}from"express";import{existsSync as $1}from"fs";import q1 from"path";import{hostname as j1}from"os";var Ug="0.4.6",ft=$o({app:"mobile-desktop-server",hostname:j1(),disableConsoleLogs:!0}).child({cliVersion:Ug});(async()=>{try{let r=await ls(ft);r.gitBranchName&&ft.addBinding("branch",r.gitBranchName)}catch{}})();var Fg=W1();Fg.get("/",Ve(async(r,e)=>{let t=ps();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Fg.post("/upload-url",Ve(async(r,e)=>{let t;try{t=cy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ps();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=q1.resolve(t.filePath);if(!$1(o)){e.status(400).json({error:`File not found: ${o}`});return}await fc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:ft}),e.sendStatus(204)}));var HC=Fg;import{Router as X1}from"express";import{Router as K1}from"express";import GC from"fs";import Y1 from"path";var fs=K1();async function Bg(r){return(await CC(r,ft)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}fs.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Bg(n);e.status(200).json(o)}));fs.get("/:moduleId",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(ze()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await bg(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));fs.patch("/:moduleId/metadata",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=uy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ze(),o=await dr(n);wC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));fs.post("/",Ve(async(r,e)=>{let t;try{t=dy.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{Qi(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=ze(),i=(await dr(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=Y1.join(n.rootDir,t.folderPath??"");if(!GC.existsSync(a)||!GC.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await RC({...t,folder:a,project:n});e.status(201).json(s)}));var VC=fs;var jC=X1();jC.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Bg(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var WC=jC;import{Router as J1}from"express";var zg=J1();zg.get("/",Ve((r,e)=>{let t=mC(ze(),ft);e.status(200).json(t)}));zg.get("/names",Ve((r,e)=>{let n=ze().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var $C=zg;import{Router as Z1}from"express";var qC=Z1();qC.get("/",(r,e)=>{e.status(200).json({userId:fu(),orgId:Li(),cliVersion:Ug??"0.0.0"})});var KC=qC;import{Router as Q1}from"express";import Hg from"path";var yu=Q1();yu.patch("/:testPath",Ve(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ly.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=ze(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await MC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));yu.post("/",Ve((r,e)=>{let t;try{t=sy.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Qi(n)}catch(g){e.status(400).json({error:g.message});return}let s=ze(),c=Hg.join(s.rootDir,...a),{fullPath:l,testId:u}=xC({name:n,description:o,steps:[],settings:i,folder:c}),d=Hg.basename(l),p=Hg.relative(s.rootDir,l),m={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(m)}));yu.get("/:fileName",Ve(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=ze(),i=await dr(o),s=await lu(n,ft,i);e.status(200).json(s)}));var YC=yu;var bu=class extends Mi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ze();return is(t,o,R)}};var ZC="10mb";async function QC(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&kC(n),await UC(t);let u=Li(),d=fu(),p=r.logger.child({orgId:u,userId:d});FC(i,w=>ss({configFilePath:w}));let m=JC();m.use(eH()),m.use(XC.json({limit:ZC})),m.use(XC.urlencoded({extended:!1,limit:ZC}));let g=nH();if(g.use("/folders",Dg),g.use("/entities",WC),g.use("/identify",KC),g.use("/mobile-tests",YC),g.use("/mobile-modules",VC),g.use("/assets",HC),g.use("/git",kg),g.use("/environments",$C),m.use("/api",g),m.use((w,D,V)=>{R.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),ft.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),V()}),m.use((w,D,V,ie)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){V.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),ft.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),V.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=JC.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(w),m.use("*",(D,V)=>{V.sendFile(iH.join(o,"index.html"))})}let h=oH.createServer(m),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?aH(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Lg(),apiKey:t,logger:p},x=new vr(b),A=ze(),T={...b,mode:"interactive"},{dispose:M}=dC({baseServer:h,logger:p,authorization:b,globalStateManager:zC,getOrgId:()=>Li(),androidDriverFactory:async({socket:w,logger:D,creationOpts:V})=>{let ie=Math.floor(Math.random()*1e4)+4e4,ee=await Tl(ie,"appium");return hc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:V,socket:w,appiumPort:ee,sessionId:w.id,orgId:Li(),onStatusUpdate:he=>{w.emit("connectionStatusUpdate",{message:he})}})},mobileGeneratorFactory:async w=>new Ii({baseUrl:Lg(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async w=>new yo(A.config.ai?.agentConfig,T),browserEnricherFactory:async w=>new xi(T,new yo(A.config.ai?.agentConfig,T)),storageFactory:async w=>new bu(x,w),cacheStorageFactory:async w=>{let D=await Ri(p,x,A);return pu({orgId:w,client:x,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Pi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await M(),await Rt.flush()}catch(w){R.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await M(),await Rt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await M(),await Rt.flush()}finally{h.close(()=>process.exit(0))}})}rH.setMaxListeners(25);process.on("warning",r=>{ft.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{ft.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{ft.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function aH(r){R.error(tH`Port ${r} is already in use by another process. Please close the other process and try again.
4142
+ `),c=su.parse(s),l=ol.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await An({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=su.stringify(ol.parse(d));for(let m of u?.moduleUpdates??[])AC({content:m,schemaVersion:nd,momenticFiles:i,project:o});fo.writeFileSync(a,p,"utf-8"),Pn(a,o.config)}import{randomUUID as T1}from"crypto";import On from"fs";import Ci from"path";var _C=new Set([".DS_Store","__MACOSX"]),PC={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function v1(r,e,t){if(PC[t]){let i=PC[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var Tg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function IC(r,e){try{let t=Ci.join(e,"metadata.json");return Sl.parse(JSON.parse(On.readFileSync(t,"utf-8")))}catch{throw new Tg(r,e)}}function OC(r,e,t){let n=T1(),o=r.child({runGroupId:n});On.rmSync(e,{recursive:!0,force:!0});let i=On.readdirSync(t).filter(c=>!_C.has(c)).map(c=>Ci.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);On.mkdirSync(e,{recursive:!0});let a={...IC(t,i[0]),id:n};for(let c of i){let l=Ci.join(c,"runs");if(!On.existsSync(l))continue;let u=IC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=v1(a,u,m)}let d=On.readdirSync(l);for(let p of d){if(_C.has(p))continue;let m=Ci.join(l,p),g=Ci.join(e,"runs",p);On.cpSync(m,g,{recursive:!0})}}let s=Ci.join(e,"metadata.json");On.writeFileSync(s,JSON.stringify(a,null,2))}import NC from"adm-zip";import xg from"fs";import{z as _1}from"zod";var U="v1",vg="mobile-cli",So="0.4.7";var A1=9e4,w1=3,R1=1500,C1=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function x1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Ag=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return So&&(e[gl]=So),vg&&(e[hy]=vg),e}async sendRequest(e,t){let{retries:n=w1,requestTimeoutMs:o=A1,initialRetryDelayMs:i=R1,maxRetryDelayMs:a=C1,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(p){u=p;try{s?.(u)}catch{}if(p instanceof Tr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new fn),c===0)throw u;let m=l-c,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let p=await x1(u);throw new Tr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},zr=class extends Ag{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[gy]:this.mode??""}}};import{createAnthropic as M1}from"@ai-sdk/anthropic";var cu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[gl]:So??"",...t&&{[Sy]:t},...n||{}};return o&&(a[fy]=JSON.stringify(o)),M1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var yo=class extends zr{agentConfig;constructor(e,t){let n={...pS,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Qf.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:So,...e},signal:t.abortSignal});return Zf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return _1.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ty.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return qd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ey.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return by.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return qd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return yy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ad.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return vy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return od.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Pf.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return If.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ju.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return dS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return xf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return ih.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return cu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as wg}from"zod";var vr=class extends zr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{R.warn(`API key check failed: ${t.message}`)}});return Dy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Iy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return wy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ay.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ny.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ky.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Jy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Kf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return By.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return zy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Hy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return eb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Jd.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ba.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ba.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Jd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return wg.record(wg.string(),wg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Gy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Vy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return jy.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Wy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Rg(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var uu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var xi=class extends zr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ah.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Mi=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as P1,en as I1}from"@faker-js/faker";var _i="v1",Pi=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new P1({locale:I1}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${_i}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Tr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${_i}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${_i}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${_i}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${_i}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${_i}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function LC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var du=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await LC(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var Ii=class extends zr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return SS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return cu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function pu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new fl:new Cg(r,e,t,o)}var Cg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Kd(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&um({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await An({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import mu from"path";function O1(r){let e=new NC,t=mu.join(r,"metadata.json"),n=Sl.parse(JSON.parse(xg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of xg.readdirSync(mu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new NC(mu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(mu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function gu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!xg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new du(e);try{let{runGroupId:i,buffer:a}=O1(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import L1 from"adm-zip";import ht from"fs";import Vt from"path";var ds=class r{constructor(e){this.filePath=e;ht.rmSync(this.filePath,{recursive:!0,force:!0}),ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){ht.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(ht.existsSync(t))return ht.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{ht.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return ht.createWriteStream(t)}createRunArchive(e){return new Mg(Vt.join(this.filePath,"runs"),e)}},Mg=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),ht.rmSync(this.tempPath,{recursive:!0,force:!0}),ht.rmSync(this.finalPath,{recursive:!0,force:!0}),ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(ht.existsSync(t))return ht.readFileSync(t)}mkdir(e){ht.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ds(Vt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);ht.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return ht.createWriteStream(t)}close(){let e=new L1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();ht.writeFileSync(this.finalPath,t),ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import vu from"fs";import XC from"body-parser";import eH from"cors";import tH from"dedent";import{Router as U1}from"express";import Nt from"fs";import{globSync as F1}from"glob";import ut from"path";import hu from"fs";import N1 from"path";var D1=new Ic(30,60*1e3),Og="https://api.momentic.ai",Pg,kC=r=>{Og=r},Lg=()=>Og,ps=()=>Pg;var Oi,Ig,DC,UC=async r=>{if(Pg&&Oi&&DC)return Oi;let e=new vr({baseUrl:Og,apiKey:r,logger:R});Pg=e;try{let t=await e.getAuthInfo();return Oi=t.orgId,Ig=t.userId,DC=r,Oi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Li=()=>{if(!Oi)throw new Error("Your organization ID is invalid.");return Oi},fu=()=>{if(!Ig)throw new Error("Your user ID is invalid.");return Ig};var Ng,_g,FC=(r,e)=>{Ng=r,_g?.abort(),_g=new AbortController;let t=_g.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=N1.resolve(r.rootDir,o.envFile);try{if(hu.lstatSync(i).isSymbolicLink())return;hu.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{k1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},ze=()=>Ng;function k1({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(D1.increment("setLocalProject")&&R.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),Ng=await Promise.resolve(e(n.configFilePath)))};hu.watchFile(o,{persistent:!1},i);let a=()=>{hu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ve(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var gs=U1();function ms(r){let e=ze(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function B1(r){let e=ze(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function z1(r,e){let t=Nt.statSync(r),n=B1(r);return Hd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}gs.post("/",Ve(async(r,e,t)=>{let n;try{n=ey.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ms(n);if(!Nt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Nt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=ze(),s=Array.from(a.config.exclude??[]).concat(cl),l=F1("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ut.join(o,d);return z1(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));gs.put("/",Ve(async(r,e,t)=>{let n;try{n=ty.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ms(n);if(Nt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Nt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));gs.patch("/",Ve(async(r,e,t)=>{let n,o;try{let l=ry.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=ms(n),a=ms(o);if(!Nt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Nt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let s=ut.dirname(a);Nt.existsSync(s)||Nt.mkdirSync(s,{recursive:!0}),Nt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));gs.delete("/",Ve(async(r,e,t)=>{let n,o=!0;try{let c=ny.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=ms(n);if(!Nt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Nt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Nt.rmSync(i,{recursive:!0,force:!0});else{if(Nt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Nt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Dg=gs;import{Router as V1}from"express";import{hostname as H1}from"os";var G1="0.4.7",hs=$o({app:"desktop-server",hostname:H1(),disableConsoleLogs:!0}).child({cliVersion:G1});(async()=>{try{let r=await ls(hs);r.gitBranchName&&hs.addBinding("branch",r.gitBranchName)}catch{}})();var BC=V1();BC.get("/",async(r,e)=>{let t=ze(),n=ps();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ri(hs,n,t);e.status(200).json(o)});var kg=BC;import rH from"events";import JC,{Router as nH}from"express";import oH from"http";import iH from"path";var Su=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var zC=new Su;import{Router as W1}from"express";import{existsSync as $1}from"fs";import q1 from"path";import{hostname as j1}from"os";var Ug="0.4.7",ft=$o({app:"mobile-desktop-server",hostname:j1(),disableConsoleLogs:!0}).child({cliVersion:Ug});(async()=>{try{let r=await ls(ft);r.gitBranchName&&ft.addBinding("branch",r.gitBranchName)}catch{}})();var Fg=W1();Fg.get("/",Ve(async(r,e)=>{let t=ps();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Fg.post("/upload-url",Ve(async(r,e)=>{let t;try{t=cy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ps();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=q1.resolve(t.filePath);if(!$1(o)){e.status(400).json({error:`File not found: ${o}`});return}await fc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:ft}),e.sendStatus(204)}));var HC=Fg;import{Router as X1}from"express";import{Router as K1}from"express";import GC from"fs";import Y1 from"path";var fs=K1();async function Bg(r){return(await CC(r,ft)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}fs.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Bg(n);e.status(200).json(o)}));fs.get("/:moduleId",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(ze()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await bg(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));fs.patch("/:moduleId/metadata",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=uy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ze(),o=await dr(n);wC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));fs.post("/",Ve(async(r,e)=>{let t;try{t=dy.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{Qi(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=ze(),i=(await dr(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=Y1.join(n.rootDir,t.folderPath??"");if(!GC.existsSync(a)||!GC.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await RC({...t,folder:a,project:n});e.status(201).json(s)}));var VC=fs;var jC=X1();jC.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Bg(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var WC=jC;import{Router as J1}from"express";var zg=J1();zg.get("/",Ve((r,e)=>{let t=mC(ze(),ft);e.status(200).json(t)}));zg.get("/names",Ve((r,e)=>{let n=ze().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var $C=zg;import{Router as Z1}from"express";var qC=Z1();qC.get("/",(r,e)=>{e.status(200).json({userId:fu(),orgId:Li(),cliVersion:Ug??"0.0.0"})});var KC=qC;import{Router as Q1}from"express";import Hg from"path";var yu=Q1();yu.patch("/:testPath",Ve(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ly.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=ze(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await MC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));yu.post("/",Ve((r,e)=>{let t;try{t=sy.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Qi(n)}catch(g){e.status(400).json({error:g.message});return}let s=ze(),c=Hg.join(s.rootDir,...a),{fullPath:l,testId:u}=xC({name:n,description:o,steps:[],settings:i,folder:c}),d=Hg.basename(l),p=Hg.relative(s.rootDir,l),m={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(m)}));yu.get("/:fileName",Ve(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=ze(),i=await dr(o),s=await lu(n,ft,i);e.status(200).json(s)}));var YC=yu;var bu=class extends Mi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ze();return is(t,o,R)}};var ZC="10mb";async function QC(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&kC(n),await UC(t);let u=Li(),d=fu(),p=r.logger.child({orgId:u,userId:d});FC(i,w=>ss({configFilePath:w}));let m=JC();m.use(eH()),m.use(XC.json({limit:ZC})),m.use(XC.urlencoded({extended:!1,limit:ZC}));let g=nH();if(g.use("/folders",Dg),g.use("/entities",WC),g.use("/identify",KC),g.use("/mobile-tests",YC),g.use("/mobile-modules",VC),g.use("/assets",HC),g.use("/git",kg),g.use("/environments",$C),m.use("/api",g),m.use((w,D,V)=>{R.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),ft.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),V()}),m.use((w,D,V,ie)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){V.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),ft.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),V.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=JC.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(w),m.use("*",(D,V)=>{V.sendFile(iH.join(o,"index.html"))})}let h=oH.createServer(m),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?aH(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Lg(),apiKey:t,logger:p},x=new vr(b),A=ze(),T={...b,mode:"interactive"},{dispose:M}=dC({baseServer:h,logger:p,authorization:b,globalStateManager:zC,getOrgId:()=>Li(),androidDriverFactory:async({socket:w,logger:D,creationOpts:V})=>{let ie=Math.floor(Math.random()*1e4)+4e4,ee=await Tl(ie,"appium");return hc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:V,socket:w,appiumPort:ee,sessionId:w.id,orgId:Li(),onStatusUpdate:he=>{w.emit("connectionStatusUpdate",{message:he})}})},mobileGeneratorFactory:async w=>new Ii({baseUrl:Lg(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async w=>new yo(A.config.ai?.agentConfig,T),browserEnricherFactory:async w=>new xi(T,new yo(A.config.ai?.agentConfig,T)),storageFactory:async w=>new bu(x,w),cacheStorageFactory:async w=>{let D=await Ri(p,x,A);return pu({orgId:w,client:x,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Pi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await M(),await Rt.flush()}catch(w){R.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await M(),await Rt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await M(),await Rt.flush()}finally{h.close(()=>process.exit(0))}})}rH.setMaxListeners(25);process.on("warning",r=>{ft.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{ft.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{ft.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function aH(r){R.error(tH`Port ${r} is already in use by another process. Please close the other process and try again.
4143
4143
  Using Bash on MacOS or Linux:
4144
4144
  lsof -t -i :58888 | xargs kill -9
4145
4145
 
@@ -4148,7 +4148,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
4148
4148
  `)}import CH from"open";import Au from"path";import{fileURLToPath as xH}from"url";import{InvalidArgumentError as Gg,Option as dt}from"@commander-js/extra-typings";import{z as sH}from"zod";var ex=58890;function lH(r){let e=parseInt(r,10);if(isNaN(e))throw new Gg("Not a number.");return e}var Ss=new dt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Gg("API key is required.");return r}).makeOptionMandatory(),Vg=new dt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ys=new dt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return sH.string().url().parse(r),r}catch{throw new Gg("Not a valid URL.")}}),jg=new dt("-y, --yes","Skip all confirmation prompts.").env("CI"),Wg=new dt("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),$g=new dt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),qg=new dt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),Kg=new dt("--tag <tag>","Tag identifier for the asset."),tx=new dt("--channel <channel>","Channel name for the asset."),rx=new dt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),nx=new dt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),ox=new dt("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),ix=new dt("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),ax=new dt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(lH),Yg=new dt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),sx=new dt("--upload-results","Upload test results to Momentic Cloud.").default(!1),Xg=new dt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),lx=new dt("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as EH}from"crypto";import{existsSync as TH}from"fs";import Jg from"fs";import bs from"path";import{cwd as uH}from"process";async function cx({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:s}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>Jg.existsSync(p)),d=uH();u?(d!==t.rootDir&&a.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),a.info(`Reading tests from the following local file paths:
4149
4149
  - ${r.join(`
4150
4150
  - `)}
4151
- `),r.forEach(p=>{if(!Jg.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=Jg.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=bs.resolve(p);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await yl("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=bs.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=bs.relative(t.rootDir,u),p=await lu(u,a,e),m=bs.basename(u,bs.extname(u));return{id:p.id,name:m,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as dH}from"crypto";import{existsSync as pH,statSync as mH}from"fs";import{cloneDeep as gH}from"lodash-es";import hH from"path";async function ux(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:gH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(p.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await fH({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:m},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function fH(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:m,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:A,alwaysSaveCache:T,noCache:M,logLevel:w,localAvdId:D,localApkPath:V}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let ie={...a.project.config.emulator,...t.settings?.emulator},ee=V?hH.resolve(V):void 0;if(ee&&(!pH(ee)||!mH(ee).isFile()))throw new Error(`Local APK path "${ee}" does not exist. Provide a valid file path via --local-apk-path.`);let he=pu({orgId:u,client:p,gitMetadata:d,regenerateCache:A??!1,alwaysSaveCache:T??!1,noCache:M??!1}),st=new Mi(p,u),W={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m,mode:"runner"},B=new Ii(W),ae=new yo(b.config.ai?.agentConfig,W),ce=new xi(W,ae),Ze=new Pi({httpClient:p,fakerSeed:void 0}),Ce=Math.floor(Math.random()*1e4)+4e4,zt=await Tl(Ce,"appium"),St=ie.region==="local"?ee??t.settings?.defaultApkFilePath?.trim():void 0,Pe=f&&!St?{channel:f,tag:E}:void 0,qe;if(D||ie.region==="local"){if(!ie.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");qe={avdId:D??ie.localEmulatorSettings?.avdId,apkToInstall:Pe,apkFilePath:St}}else qe={region:ie.region,apkToInstall:Pe,osVersion:ie.remoteEmulatorSettings?.androidVersion??NS};let pr=dH(),Ct=await hc({apiClient:p,logger:m,driverLogLevel:w,creationOpts:qe,onStatusUpdate:Ts=>{m.debug({status:Ts},"Limbar emulator status update")},appiumPort:zt,orgId:u,sessionId:pr}),Hr=await e.startAttempt({emulatorName:Ct.emulatorName,runAttemptId:pr}),bo=m.child(Hr.loggerBindings||{}),Eo=await Sc({driver:Ct.driver,onLogs:Ts=>{Hr.appendLogs(Ts)}}),wu=x||t.settings?.defaultEnv,nh;wu&&(nh=is(wu,b,bo).variables);let gx=new zo({variablesFromEnvironment:nh??{},envName:wu,testName:t.name}),oh=await Ti.init({driver:Ct.driver,generator:B,logger:bo,limbarClient:Ct.limbarClient,playwrightDevice:Ct.playwrightDevice,orgId:u,adbPort:Ct.adbPort,options:{emulator:ie},fixtures:{storage:st,browserEnricher:ce,browserGenerator:ae,localCodeEvalTools:Ze,testContext:gx}}),G;try{G=await nu({containerName:"mobile-test",fixtures:{controller:oh,logger:bo,cacheStorage:he,usageTracker:g},work:{},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Hr,callbacks:{}})}finally{await Eo(),await Ct.cleanup(),await oh.cleanup()}return await Hr.finish({logger:bo,results:G.results,status:G.status}),G}import{debounce as SH}from"ts-debounce";var Es="0.4.6";var Eu="assets";function yH(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function bH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Zg=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new po,Jr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Eu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Eu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:bH(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ni=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${Eu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Zg(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:yH(e.status),finishedAt:e.finishedAt}))))}},Qg=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
4151
+ `),r.forEach(p=>{if(!Jg.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=Jg.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=bs.resolve(p);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await yl("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=bs.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=bs.relative(t.rootDir,u),p=await lu(u,a,e),m=bs.basename(u,bs.extname(u));return{id:p.id,name:m,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as dH}from"crypto";import{existsSync as pH,statSync as mH}from"fs";import{cloneDeep as gH}from"lodash-es";import hH from"path";async function ux(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:gH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(p.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await fH({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:m},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function fH(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:m,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:A,alwaysSaveCache:T,noCache:M,logLevel:w,localAvdId:D,localApkPath:V}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let ie={...a.project.config.emulator,...t.settings?.emulator},ee=V?hH.resolve(V):void 0;if(ee&&(!pH(ee)||!mH(ee).isFile()))throw new Error(`Local APK path "${ee}" does not exist. Provide a valid file path via --local-apk-path.`);let he=pu({orgId:u,client:p,gitMetadata:d,regenerateCache:A??!1,alwaysSaveCache:T??!1,noCache:M??!1}),st=new Mi(p,u),W={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m,mode:"runner"},B=new Ii(W),ae=new yo(b.config.ai?.agentConfig,W),ce=new xi(W,ae),Ze=new Pi({httpClient:p,fakerSeed:void 0}),Ce=Math.floor(Math.random()*1e4)+4e4,zt=await Tl(Ce,"appium"),St=ie.region==="local"?ee??t.settings?.defaultApkFilePath?.trim():void 0,Pe=f&&!St?{channel:f,tag:E}:void 0,qe;if(D||ie.region==="local"){if(!ie.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");qe={avdId:D??ie.localEmulatorSettings?.avdId,apkToInstall:Pe,apkFilePath:St}}else qe={region:ie.region,apkToInstall:Pe,osVersion:ie.remoteEmulatorSettings?.androidVersion??NS};let pr=dH(),Ct=await hc({apiClient:p,logger:m,driverLogLevel:w,creationOpts:qe,onStatusUpdate:Ts=>{m.debug({status:Ts},"Limbar emulator status update")},appiumPort:zt,orgId:u,sessionId:pr}),Hr=await e.startAttempt({emulatorName:Ct.emulatorName,runAttemptId:pr}),bo=m.child(Hr.loggerBindings||{}),Eo=await Sc({driver:Ct.driver,onLogs:Ts=>{Hr.appendLogs(Ts)}}),wu=x||t.settings?.defaultEnv,nh;wu&&(nh=is(wu,b,bo).variables);let gx=new zo({variablesFromEnvironment:nh??{},envName:wu,testName:t.name}),oh=await Ti.init({driver:Ct.driver,generator:B,logger:bo,limbarClient:Ct.limbarClient,playwrightDevice:Ct.playwrightDevice,orgId:u,adbPort:Ct.adbPort,options:{emulator:ie},fixtures:{storage:st,browserEnricher:ce,browserGenerator:ae,localCodeEvalTools:Ze,testContext:gx}}),G;try{G=await nu({containerName:"mobile-test",fixtures:{controller:oh,logger:bo,cacheStorage:he,usageTracker:g},work:{},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Hr,callbacks:{}})}finally{await Eo(),await Ct.cleanup(),await oh.cleanup()}return await Hr.finish({logger:bo,results:G.results,status:G.status}),G}import{debounce as SH}from"ts-debounce";var Es="0.4.7";var Eu="assets";function yH(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function bH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Zg=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new po,Jr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Eu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Eu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:bH(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ni=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${Eu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Zg(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:yH(e.status),finishedAt:e.finishedAt}))))}},Qg=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
4152
4152
  `);this.logStream.write(t+`
4153
4153
  `)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:Kc(o,t),beforeResults:i?Kc(i,t):void 0,afterResults:a?Kc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Eu}/${t}.jpeg`)}},eh=class{constructor(e,t,n,o,i,a){this.client=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){let{runAttemptId:t}=e;this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:sn,runAttemptSchemaVersion:lb,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=SH(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Qg(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Tu=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let s={...i,id:t,trigger:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Es,labels:a??[]},c=new ds(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,t,s,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:Es,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new eh(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function dx(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function Zr(){try{await k(Promise.all([Sb(),Rt.flush()]),{milliseconds:5e3})}catch{}}async function px(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;TH(d)&&R.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await dx(s,a,e.ignoreQuarantine),g=await dr(i),h=await cx({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:R,quarantinedTestReasons:m}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Tu.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,A=new Set,T=async()=>vH({runResults:b,startTime:x,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),M=[],w=async()=>{R.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(M.map(ee=>ee())),await Zr(),process.exit(1)};process.once("SIGINT",w);let D={};for(let ee=0;ee<h.length;ee++){let he=Object.values(D);he.length===p&&await Promise.race(he.map(B=>B.promise));let st=h[ee],W=`test-${ee}`;D[W]={done:!1,promise:(async({testDefinition:B})=>{A.add(W);let ae=B.relativeFilePath.includes("..")?B.fullFilePath:B.relativeFilePath;Ta({status:"START",testLogRef:ae,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let ce=setInterval(()=>Ta({status:"RUN",testLogRef:ae,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Ze=EH(),Ce=f.child({testId:B.id,runId:Ze}),zt=new Mc({logger:Ce,reporter:new uu(a),runType:"mobile-test-run",runId:Ze,testMetadata:B,suiteMetadata:void 0});try{let St=await ux({metadata:{...o,runId:Ze},fixtures:{...t,tracer:E,logger:Ce,usageTracker:zt},inputs:{...n,project:i,testDefinition:B,channel:n.channel??B.settings?.defaultChannel,tag:n.tag??B.settings?.defaultTag,logUpdate:(Pe,qe)=>Ta({status:Pe,testLogRef:ae,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:qe}),runSigIntHandlers:M},options:e});Ta({status:St.status,testLogRef:ae,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(St)}catch(St){let Pe=`Encountered unexpected fatal error when running test '${B.name}': ${St.message}
4154
4154
  ${St.stack}`;R.error(Pe),Ce.error({err:St},`Encountered unexpected fatal error when running test ${B.name}`)}finally{clearInterval(ce),D[W].done=!0,delete D[W]}await zt.flush(s)})({testDefinition:st})}}await Promise.allSettled(Object.values(D).map(ee=>ee.promise));let ie=b.some(ee=>ee.status==="FAILED"&&!ee.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ie}),process.off("SIGINT",w),T()}async function vH({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=yb({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${rp}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return R.log(""),o?(R.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await gu({client:n,consoleLogger:R,resultsPath:i})):R.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),s}async function th(){Uv(),vb("Chromium")||(Kn?(await yl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await El({rawBrowsers:["chromium"],force:!1,all:!1})):(R.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}_v({serviceName:"mobile-cli"});rr.setApp("mobile-cli");var Ln=new AH;Ln.name("momentic-mobile").description("Momentic Mobile CLI").version(Es);var MH=Ln.command("assets").description("Manage mobile testing assets");MH.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ss).addOption(ys).addOption(Kg).addOption(rx).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=Au.resolve(r);vu.existsSync(a)||(R.error(`File not found: ${a}`),process.exit(1));let s=new vr({baseUrl:n,apiKey:t,logger:R});/\.apk$/i.test(a)||(R.error(`File is not an APK file: ${a}`),process.exit(1)),await fc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:R})});Ln.command("app").addOption(Ss).addOption(ys).addOption(jg).addOption(Vg).addOption(Xg).addOption(Wg).addOption($g).addOption(qg).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=op(r.logLevel);rr.setApp("mobile-desktop-server");let c=new vr({baseUrl:t,apiKey:e,logger:rr});await Rg({client:c,skipPrompts:n}),R.debug("API key check complete");let l=xH(import.meta.url),u=Au.dirname(l),d=Au.resolve(u,"..","static");await th(),R.debug({appiumHome:$a},"Resolved resource paths");let p=await ss({configFilePath:r.config}),m=ex;await QC({momenticServerUrl:t,serverPort:m,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:s,logger:rr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${m}`;R.info(`Local app started on: ${g}`),await CH(g)});var mx=Ln.command("results").description("Merge and upload test results.");mx.command("merge").description("Merge test results files.").addOption(Yg).addArgument(new rh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(R.error("Output directory is required."),process.exit(1)),vu.existsSync(r)||(R.warn("Results path does not exist, skipping merge."),process.exit(0)),vu.existsSync(t)&&R.warn(`Output directory ${t} already exists, removing before merging...`),OC(rr,t,r),await Zr(),process.exit(0)});var _H=new rh("<results>","Path to the results archive.").argRequired();mx.command("upload").description("Upload test results to Momentic cloud.").addOption(Ss).addOption(ys).addArgument(_H).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=rr,i=new vr({baseUrl:n,apiKey:t,logger:o});await gu({consoleLogger:R,resultsPath:r,client:i}),await Zr(),process.exit(0)});var PH=Ln.command("run").alias("test").description("Run tests on the local machine");PH.addOption(Ss).addOption(ys).addOption(Vg).addOption(jg).addOption(ax).addOption(Xg).addOption(Wg).addOption($g).addOption(qg).addOption(Yg).addOption(sx).addOption(lx).addOption(Kg).addOption(tx).addOption(nx).addOption(ox).addOption(ix).addArgument(new rh("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=op(e.logLevel);await th(),R.debug({appiumHome:$a},"Resolved resource paths");let c=await ss({configFilePath:e.config}),l=a??c.config.outputDir??EC,u=e.parallel??c.config.parallel??1;R.debug("Checking API key and dependencies");let d=new vr({baseUrl:n,apiKey:t,logger:R}),{orgId:p,userId:m}=await Rg({client:d,skipPrompts:e.yes});R.debug("API key check and browser installation complete");let g=RH(),h=rr.child({runGroupId:g,orgId:p,userId:m}),f=await Ri(rr,d,c);h.debug(f,"Got local git metadata");try{let E=await px({options:{...e,parallel:u,outputDir:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:s},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});await Zr(),E.failed>0?process.exit(1):process.exit(0)}catch(E){R.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),R.error(E),rr.error({err:E},"Failed to run tests locally"),await Zr(),process.exit(1)}});Ln.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new wH("--name <name>","Name of the project")).action(async r=>{R.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}