momentic-mobile 0.9.4 → 0.9.5
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 +5 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -24,7 +24,7 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
24
24
|
`).slice(o).filter(Boolean).join(`
|
|
25
25
|
`);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",Na(e,...t))}error(e,...t){this._log("error",Na(e,...t))}info(e,...t){this._log("info",Na(e,...t))}log(e,...t){this._log("log",Na(e,...t))}warn(e,...t){this._log("warn",Na(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function uE(r){let e=globalThis.console,t=new Ll;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
26
26
|
`);process.stderr.write(`${o}
|
|
27
|
-
`),globalThis.console=e}}var xp=" ".repeat(6);import WL from"fetch-retry";import jL from"os";import dE,{multistream as $L}from"pino";import qL from"pino-pretty";import KL from"pino-std-serializers";var ci=new Map,YL=!0,pE="Log throttle exceeded",XL=100,JL=5e3,QL=WL(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}}),Mp=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??jL.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=YL?dE(a):dE(a,$L([{stream:qL({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 QL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:lo(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===pE)return!0;let t=Date.now();return t-this.lastWindowStart>JL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,pE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<XL?(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(Oa[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=KL.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:tb({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,ci.set("app",this),ci.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=rb[e]):(this.minLevelValue=Oa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ui=({app:r,hostname:e,disableConsoleLogs:t})=>(ci.has(r)||ci.set(r,new Mp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ci.get(r));async function mE(){await Promise.all([...ci.values()].map(r=>r.flush()))}import{hostname as ZL}from"os";var ar=ui({app:"cli",hostname:ZL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.4"});function _p(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function gE({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 uE(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.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 Da=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=di.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=di.bgGreen.white("PASS"),a=3):r.includes("START")?(i=di.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=di.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=di.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=di.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),eN||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import tN from"fs";import{tmpdir as rN}from"os";import nN from"path";import{registry as ka}from"playwright-core/lib/server";import hE from"proper-lockfile";var fE=nN.join(rN(),"momenticBrowserInstallation");var Pp=["chrome","chromium","chrome-for-testing","ffmpeg"],oN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},SE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function yE(r){let e=SE[oN[r]??""]??"",t=ka.findExecutable(e);return!t||t.installType==="none"?!1:Ip(t)}function Ip(r){let e=r.executablePath();return tN.existsSync(e)}function iN(r,e){let t=SE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ka.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Ip(n)))return n}async function aN({browser:r,force:e}){let t=iN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await ka.installDeps([t],!1),await ka.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ka.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Ip(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Nl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Pp:Array.from(new Set(r));try{await hE.lock(fE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 aN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await hE.unlock(fE,{realpath:!1})}if(o)throw o}import{createServer as sN}from"http";async function Dl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await kl(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function kl(r){return new Promise((e,t)=>{let n=sN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.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 aee from"blocked-at";import lee from"why-is-node-running";import U0 from"fs";import{tmpdir as F0}from"os";import B0 from"path";import{remote as z0}from"webdriverio";import{createInstanceClient as I0}from"@limrun/api";import{execSync as O0}from"child_process";import bee,{multistream as Tee}from"pino";import Aee from"pino-pretty";var Ree=5*1024,lN="...[truncated]",xee=Buffer.byteLength(lN,"utf8");import{PostHog as Uee}from"posthog-node";var xn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var bE=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(bE(p));l=()=>c(bE(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 xn(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 $ee}from"posthog-node";import{execSync as cN}from"child_process";import pi from"os";import uN from"v8";var EE,Dr,vE=pi.platform(),dN=pi.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),{}),TE=r=>{try{let e={},t=!1,n=pN(),o=mN(),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=uN.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"),co&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function AE(r){if(!Lr)return TE(r),{interval:setInterval(()=>TE(r),2e4),cpuMetadata:dN,platform:vE}}function pN(){let r=pi.totalmem(),e=vE==="darwin"?gN():(()=>{let n=pi.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function mN(){let r=pi.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,!Dr)return Dr=t,null;let n={user:t.user-Dr.user,nice:t.nice-Dr.nice,sys:t.sys-Dr.sys,idle:t.idle-Dr.idle,irq:t.irq-Dr.irq,total:t.total-Dr.total};return EE={measurementTime:e,intervalMs:e-Dr.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},Dr=t,EE}function gN(){try{let r=cN("/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=pi.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Ul=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function hN(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 Fl(r,e){let t=hN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var XE="=",Gl=";",Vp=",";var JE=8192;var fi={};RM(fi,{getKeyPairs:()=>KN,parseKeyPairsIntoRecord:()=>YN,parsePairKeyValue:()=>QE,serializeKeyPairs:()=>qN});_e();var $N=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 qN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Vp:"")+t;return n.length>JE?e:n},"")}function KN(r){return r.getAllEntries().map(function(e){var t=$N(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Gl+o.metadata.toString()),i})}function QE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(XE);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(Gl))),{key:o,value:i,metadata:a}}}}}function YN(r){return typeof r!="string"||r.length===0?{}:r.split(Vp).map(function(e){return QE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Vl;(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"})(Vl||(Vl={}));var XN=",",JN=["OTEL_SDK_DISABLED"];function QN(r){return JN.indexOf(r)>-1}var ZN=["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 eD(r){return ZN.indexOf(r)>-1}var tD=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function rD(r){return tD.indexOf(r)>-1}var Wp=1/0,jp=128,nD=128,oD=128,$p={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:Ue.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:nD,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:oD,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Vl.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 iD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function aD(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 sD(r,e,t,n){n===void 0&&(n=XN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var lD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function cD(r,e,t){var n=t[r];if(typeof n=="string"){var o=lD[n.toUpperCase()];o!=null&&(e[r]=o)}}function ZE(r){var e={};for(var t in $p){var n=t;switch(n){case"OTEL_LOG_LEVEL":cD(n,e,r);break;default:if(QN(n))iD(n,e,r);else if(eD(n))aD(n,e,r);else if(rD(n))sD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=ZE(process.env);return Object.assign({},$p,r)}function eT(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=eT(r.charCodeAt(n)),i=eT(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var tT="1.25.1";var uD="deployment.environment";var dD="process.runtime.name";var pD="service.name";var mD="service.instance.id";var gD="telemetry.sdk.name",hD="telemetry.sdk.language",fD="telemetry.sdk.version";var rT=uD;var nT=dD;var jl=pD;var oT=mD;var Va=gD,Wa=hD,ja=fD;var SD="nodejs";var iT=SD;var Si,$l=(Si={},Si[Va]="opentelemetry",Si[nT]="node",Si[Wa]=iT,Si[ja]=tT,Si);var yD=9,bD=6,ED=Math.pow(10,bD),TD=Math.pow(10,yD);function aT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ED);return[t,n]}function sT(r){return r[0]*TD+r[1]}function $a(r){return r[0]*1e6+r[1]/1e3}var po;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(po||(po={}));var lT=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 vD=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},AD=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))},cT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new lT}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,AD([this._that],vD(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 sr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(sr||(sr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));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)}}();var fne=function(r){wD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function uT(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}_e();var lr;(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"})(lr||(lr={}));var dT=function(){function r(){this.kind=lr.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 se;(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"})(se||(se={}));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};function RD(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 qp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RD(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=uT(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 Kp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new qp(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 qp(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 qp(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:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=CD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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}();_e();var Yp=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},Xp=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))},Jp=function(){function r(e,t,n,o){e===void 0&&(e=new xD),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 xD=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,Xp([n,this._counts.length-t],Yp(this._counts.slice(t)),!1)),o.splice.apply(o,Xp([0,t],Yp(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(Xp([],Yp(this._counts),!1))},r}();var pT=52,MD=2146435072,_D=1048575,Qp=1023,ql=-Qp+1,Kl=Qp,qa=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&MD)>>20;return n-Qp}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&_D)*Math.pow(2,32);return o+n}function Ka(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function gT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var PD=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)}}(),Mn=function(r){PD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var fT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<qa)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,pT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Mn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Mn("overflow: "+e+" is > maximum lower boundary: "+n);return Ka(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var ST=function(){function r(e){this._scale=e,this._scaleFactor=Ka(Math.LOG2E,e),this._inverseFactor=Ka(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=qa)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 Mn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return qa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Mn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var yT=-10,bT=20,ID=Array.from({length:31},function(r,e){return e>10?new ST(e-10):new fT(e-10)});function Zp(r){if(r>bT||r<yT)throw new Mn("expected scale >= "+yT+" && <= "+bT+", got: "+r);return ID[r+10]}var OD=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},Jl=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}(),LD=20,ND=160,em=2,DD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=ND),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 Jp),u===void 0&&(u=new Jp),d===void 0&&(d=Zp(LD)),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<em&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+em),this._maxSize=em)}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=gT(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=Zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(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 ET=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new DD(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=OD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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 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},tm=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=aT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var TT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new tm(e)},r.prototype.merge=function(e,t){var n=$a(t.sampleTime)>=$a(e.sampleTime)?t:e;return new tm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=$a(t.sampleTime)>=$a(e.sampleTime)?t:e;return new tm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.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 UD=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},Ya=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 rm=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new Ya(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ya(t.startTime,this.monotonic,o,t.reset):new Ya(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 Ya(t.startTime,this.monotonic,o,!0):new Ya(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=UD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var mo=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)}}(),Ur=function(){function r(){}return r.Drop=function(){return _T},r.Sum=function(){return PT},r.LastValue=function(){return IT},r.Histogram=function(){return OT},r.ExponentialHistogram=function(){return FD},r.Default=function(){return BD},r}();var vT=function(r){mo(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 dT,e}(Ur);var AT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new rm(!0),e.NON_MONOTONIC_INSTANCE=new rm(!1),e}(Ur);var wT=function(r){mo(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 TT,e}(Ur);var CT=function(r){mo(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 Kp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var RT=function(r){mo(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 Kp(this._boundaries,this._recordMinMax)},e}(Ur);var xT=function(r){mo(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 ET(this._maxSize,this._recordMinMax)},e}(Ur);var MT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return PT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return IT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new RT(t.advice.explicitBucketBoundaries):OT}return H.warn("Unable to recognize instrument type: "+t.type),_T},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var _T=new vT,PT=new AT,IT=new wT,OT=new CT,FD=new xT,BD=new MT;_e();function Ql(){return"unknown_service:"+process.argv0}var _n=function(){return _n=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},_n.apply(this,arguments)},zD=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())})},HD=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},nm=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 H.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[jl]=Ql(),e[Wa]=$l[Wa],e[Va]=$l[Va],e[ja]=$l[ja],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 zD(this,void 0,void 0,function(){return HD(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=_n(_n({},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=GD(a,2),l=c[0],u=c[1];return _n(_n(_n(_n({},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 go;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(go||(go={}));_e();var VD=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())})},WD=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}}},om=function(){return sr.CUMULATIVE},LT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return sr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return sr.CUMULATIVE}},NT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return sr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return sr.CUMULATIVE}};function jD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?om:e==="delta"?LT:e==="lowmemory"?NT:(H.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."),om)}function $D(r){return r!=null?r===go.DELTA?LT:r===go.LOWMEMORY?NT:om:jD()}function qD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var DT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=qD(t),this._aggregationTemporalitySelector=$D(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return VD(this,void 0,void 0,function(){return WD(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}();_e();_e();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},kT=1e4,UT=5,FT=1e3,BT=5e3,zT=1.5;function Xa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=KD(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function im(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function am(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function sm(r){return typeof r=="number"?r<=0?lm(r,kT):r:YD()}function YD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?lm(e,kT):e}function lm(r,e){return H.warn("Timeout must be greater than 0",r),e}function HT(r){var e=[429,502,503,504];return e.includes(r)}function GT(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 VT=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 cT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=sm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:po.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:po.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:po.SUCCESS})}).catch(function(n){t({code:po.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{H.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 H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as cm from"url";import*as ec from"http";import*as tc from"https";import*as WT from"zlib";import{Readable as JD}from"stream";var Pn;(function(r){r.NONE="none",r.GZIP="gzip"})(Pn||(Pn={}));var XD=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)}}(),yi=function(r){XD(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 Zl=function(){return Zl=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},Zl.apply(this,arguments)};function um(r,e,t,n,o){var i=r.timeoutMillis,a=new cm.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 yi("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:Zl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?ec.request:tc.request,m=function(h,f){switch(h===void 0&&(h=UT),f===void 0&&(f=FT),l=g(p,function(b){var x="";b.on("data",function(w){return x+=w}),b.on("aborted",function(){if(u){var w=new yi("Request Timeout");o(w)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&HT(b.statusCode)&&h>0){var w=void 0;f=zT*f,b.headers["retry-after"]?w=GT(b.headers["retry-after"]):w=Math.round(Math.random()*(BT-f)+f),c=setTimeout(function(){m(h-1,f)},w)}else{var T=new yi(b.statusMessage,b.statusCode,x);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new yi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new yi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Pn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=QD(e);E.on("error",o).pipe(WT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function QD(r){var e=new JD;return e.push(r),e.push(null),e}function dm(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new cm.URL(r.url),t=e.protocol==="http:"?ec.Agent:tc.Agent;return new t(Zl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function pm(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Pn.GZIP?Pn.GZIP:Pn.NONE}_e();var ZD=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)}}(),rc=function(r){ZD(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&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Xa(t.headers),fi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=dm(t),i.compression=pm(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){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;um(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}(VT);function $T(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function ek(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function qT(r){var e=$T(r);return ek(e)}function tk(r){var e=$T(r);return e.toString()}var rk=typeof BigInt<"u"?tk:sT;function jT(r){return r}function KT(r){if(r!==void 0)return Wl(r)}var nk={encodeHrTime:qT,encodeSpanContext:Wl,encodeOptionalSpanContext:KT};function YT(r){var e,t;if(r===void 0)return nk;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?qT:rk,encodeSpanContext:o?jT:Wl,encodeOptionalSpanContext:o?jT:KT}}var 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};function XT(r){return{name:r.name,version:r.version}}function bi(r){return Object.keys(r).map(function(e){return JT(e,r[e])})}function JT(r,e){return{key:r,value:QT(e)}}function QT(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(QT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ok(t,2),o=n[0],i=n[1];return JT(o,i)})}}:{}}function ZT(r){return{attributes:bi(r.attributes),droppedAttributesCount:0}}_e();function tv(r,e){var t=YT(e);return{resource:ZT(r.resource),schemaUrl:void 0,scopeMetrics:ik(r.scopeMetrics,t)}}function ik(r,e){return Array.from(r.map(function(t){return{scope:XT(t.scope),metrics:t.metrics.map(function(n){return ak(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function ak(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=uk(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:ev(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:ev(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:lk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ck(r,e)};break}return t}function sk(r,e,t){var n={attributes:bi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case jt.INT:n.asInt=r.value;break;case jt.DOUBLE:n.asDouble=r.value;break}return n}function ev(r,e){return r.dataPoints.map(function(t){return sk(t,r.descriptor.valueType,e)})}function lk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:bi(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 ck(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:bi(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 uk(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function rv(r,e){return{resourceMetrics:r.map(function(t){return tv(t,e)})}}var mm={serializeRequest:function(r){var e=rv(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 nv="0.52.1";var ov=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(){return Ei=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},Ei.apply(this,arguments)},iv="v1/metrics",dk="http://localhost:4318/"+iv,pk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+nv},mk=function(r){ov(e,r);function e(t){var n=r.call(this,t,mm,"application/json")||this;return n.headers=Ei(Ei(Ei(Ei({},n.headers),pk),fi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Xa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?am(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?im(bt().OTEL_EXPORTER_OTLP_ENDPOINT,iv):dk},e}(rc),av=function(r){ov(e,r);function e(t){return r.call(this,new mk(t),t)||this}return e}(DT);var Ti;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Ti||(Ti={}));var Fr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Fr||(Fr={}));_e();var gk=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)}}(),sv=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())})},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}}},hk=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},fk=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))},Sk=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 cv(r){return r!=null}function nc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function uv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var gm=function(r){gk(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function In(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new gm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function dv(r){return sv(this,void 0,void 0,function(){var e=this;return lv(this,function(t){return[2,Promise.all(r.map(function(n){return sv(e,void 0,void 0,function(){var o,i;return lv(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 pv(r){return r.status==="rejected"}function hm(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,fk([],hk(e(n)),!1))}),t}function mv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=Sk(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 gv(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 hv(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var cr;(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"})(cr||(cr={}));var fm=function(){function r(){this.kind=cr.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}();_e();var he;(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"})(he||(he={}));function Br(r,e,t){var n,o,i,a;return bk(r)||H.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:jt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function fv(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 Sv(r,e){return hv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var yk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function bk(r){return r.match(yk)!=null}var 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};function Tk(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 oc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=Tk(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=gv(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 ic=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=cr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new oc(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 oc(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 oc(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:Fr.HISTOGRAM,dataPoints:n.map(function(i){var a=Ek(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.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}();_e();var Sm=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},ym=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))},bm=function(){function r(e,t,n,o){e===void 0&&(e=new vk),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 vk=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,ym([n,this._counts.length-t],Sm(this._counts.slice(t)),!1)),o.splice.apply(o,ym([0,t],Sm(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(ym([],Sm(this._counts),!1))},r}();var yv=52,Ak=2146435072,wk=1048575,Em=1023,ac=-Em+1,sc=Em,Ja=Math.pow(2,-1022);function lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&Ak)>>20;return n-Em}function cc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&wk)*Math.pow(2,32);return o+n}function Qa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Ev(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}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)}}(),On=function(r){Ck(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var vv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ja)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,yv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new On("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new On("overflow: "+e+" is > maximum lower boundary: "+n);return Qa(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=ac>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return sc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Av=function(){function r(e){this._scale=e,this._scaleFactor=Qa(Math.LOG2E,e),this._inverseFactor=Qa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ja)return this._minNormalLowerBoundaryIndex()-1;if(cc(e)===0){var t=lc(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 On("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ja;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new On("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 ac<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(sc+1<<this._scale)-1},r}();var wv=-10,Cv=20,Rk=Array.from({length:31},function(r,e){return e>10?new Av(e-10):new vv(e-10)});function Tm(r){if(r>Cv||r<wv)throw new On("expected scale >= "+wv+" && <= "+Cv+", got: "+r);return Rk[r+10]}var xk=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},uc=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}(),Mk=20,_k=160,vm=2,Rv=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_k),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 bm),u===void 0&&(u=new bm),d===void 0&&(d=Tm(Mk)),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<vm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+vm),this._maxSize=vm)}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=Ev(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=Tm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=uc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=uc.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 uc(0,-1);var o=t-n;return new uc(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 Am=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Rv(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:Fr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=xk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.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}();_e();var Pk=Np("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function xv(r){return r.setValue(Pk,!0)}_e();function Mv(){return function(r){H.error(Ik(r))}}function Ik(r){return typeof r=="string"?r:JSON.stringify(Ok(r))}function Ok(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 Lk=Mv();function dc(r){try{Lk(r)}catch{}}var _v="1.30.1";var Nk="process.runtime.name";var Dk="service.name";var kk="telemetry.sdk.name",Uk="telemetry.sdk.language",Fk="telemetry.sdk.version";var Pv=Nk;var Iv=Dk;var Za=kk,es=Uk,ts=Fk;var Bk="nodejs";var Ov=Bk;var vi,ho=(vi={},vi[Za]="opentelemetry",vi[Pv]="node",vi[es]=Ov,vi[ts]=_v,vi);function rs(r){r.unref()}var $k=9,qk=6,Kk=Math.pow(10,qk),Eae=Math.pow(10,$k);function fo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Kk);return[t,n]}function Ai(r){return r[0]*1e6+r[1]/1e3}var ns;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ns||(ns={}));_e();function Lv(r,e){return new Promise(function(t){hi.with(xv(hi.active()),function(){r.export(e,function(n){t(n)})})})}var Nv={_export:Lv};var Yk=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},pc=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=fo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var wm=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new pc(e)},r.prototype.merge=function(e,t){var n=Ai(t.sampleTime)>=Ai(e.sampleTime)?t:e;return new pc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ai(t.sampleTime)>=Ai(e.sampleTime)?t:e;return new pc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.GAUGE,dataPoints:n.map(function(i){var a=Yk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var Xk=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},wi=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 mc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new wi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new wi(t.startTime,this.monotonic,o,t.reset):new wi(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 wi(t.startTime,this.monotonic,o,!0):new wi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.SUM,dataPoints:n.map(function(i){var a=Xk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var So=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)}}(),ur=function(){function r(){}return r.Drop=function(){return Hv},r.Sum=function(){return Gv},r.LastValue=function(){return Vv},r.Histogram=function(){return Wv},r.ExponentialHistogram=function(){return Jk},r.Default=function(){return Qk},r}();var Dv=function(r){So(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 fm,e}(ur);var kv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case he.COUNTER:case he.OBSERVABLE_COUNTER:case he.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new mc(!0),e.NON_MONOTONIC_INSTANCE=new mc(!1),e}(ur);var Uv=function(r){So(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 wm,e}(ur);var Fv=function(r){So(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 ic([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ur);var os=function(r){So(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 ic(this._boundaries,this._recordMinMax)},e}(ur);var Bv=function(r){So(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 Am(this._maxSize,this._recordMinMax)},e}(ur);var zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case he.COUNTER:case he.UP_DOWN_COUNTER:case he.OBSERVABLE_COUNTER:case he.OBSERVABLE_UP_DOWN_COUNTER:return Gv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return Vv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new os(t.advice.explicitBucketBoundaries):Wv}return H.warn("Unable to recognize instrument type: "+t.type),Hv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Hv=new Dv,Gv=new kv,Vv=new Uv,Wv=new Fv,Jk=new Bv,Qk=new zv;var jv=function(r){return ur.Default()},$v=function(r){return Ti.CUMULATIVE};var Cm=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())})},Rm=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}}},qv=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},Zk=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))},Kv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:jv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:$v,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 Cm(this,void 0,void 0,function(){var t,n,o,i,a,s;return Rm(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(Zk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],qv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=qv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(hm(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(hm(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Cm(this,void 0,void 0,function(){return Rm(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,In(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Cm(this,void 0,void 0,function(){return Rm(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,In(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var e0=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)}}(),gc=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())})},hc=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}}},t0=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},r0=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))},xm=function(r){e0(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 gc(this,void 0,void 0,function(){var t;return hc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,In(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof gm?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(dc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return gc(this,void 0,void 0,function(){var o,i,a,s,c,l;return hc(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=H).error.apply(l,r0(["PeriodicExportingMetricReader: metrics collection errors"],t0(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(),H.debug("Error while resolving async portion of resource: ",s),dc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Nv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ns.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),rs(this._interval)},e.prototype.onForceFlush=function(){return gc(this,void 0,void 0,function(){return hc(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 gc(this,void 0,void 0,function(){return hc(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}(Kv);_e();_e();function fc(){return"unknown_service:"+process.argv0}var Ln=function(){return Ln=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},Ln.apply(this,arguments)},n0=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())})},o0=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}}},i0=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){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 H.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[Iv]=fc(),e[es]=ho[es],e[Za]=ho[Za],e[ts]=ho[ts],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 n0(this,void 0,void 0,function(){return o0(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=Ln(Ln({},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=i0(a,2),l=c[0],u=c[1];return Ln(Ln(Ln(Ln({},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 Yv=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}();_e();var yo=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)}}(),yc=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=hi.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===jt.INT&&!Number.isInteger(e)&&(H.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,fo(Date.now()))},r}();var Xv=function(r){yo(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}(yc);var Jv=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(yc);var Qv=function(r){yo(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}(yc);var Zv=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(yc);var bc=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 eA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var tA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var rA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function is(r){return r instanceof bc}var nA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Br(e,he.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Qv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Zv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Jv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Br(e,he.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new eA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Br(e,he.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rA(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 Ec=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Br(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var a0=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)}}(),oA=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}}},s0=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 oA(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 oA(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 Tr=function(r){a0(e,r);function e(){return r.call(this,nc)||this}return e}(s0);var l0=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},Tc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Tr,this._cumulativeMemoStorage=new Tr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=nc(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=l0(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 Tr,e},r}();var Mm=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.")},iA=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},vc=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===Ti.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=c0(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=Mm(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 Tr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Mm(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=iA(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=Mm(e.keys()),s=a.next();!s.done;s=a.next()){var c=iA(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 c0(r){return Array.from(r.entries())}var u0=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)}}(),d0=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},aA=function(r){u0(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 Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Tr;Array.from(t.entries()).forEach(function(a){var s=d0(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}(Ec);_e();function _m(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
27
|
+
`),globalThis.console=e}}var xp=" ".repeat(6);import WL from"fetch-retry";import jL from"os";import dE,{multistream as $L}from"pino";import qL from"pino-pretty";import KL from"pino-std-serializers";var ci=new Map,YL=!0,pE="Log throttle exceeded",XL=100,JL=5e3,QL=WL(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}}),Mp=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??jL.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=YL?dE(a):dE(a,$L([{stream:qL({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 QL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:lo(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===pE)return!0;let t=Date.now();return t-this.lastWindowStart>JL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,pE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<XL?(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(Oa[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=KL.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:tb({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,ci.set("app",this),ci.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=rb[e]):(this.minLevelValue=Oa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ui=({app:r,hostname:e,disableConsoleLogs:t})=>(ci.has(r)||ci.set(r,new Mp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ci.get(r));async function mE(){await Promise.all([...ci.values()].map(r=>r.flush()))}import{hostname as ZL}from"os";var ar=ui({app:"cli",hostname:ZL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.5"});function _p(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function gE({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 uE(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.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 Da=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=di.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=di.bgGreen.white("PASS"),a=3):r.includes("START")?(i=di.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=di.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=di.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=di.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),eN||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import tN from"fs";import{tmpdir as rN}from"os";import nN from"path";import{registry as ka}from"playwright-core/lib/server";import hE from"proper-lockfile";var fE=nN.join(rN(),"momenticBrowserInstallation");var Pp=["chrome","chromium","chrome-for-testing","ffmpeg"],oN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},SE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function yE(r){let e=SE[oN[r]??""]??"",t=ka.findExecutable(e);return!t||t.installType==="none"?!1:Ip(t)}function Ip(r){let e=r.executablePath();return tN.existsSync(e)}function iN(r,e){let t=SE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ka.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Ip(n)))return n}async function aN({browser:r,force:e}){let t=iN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await ka.installDeps([t],!1),await ka.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ka.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Ip(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Nl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Pp:Array.from(new Set(r));try{await hE.lock(fE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 aN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await hE.unlock(fE,{realpath:!1})}if(o)throw o}import{createServer as sN}from"http";async function Dl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await kl(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function kl(r){return new Promise((e,t)=>{let n=sN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.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 aee from"blocked-at";import lee from"why-is-node-running";import U0 from"fs";import{tmpdir as F0}from"os";import B0 from"path";import{remote as z0}from"webdriverio";import{createInstanceClient as I0}from"@limrun/api";import{execSync as O0}from"child_process";import bee,{multistream as Tee}from"pino";import Aee from"pino-pretty";var Ree=5*1024,lN="...[truncated]",xee=Buffer.byteLength(lN,"utf8");import{PostHog as Uee}from"posthog-node";var xn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var bE=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(bE(p));l=()=>c(bE(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 xn(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 $ee}from"posthog-node";import{execSync as cN}from"child_process";import pi from"os";import uN from"v8";var EE,Dr,vE=pi.platform(),dN=pi.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),{}),TE=r=>{try{let e={},t=!1,n=pN(),o=mN(),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=uN.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"),co&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function AE(r){if(!Lr)return TE(r),{interval:setInterval(()=>TE(r),2e4),cpuMetadata:dN,platform:vE}}function pN(){let r=pi.totalmem(),e=vE==="darwin"?gN():(()=>{let n=pi.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function mN(){let r=pi.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,!Dr)return Dr=t,null;let n={user:t.user-Dr.user,nice:t.nice-Dr.nice,sys:t.sys-Dr.sys,idle:t.idle-Dr.idle,irq:t.irq-Dr.irq,total:t.total-Dr.total};return EE={measurementTime:e,intervalMs:e-Dr.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},Dr=t,EE}function gN(){try{let r=cN("/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=pi.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Ul=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function hN(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 Fl(r,e){let t=hN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var XE="=",Gl=";",Vp=",";var JE=8192;var fi={};RM(fi,{getKeyPairs:()=>KN,parseKeyPairsIntoRecord:()=>YN,parsePairKeyValue:()=>QE,serializeKeyPairs:()=>qN});_e();var $N=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 qN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Vp:"")+t;return n.length>JE?e:n},"")}function KN(r){return r.getAllEntries().map(function(e){var t=$N(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Gl+o.metadata.toString()),i})}function QE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(XE);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(Gl))),{key:o,value:i,metadata:a}}}}}function YN(r){return typeof r!="string"||r.length===0?{}:r.split(Vp).map(function(e){return QE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Vl;(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"})(Vl||(Vl={}));var XN=",",JN=["OTEL_SDK_DISABLED"];function QN(r){return JN.indexOf(r)>-1}var ZN=["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 eD(r){return ZN.indexOf(r)>-1}var tD=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function rD(r){return tD.indexOf(r)>-1}var Wp=1/0,jp=128,nD=128,oD=128,$p={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:Ue.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Wp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:jp,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:nD,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:oD,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Vl.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 iD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function aD(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 sD(r,e,t,n){n===void 0&&(n=XN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var lD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function cD(r,e,t){var n=t[r];if(typeof n=="string"){var o=lD[n.toUpperCase()];o!=null&&(e[r]=o)}}function ZE(r){var e={};for(var t in $p){var n=t;switch(n){case"OTEL_LOG_LEVEL":cD(n,e,r);break;default:if(QN(n))iD(n,e,r);else if(eD(n))aD(n,e,r);else if(rD(n))sD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=ZE(process.env);return Object.assign({},$p,r)}function eT(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=eT(r.charCodeAt(n)),i=eT(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var tT="1.25.1";var uD="deployment.environment";var dD="process.runtime.name";var pD="service.name";var mD="service.instance.id";var gD="telemetry.sdk.name",hD="telemetry.sdk.language",fD="telemetry.sdk.version";var rT=uD;var nT=dD;var jl=pD;var oT=mD;var Va=gD,Wa=hD,ja=fD;var SD="nodejs";var iT=SD;var Si,$l=(Si={},Si[Va]="opentelemetry",Si[nT]="node",Si[Wa]=iT,Si[ja]=tT,Si);var yD=9,bD=6,ED=Math.pow(10,bD),TD=Math.pow(10,yD);function aT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ED);return[t,n]}function sT(r){return r[0]*TD+r[1]}function $a(r){return r[0]*1e6+r[1]/1e3}var po;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(po||(po={}));var lT=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 vD=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},AD=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))},cT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new lT}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,AD([this._that],vD(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 sr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(sr||(sr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));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)}}();var fne=function(r){wD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function uT(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}_e();var lr;(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"})(lr||(lr={}));var dT=function(){function r(){this.kind=lr.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 se;(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"})(se||(se={}));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};function RD(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 qp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RD(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=uT(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 Kp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new qp(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 qp(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 qp(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:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=CD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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}();_e();var Yp=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},Xp=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))},Jp=function(){function r(e,t,n,o){e===void 0&&(e=new xD),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 xD=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,Xp([n,this._counts.length-t],Yp(this._counts.slice(t)),!1)),o.splice.apply(o,Xp([0,t],Yp(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(Xp([],Yp(this._counts),!1))},r}();var pT=52,MD=2146435072,_D=1048575,Qp=1023,ql=-Qp+1,Kl=Qp,qa=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&MD)>>20;return n-Qp}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&_D)*Math.pow(2,32);return o+n}function Ka(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function gT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var PD=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)}}(),Mn=function(r){PD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var fT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<qa)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,pT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Mn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Mn("overflow: "+e+" is > maximum lower boundary: "+n);return Ka(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var ST=function(){function r(e){this._scale=e,this._scaleFactor=Ka(Math.LOG2E,e),this._inverseFactor=Ka(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=qa)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 Mn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return qa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Mn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var yT=-10,bT=20,ID=Array.from({length:31},function(r,e){return e>10?new ST(e-10):new fT(e-10)});function Zp(r){if(r>bT||r<yT)throw new Mn("expected scale >= "+yT+" && <= "+bT+", got: "+r);return ID[r+10]}var OD=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},Jl=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}(),LD=20,ND=160,em=2,DD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=ND),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 Jp),u===void 0&&(u=new Jp),d===void 0&&(d=Zp(LD)),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<em&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+em),this._maxSize=em)}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=gT(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=Zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(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 ET=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new DD(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=OD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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 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},tm=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=aT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var TT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new tm(e)},r.prototype.merge=function(e,t){var n=$a(t.sampleTime)>=$a(e.sampleTime)?t:e;return new tm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=$a(t.sampleTime)>=$a(e.sampleTime)?t:e;return new tm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.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 UD=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},Ya=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 rm=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new Ya(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ya(t.startTime,this.monotonic,o,t.reset):new Ya(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 Ya(t.startTime,this.monotonic,o,!0):new Ya(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=UD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var mo=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)}}(),Ur=function(){function r(){}return r.Drop=function(){return _T},r.Sum=function(){return PT},r.LastValue=function(){return IT},r.Histogram=function(){return OT},r.ExponentialHistogram=function(){return FD},r.Default=function(){return BD},r}();var vT=function(r){mo(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 dT,e}(Ur);var AT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new rm(!0),e.NON_MONOTONIC_INSTANCE=new rm(!1),e}(Ur);var wT=function(r){mo(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 TT,e}(Ur);var CT=function(r){mo(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 Kp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var RT=function(r){mo(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 Kp(this._boundaries,this._recordMinMax)},e}(Ur);var xT=function(r){mo(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 ET(this._maxSize,this._recordMinMax)},e}(Ur);var MT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return PT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return IT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new RT(t.advice.explicitBucketBoundaries):OT}return H.warn("Unable to recognize instrument type: "+t.type),_T},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var _T=new vT,PT=new AT,IT=new wT,OT=new CT,FD=new xT,BD=new MT;_e();function Ql(){return"unknown_service:"+process.argv0}var _n=function(){return _n=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},_n.apply(this,arguments)},zD=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())})},HD=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},nm=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 H.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[jl]=Ql(),e[Wa]=$l[Wa],e[Va]=$l[Va],e[ja]=$l[ja],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 zD(this,void 0,void 0,function(){return HD(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=_n(_n({},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=GD(a,2),l=c[0],u=c[1];return _n(_n(_n(_n({},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 go;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(go||(go={}));_e();var VD=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())})},WD=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}}},om=function(){return sr.CUMULATIVE},LT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return sr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return sr.CUMULATIVE}},NT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return sr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return sr.CUMULATIVE}};function jD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?om:e==="delta"?LT:e==="lowmemory"?NT:(H.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."),om)}function $D(r){return r!=null?r===go.DELTA?LT:r===go.LOWMEMORY?NT:om:jD()}function qD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var DT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=qD(t),this._aggregationTemporalitySelector=$D(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return VD(this,void 0,void 0,function(){return WD(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}();_e();_e();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},kT=1e4,UT=5,FT=1e3,BT=5e3,zT=1.5;function Xa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=KD(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function im(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function am(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function sm(r){return typeof r=="number"?r<=0?lm(r,kT):r:YD()}function YD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?lm(e,kT):e}function lm(r,e){return H.warn("Timeout must be greater than 0",r),e}function HT(r){var e=[429,502,503,504];return e.includes(r)}function GT(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 VT=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 cT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=sm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:po.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:po.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:po.SUCCESS})}).catch(function(n){t({code:po.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{H.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 H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as cm from"url";import*as ec from"http";import*as tc from"https";import*as WT from"zlib";import{Readable as JD}from"stream";var Pn;(function(r){r.NONE="none",r.GZIP="gzip"})(Pn||(Pn={}));var XD=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)}}(),yi=function(r){XD(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 Zl=function(){return Zl=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},Zl.apply(this,arguments)};function um(r,e,t,n,o){var i=r.timeoutMillis,a=new cm.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 yi("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:Zl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?ec.request:tc.request,m=function(h,f){switch(h===void 0&&(h=UT),f===void 0&&(f=FT),l=g(p,function(b){var x="";b.on("data",function(w){return x+=w}),b.on("aborted",function(){if(u){var w=new yi("Request Timeout");o(w)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&HT(b.statusCode)&&h>0){var w=void 0;f=zT*f,b.headers["retry-after"]?w=GT(b.headers["retry-after"]):w=Math.round(Math.random()*(BT-f)+f),c=setTimeout(function(){m(h-1,f)},w)}else{var T=new yi(b.statusMessage,b.statusCode,x);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new yi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new yi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Pn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=QD(e);E.on("error",o).pipe(WT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function QD(r){var e=new JD;return e.push(r),e.push(null),e}function dm(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new cm.URL(r.url),t=e.protocol==="http:"?ec.Agent:tc.Agent;return new t(Zl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function pm(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Pn.GZIP?Pn.GZIP:Pn.NONE}_e();var ZD=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)}}(),rc=function(r){ZD(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&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Xa(t.headers),fi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=dm(t),i.compression=pm(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){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;um(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}(VT);function $T(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function ek(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function qT(r){var e=$T(r);return ek(e)}function tk(r){var e=$T(r);return e.toString()}var rk=typeof BigInt<"u"?tk:sT;function jT(r){return r}function KT(r){if(r!==void 0)return Wl(r)}var nk={encodeHrTime:qT,encodeSpanContext:Wl,encodeOptionalSpanContext:KT};function YT(r){var e,t;if(r===void 0)return nk;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?qT:rk,encodeSpanContext:o?jT:Wl,encodeOptionalSpanContext:o?jT:KT}}var 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};function XT(r){return{name:r.name,version:r.version}}function bi(r){return Object.keys(r).map(function(e){return JT(e,r[e])})}function JT(r,e){return{key:r,value:QT(e)}}function QT(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(QT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ok(t,2),o=n[0],i=n[1];return JT(o,i)})}}:{}}function ZT(r){return{attributes:bi(r.attributes),droppedAttributesCount:0}}_e();function tv(r,e){var t=YT(e);return{resource:ZT(r.resource),schemaUrl:void 0,scopeMetrics:ik(r.scopeMetrics,t)}}function ik(r,e){return Array.from(r.map(function(t){return{scope:XT(t.scope),metrics:t.metrics.map(function(n){return ak(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function ak(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=uk(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:ev(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:ev(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:lk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ck(r,e)};break}return t}function sk(r,e,t){var n={attributes:bi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case jt.INT:n.asInt=r.value;break;case jt.DOUBLE:n.asDouble=r.value;break}return n}function ev(r,e){return r.dataPoints.map(function(t){return sk(t,r.descriptor.valueType,e)})}function lk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:bi(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 ck(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:bi(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 uk(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function rv(r,e){return{resourceMetrics:r.map(function(t){return tv(t,e)})}}var mm={serializeRequest:function(r){var e=rv(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 nv="0.52.1";var ov=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(){return Ei=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},Ei.apply(this,arguments)},iv="v1/metrics",dk="http://localhost:4318/"+iv,pk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+nv},mk=function(r){ov(e,r);function e(t){var n=r.call(this,t,mm,"application/json")||this;return n.headers=Ei(Ei(Ei(Ei({},n.headers),pk),fi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Xa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?am(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?im(bt().OTEL_EXPORTER_OTLP_ENDPOINT,iv):dk},e}(rc),av=function(r){ov(e,r);function e(t){return r.call(this,new mk(t),t)||this}return e}(DT);var Ti;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Ti||(Ti={}));var Fr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Fr||(Fr={}));_e();var gk=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)}}(),sv=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())})},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}}},hk=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},fk=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))},Sk=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 cv(r){return r!=null}function nc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function uv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var gm=function(r){gk(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function In(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new gm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function dv(r){return sv(this,void 0,void 0,function(){var e=this;return lv(this,function(t){return[2,Promise.all(r.map(function(n){return sv(e,void 0,void 0,function(){var o,i;return lv(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 pv(r){return r.status==="rejected"}function hm(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,fk([],hk(e(n)),!1))}),t}function mv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=Sk(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 gv(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 hv(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var cr;(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"})(cr||(cr={}));var fm=function(){function r(){this.kind=cr.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}();_e();var he;(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"})(he||(he={}));function Br(r,e,t){var n,o,i,a;return bk(r)||H.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:jt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function fv(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 Sv(r,e){return hv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var yk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function bk(r){return r.match(yk)!=null}var 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};function Tk(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 oc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=Tk(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=gv(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 ic=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=cr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new oc(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 oc(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 oc(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:Fr.HISTOGRAM,dataPoints:n.map(function(i){var a=Ek(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.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}();_e();var Sm=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},ym=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))},bm=function(){function r(e,t,n,o){e===void 0&&(e=new vk),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 vk=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,ym([n,this._counts.length-t],Sm(this._counts.slice(t)),!1)),o.splice.apply(o,ym([0,t],Sm(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(ym([],Sm(this._counts),!1))},r}();var yv=52,Ak=2146435072,wk=1048575,Em=1023,ac=-Em+1,sc=Em,Ja=Math.pow(2,-1022);function lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&Ak)>>20;return n-Em}function cc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&wk)*Math.pow(2,32);return o+n}function Qa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Ev(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}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)}}(),On=function(r){Ck(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var vv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ja)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,yv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new On("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new On("overflow: "+e+" is > maximum lower boundary: "+n);return Qa(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=ac>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return sc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Av=function(){function r(e){this._scale=e,this._scaleFactor=Qa(Math.LOG2E,e),this._inverseFactor=Qa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ja)return this._minNormalLowerBoundaryIndex()-1;if(cc(e)===0){var t=lc(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 On("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ja;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new On("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 ac<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(sc+1<<this._scale)-1},r}();var wv=-10,Cv=20,Rk=Array.from({length:31},function(r,e){return e>10?new Av(e-10):new vv(e-10)});function Tm(r){if(r>Cv||r<wv)throw new On("expected scale >= "+wv+" && <= "+Cv+", got: "+r);return Rk[r+10]}var xk=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},uc=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}(),Mk=20,_k=160,vm=2,Rv=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_k),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 bm),u===void 0&&(u=new bm),d===void 0&&(d=Tm(Mk)),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<vm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+vm),this._maxSize=vm)}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=Ev(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=Tm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=uc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=uc.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 uc(0,-1);var o=t-n;return new uc(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 Am=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Rv(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:Fr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=xk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.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}();_e();var Pk=Np("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function xv(r){return r.setValue(Pk,!0)}_e();function Mv(){return function(r){H.error(Ik(r))}}function Ik(r){return typeof r=="string"?r:JSON.stringify(Ok(r))}function Ok(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 Lk=Mv();function dc(r){try{Lk(r)}catch{}}var _v="1.30.1";var Nk="process.runtime.name";var Dk="service.name";var kk="telemetry.sdk.name",Uk="telemetry.sdk.language",Fk="telemetry.sdk.version";var Pv=Nk;var Iv=Dk;var Za=kk,es=Uk,ts=Fk;var Bk="nodejs";var Ov=Bk;var vi,ho=(vi={},vi[Za]="opentelemetry",vi[Pv]="node",vi[es]=Ov,vi[ts]=_v,vi);function rs(r){r.unref()}var $k=9,qk=6,Kk=Math.pow(10,qk),Eae=Math.pow(10,$k);function fo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Kk);return[t,n]}function Ai(r){return r[0]*1e6+r[1]/1e3}var ns;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ns||(ns={}));_e();function Lv(r,e){return new Promise(function(t){hi.with(xv(hi.active()),function(){r.export(e,function(n){t(n)})})})}var Nv={_export:Lv};var Yk=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},pc=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=fo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var wm=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new pc(e)},r.prototype.merge=function(e,t){var n=Ai(t.sampleTime)>=Ai(e.sampleTime)?t:e;return new pc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ai(t.sampleTime)>=Ai(e.sampleTime)?t:e;return new pc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.GAUGE,dataPoints:n.map(function(i){var a=Yk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var Xk=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},wi=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 mc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new wi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new wi(t.startTime,this.monotonic,o,t.reset):new wi(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 wi(t.startTime,this.monotonic,o,!0):new wi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.SUM,dataPoints:n.map(function(i){var a=Xk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var So=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)}}(),ur=function(){function r(){}return r.Drop=function(){return Hv},r.Sum=function(){return Gv},r.LastValue=function(){return Vv},r.Histogram=function(){return Wv},r.ExponentialHistogram=function(){return Jk},r.Default=function(){return Qk},r}();var Dv=function(r){So(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 fm,e}(ur);var kv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case he.COUNTER:case he.OBSERVABLE_COUNTER:case he.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new mc(!0),e.NON_MONOTONIC_INSTANCE=new mc(!1),e}(ur);var Uv=function(r){So(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 wm,e}(ur);var Fv=function(r){So(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 ic([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ur);var os=function(r){So(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 ic(this._boundaries,this._recordMinMax)},e}(ur);var Bv=function(r){So(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 Am(this._maxSize,this._recordMinMax)},e}(ur);var zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case he.COUNTER:case he.UP_DOWN_COUNTER:case he.OBSERVABLE_COUNTER:case he.OBSERVABLE_UP_DOWN_COUNTER:return Gv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return Vv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new os(t.advice.explicitBucketBoundaries):Wv}return H.warn("Unable to recognize instrument type: "+t.type),Hv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Hv=new Dv,Gv=new kv,Vv=new Uv,Wv=new Fv,Jk=new Bv,Qk=new zv;var jv=function(r){return ur.Default()},$v=function(r){return Ti.CUMULATIVE};var Cm=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())})},Rm=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}}},qv=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},Zk=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))},Kv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:jv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:$v,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 Cm(this,void 0,void 0,function(){var t,n,o,i,a,s;return Rm(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(Zk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],qv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=qv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(hm(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(hm(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Cm(this,void 0,void 0,function(){return Rm(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,In(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Cm(this,void 0,void 0,function(){return Rm(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,In(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var e0=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)}}(),gc=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())})},hc=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}}},t0=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},r0=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))},xm=function(r){e0(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 gc(this,void 0,void 0,function(){var t;return hc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,In(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof gm?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(dc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return gc(this,void 0,void 0,function(){var o,i,a,s,c,l;return hc(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=H).error.apply(l,r0(["PeriodicExportingMetricReader: metrics collection errors"],t0(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(),H.debug("Error while resolving async portion of resource: ",s),dc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Nv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ns.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),rs(this._interval)},e.prototype.onForceFlush=function(){return gc(this,void 0,void 0,function(){return hc(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 gc(this,void 0,void 0,function(){return hc(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}(Kv);_e();_e();function fc(){return"unknown_service:"+process.argv0}var Ln=function(){return Ln=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},Ln.apply(this,arguments)},n0=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())})},o0=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}}},i0=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){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 H.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[Iv]=fc(),e[es]=ho[es],e[Za]=ho[Za],e[ts]=ho[ts],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 n0(this,void 0,void 0,function(){return o0(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=Ln(Ln({},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=i0(a,2),l=c[0],u=c[1];return Ln(Ln(Ln(Ln({},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 Yv=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}();_e();var yo=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)}}(),yc=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=hi.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===jt.INT&&!Number.isInteger(e)&&(H.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,fo(Date.now()))},r}();var Xv=function(r){yo(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}(yc);var Jv=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(yc);var Qv=function(r){yo(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}(yc);var Zv=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(yc);var bc=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 eA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var tA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var rA=function(r){yo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function is(r){return r instanceof bc}var nA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Br(e,he.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Qv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Zv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Jv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Br(e,he.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new eA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Br(e,he.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rA(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 Ec=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Br(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var a0=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)}}(),oA=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}}},s0=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 oA(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 oA(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 Tr=function(r){a0(e,r);function e(){return r.call(this,nc)||this}return e}(s0);var l0=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},Tc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Tr,this._cumulativeMemoStorage=new Tr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=nc(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=l0(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 Tr,e},r}();var Mm=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.")},iA=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},vc=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===Ti.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=c0(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=Mm(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 Tr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Mm(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=iA(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=Mm(e.keys()),s=a.next();!s.done;s=a.next()){var c=iA(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 c0(r){return Array.from(r.entries())}var u0=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)}}(),d0=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},aA=function(r){u0(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 Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Tr;Array.from(t.entries()).forEach(function(a){var s=d0(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}(Ec);_e();function _m(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
28
28
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
29
29
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
30
30
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
@@ -4340,9 +4340,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Eo(o.url,this.logger)){
|
|
|
4340
4340
|
`),tokenLength:d}),u=[],d=0,p=g.length?[g[g.length-1].id]:[],m=!1);let h=c[l],f=wr(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(iR)).map(K=>K&&K.length>=3?{tagName:K[1],id:K[2]}:void 0).filter(K=>!!K),T=Array.from(h.matchAll(XB)).map(K=>K&&(K[2]||K[4])).filter(K=>!!K);T.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let K of x)p.push(K.id),g.push(K);for(let K of T){let j=g[g.length-1];j&&j.tagName===K&&g.pop()}let A=g.some(K=>QB.includes(K.tagName)),N=c[l+1]??"",G=wr(N),ye=Array.from(N.matchAll(iR)).map(K=>K&&K.length>2?K[1]:void 0).filter(K=>!!K),Se=ye.some(K=>lR.includes(K)),Ae=ye.some(K=>JB.includes(K));d+G>=i&&(m=!0),d>=n&&(Se&&!A||T.some(K=>ZB.includes(K)))&&(m=!0),d>=o&&Ae&&!A&&(m=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
|
|
4341
4341
|
`),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 rz=75e4,ou=3e5;async function Co(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=wr(u);if(d>rz)try{let p=nu({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await oz({...r,tokenLimit:ou-1e4,chunks:p.chunks}),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*kn),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using naive truncation"),d=g}if(d>ou)try{if(o){let p=nu({serializedTree:u,options:sR,logger:i}),g=tz();l=await k(nz({...r,chunks:p.chunks,callId:g}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=wr(u);i.info({oldTokens:d,newTokens:m,langfuseCallId:g},"Filtered page using AI chunk ranking"),d=m}else{let p=nu({serializedTree:u,options:aR,logger:i});l=await k(iz({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using RAG"),d=g}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*kn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function nz({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:fe(c)}),u=[];return t.forEach((p,g)=>{l.indices.includes(g)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function oz(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:fe(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(g=>g.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((g,m)=>g+m.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(g=>g.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function iz(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:fe(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 Ng(r,e){if(!r.description)throw new R("UserConfigurationError","Cannot locate element with empty description");return gr({action:async()=>az(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function az(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:g,localCodeEvalTools:m,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await ss({orgId:p,s:E,context:n,localTools:m,signal:f,logger:l})),a&&(E=lz(E,a));let{serializedTree:x,tree:w}=await jr(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),T,_=Date.now(),A;for(;!T&&Date.now()-_<3e3;){f.throwIfAborted();try{T=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Q){A=Q}}if(!T)throw new R("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${A?.message}`);let N=x,G=!1,ye=`data:image/jpeg;base64,${T.toString("base64")}`;N=await Co({type:"locator",description:E,screenshot:ye,serializedTree:x,options:{aiPageFiltering:c},tree:w,fixtures:{generator:h,signal:f,logger:l,orgId:p}}),N!==x&&(G=!0);let Se=await h.getElementLocation({browserState:N,goal:E,screenshot:ye,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:fe(l),useMemory:b});l.debug({usedRag:G,result:Se},"Got locator result");let Ae=Se.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:Ae,pageState:N,ragUsed:G,thoughts:Se.thoughts}),!Ae)throw new Sn(`Could not find any relevant element: ${Se.thoughts}`,Se.updatedMemory?{type:"GCS_TRACES",traces:Se.updatedMemory}:void 0);let{resolution:K,target:j,frameConfig:le}=await g.createTargetFromA11yId({id:Se.id,requirements:Se.requirements,additionalElements:Se.additionalElements,description:E,targetSource:"AI",logger:l});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new R("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: ${K.displayString}`);return b&&(Se.updatedMemory?j.memory={type:"GCS_TRACES",traces:Se.updatedMemory}:s&&(j.memory=s)),{thoughts:Se.thoughts,target:j,resolution:K,frameConfig:le,screenshot:ye}}var sz=["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:"],cR="<select> element:",uR="text input or contenteditable element:",dR="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:",pR="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:",Lg=[cR,uR,dR,pR,...sz];function mR(r,e){if(r===e)return!0;for(let t of Lg){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Lg.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Lg.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function lz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${cR} ${r}`;case"TYPE":return`${uR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${dR}
|
|
4342
4342
|
${r}`;case"ELEMENT_CHECK":return`${pR}
|
|
4343
|
-
${r}`;default:return r}}var cz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=cz}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Bc(c),u=0,d=Date.now(),p,g,m;try{await gr({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 q(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await gr({action:async()=>{let b=await gR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(g=b,hR({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?.success){p?.updatedMemory&&ls(r,p.updatedMemory,t);break}else throw p?.thoughts?new R("AssertionFailureError",p.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),m=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 gr({action:async()=>hR({command:r,state:await gR(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(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&ls(r,p.updatedMemory,t),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new R("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function gR(r,e,t){let[n,o]=await Promise.all([jr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function hR({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,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",w=m;x!=="VISION_ONLY"&&(w=await Co({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),w!==m&&(g.ragUsed=!0),g.pageState=w);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:w,screenshot:E,contextChoice:x,source:c},A=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:fe(l)});return(A.result||i)&&A.relevantElements&&(g.relevantElementsSerialized=A.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await uz(A.relevantElements,u,l)),{success:A.result,thoughts:A.thoughts,afterScreenshotOverride:f,updatedMemory:o?A.updatedMemory:void 0}}async function uz(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 dz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function fR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await pz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof au?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 q(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function pz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await q(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await k(mz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function mz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>gz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function gz(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 ss({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(p)>dz)throw new au;s.throwIfAborted();let m;try{m=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("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,${m.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as yR}from"lodash-es";async function bR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>$h(e.cache)?e.cache:void 0,a=i(),s=yR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=XA(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,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await SR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&ks(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await SR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let m=i();return d.success&&m?.target&&!g&&(m.target=zm(m.target),m.updatedAt=new Date),d}async function SR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!gn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=yR(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>hz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ma(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{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 R)||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 hz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await fz(r,e.assertion)}async function fz(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:gt(a,500,!0)},!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:gt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},zt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:zt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:zt*1e3});break}case"FOCUSED":{t=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(t=e.negated?!t:t,!t){let a=dr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function ER(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as Sz}from"jimp";async function gs(r,e){let t=await r.screenshot(e),n=await Sz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as TR}from"jimp";import Dg from"jpeg-js";import yz from"pixelmatch";async function vR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!gn(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 ye=>gs(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await gs(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 W=`${l.width}x${l.height}`,ye=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${W}) does not match saved screenshot dimensions (${ye}) - 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 TR.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await TR.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),x=Math.abs(p.width-m.width);if(f>E){let W=d.cover({w:m.width,h:m.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let W=g.cover({w:p.width,h:p.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let w={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,A=yz(Dg.decode(u.buffer).data,Dg.decode(l.buffer).data,w.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=A>T*100,G=`Visual diff of ${A.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${T*100}%.`;if(h&&(G+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),N)throw new R("ActionFailureError",G);return{fail:N,thoughts:G,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Dg.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var bz=3e4;function Ez(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function su({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??bz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let s=a.toString(),c;if(xi(r.url)&&(c=r.url),t&&Mi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("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 g=s?`${c}?${s}`:c;try{let m=Ez(r);return await n(g,{headers:{...m.contentType?{"Content-Type":m.contentType}:{},...i},method:r.method,body:m.content})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(m){g=`Failed to read response body: ${m}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,m)=>{d[m]=g});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 Tz=5e3;async function wR({timeout:r=zt,...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 lu(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 q(s,e.signal),s=Math.min(Math.floor(s*1.5),Tz);else return i}return i=await lu(e),i}async function lu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(AR,{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(AR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?rn.CONTAINS:nn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("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)}}function AR({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 vz=3e4;async function CR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??vz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(xi(r.url)&&(s=r.url),t&&Mi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("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 R("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 R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("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 cu=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([jr(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 Co({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:{...fe(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([jr(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 Co({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}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(a)},langfuseSessionId:s})}catch(m){throw new R("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Ng({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return gr({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],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}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 R("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 gr({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&&pd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(hd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(fd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Ir&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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 R("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 q(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:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=RR(e.cache);if((!b||l)&&!Xu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.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&&!mR(o.elementDescriptor,b.inputDescription)&&(m.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&&ks(T),w=!0;if(!x(b)){w=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await fR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:m,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let T;try{T=await Ng({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(N){if(N instanceof Sn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:m,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,m),A=await a(_);return Dc({cmd:c,key:d,newTarget:T.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=fe(m)),{result:A,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let _=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,m),A=await a(_);if(Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.4"]),Dc({cmd:c,key:d,newTarget:b,logger:m,updatedWithAI:!1}),w){let N=T.decisions.filter(G=>G.matched);if(N.length!==1)m.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let G=N[0].type;n.recordTargetAutoHeal({healType:G})}}return{result:A,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed();let _="unknown";T instanceof Pr&&T.cacheMissReason&&(_=T.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.4",`missReason:${_}`]);let A=!1;if((T instanceof Ir||pd(T)||hd(T)||fd(T)||Zf(T)||md(T)||eS(T))&&(A=!0),T instanceof R&&!A)throw m.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){m.info({err:T},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Hh(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("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 gs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(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 R("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&&yf(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await oR({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{Lc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>ig(e)}}async resolveCommandTemplateStrings(e,t){return Oc({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()?iu({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 R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return iu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=tE(n.schema);if(f)throw new R("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:fe(a)});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("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 R("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 R("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(!xi(n.url)&&!Mi(n.url,this.browser.baseUrl))throw new R("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:m=>this.browser.click(m,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 m,h;if(n.target&&xr(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:w=>this.browser.hover(w),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=x}let f=this.browser.getViewport()?.height??Tn.height,E=this.browser.getViewport()?.width??Tn.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:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(xr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=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 Hc(m,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(xr(n.fromTarget)&&xr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(xr(n.fromTarget)||xr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,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:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&xr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(m,h,f,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=w}else await this.browser.mouseDrag(m,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!gn(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ma(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);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 m;try{n.environment==="BROWSER"?(m=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:m},"Executed JavaScript in browser")):m=await zr({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 R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&xr(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 m=this.browser.url(),h,f,E=RR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:w,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{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:ma(n)}});h=w,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 Hc(m,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(xr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"FOCUS":{if(!gn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"BLUR":{if(n.target&&!gn(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:m,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:m,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 Hc(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 m=new wz,h=Az(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:pl(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await CR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return vR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await $w({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=Ey.optional().parse(m)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(ER(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 iu({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&&ls(n,E.cache?.memory.traces,a)}}let f=await bR({command:n,tracer:t,timeoutMs:m,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 m=await gr({action:async()=>wR({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:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new Un(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await dg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new Un(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>m.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new Un(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Un(n.requestMatcher),async(h,f)=>{let E=await zr({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=zy.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(m=>{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:fe(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 eu({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:fe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:fe(this.logger)})}};import{cloneDeep as Cz}from"lodash-es";import IR from"truncate-json";var xR=1e3,MR=5e6,Rz=5*1024*1024;function OR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=IR(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":_R(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":_R(n),OR(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 _R(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function PR(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 uu(r,e){let t=Cz(r);if(OR(t,e),t.length>xR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,xR);let n=PR(t,e);if(n.length>MR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>MR;)t.pop(),n=PR(t,e);let{jsonString:o}=IR(n,Rz);try{return Ut.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 xz}from"async_hooks";var hs=new xz;function Mz(r){hs.enterWith({activeTracers:[r]})}function _z(r,e){let t=hs.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Pz(r,e){let t=hs.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return hs.run({activeTracers:n},e)}var an={globalAls:hs,initializeRootTracerContext:Mz,withChildTracer:_z,withChildTracerAsync:Pz};var Ro=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 an.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 an.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await an.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,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`}):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 ee(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Ro}async function LR(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=Iz(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 Iz(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 Xz}from"fs";import{tmpdir as Jz}from"os";import BR from"path";import{diff as Kz}from"deep-object-diff";import{cloneDeep as Yz}from"lodash-es";import kR from"fontoxpath";import Oz from"@prettier/plugin-xml";import Lz from"prettier";import{DOMParser as Nz,XMLSerializer as Dz}from"slimdom";var kz=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 fs(r){let e=r.toLowerCase();return e.endsWith("webview")||kz.has(e)}function Uz(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 Fz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Bz=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"]),zz=new Set(["text","hint"]),Hz=new Set(["live-region","drawing-order"]),Gz=new Set(["displayed","enabled"]);function Vz(r,e){let t={};for(let[n,o]of Object.entries(e))Fz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Bz.has(n)&&o==="false"||zz.has(n)&&o===""||Gz.has(n)&&o==="true"||Hz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function NR(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 g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=Vz(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),fs(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(`
|
|
4343
|
+
${r}`;default:return r}}var cz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=cz}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Bc(c),u=0,d=Date.now(),p,g,m;try{await gr({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 q(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await gr({action:async()=>{let b=await gR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(g=b,hR({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?.success){p?.updatedMemory&&ls(r,p.updatedMemory,t);break}else throw p?.thoughts?new R("AssertionFailureError",p.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),m=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 gr({action:async()=>hR({command:r,state:await gR(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(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&ls(r,p.updatedMemory,t),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new R("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function gR(r,e,t){let[n,o]=await Promise.all([jr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function hR({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,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",w=m;x!=="VISION_ONLY"&&(w=await Co({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),w!==m&&(g.ragUsed=!0),g.pageState=w);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:w,screenshot:E,contextChoice:x,source:c},A=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:fe(l)});return(A.result||i)&&A.relevantElements&&(g.relevantElementsSerialized=A.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await uz(A.relevantElements,u,l)),{success:A.result,thoughts:A.thoughts,afterScreenshotOverride:f,updatedMemory:o?A.updatedMemory:void 0}}async function uz(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 dz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function fR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await pz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof au?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 q(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function pz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await q(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await k(mz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function mz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>gz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function gz(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 ss({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(p)>dz)throw new au;s.throwIfAborted();let m;try{m=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("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,${m.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as yR}from"lodash-es";async function bR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>$h(e.cache)?e.cache:void 0,a=i(),s=yR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=XA(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,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await SR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&ks(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await SR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let m=i();return d.success&&m?.target&&!g&&(m.target=zm(m.target),m.updatedAt=new Date),d}async function SR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!gn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=yR(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>hz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ma(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{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 R)||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 hz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await fz(r,e.assertion)}async function fz(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:gt(a,500,!0)},!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:gt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},zt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:zt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:zt*1e3});break}case"FOCUSED":{t=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(t=e.negated?!t:t,!t){let a=dr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function ER(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as Sz}from"jimp";async function gs(r,e){let t=await r.screenshot(e),n=await Sz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as TR}from"jimp";import Dg from"jpeg-js";import yz from"pixelmatch";async function vR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!gn(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 ye=>gs(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await gs(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 W=`${l.width}x${l.height}`,ye=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${W}) does not match saved screenshot dimensions (${ye}) - 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 TR.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await TR.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),x=Math.abs(p.width-m.width);if(f>E){let W=d.cover({w:m.width,h:m.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let W=g.cover({w:p.width,h:p.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let w={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,A=yz(Dg.decode(u.buffer).data,Dg.decode(l.buffer).data,w.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=A>T*100,G=`Visual diff of ${A.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${T*100}%.`;if(h&&(G+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),N)throw new R("ActionFailureError",G);return{fail:N,thoughts:G,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Dg.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var bz=3e4;function Ez(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function su({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??bz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let s=a.toString(),c;if(xi(r.url)&&(c=r.url),t&&Mi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("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 g=s?`${c}?${s}`:c;try{let m=Ez(r);return await n(g,{headers:{...m.contentType?{"Content-Type":m.contentType}:{},...i},method:r.method,body:m.content})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(m){g=`Failed to read response body: ${m}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,m)=>{d[m]=g});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 Tz=5e3;async function wR({timeout:r=zt,...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 lu(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 q(s,e.signal),s=Math.min(Math.floor(s*1.5),Tz);else return i}return i=await lu(e),i}async function lu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(AR,{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(AR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?rn.CONTAINS:nn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("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)}}function AR({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 vz=3e4;async function CR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??vz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(xi(r.url)&&(s=r.url),t&&Mi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("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 R("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 R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("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 cu=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([jr(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 Co({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:{...fe(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([jr(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 Co({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}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(a)},langfuseSessionId:s})}catch(m){throw new R("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Ng({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return gr({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],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}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 R("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 gr({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&&pd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(hd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(fd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Ir&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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 R("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 q(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:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=RR(e.cache);if((!b||l)&&!Xu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.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&&!mR(o.elementDescriptor,b.inputDescription)&&(m.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&&ks(T),w=!0;if(!x(b)){w=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await fR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:m,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let T;try{T=await Ng({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(N){if(N instanceof Sn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:m,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,m),A=await a(_);return Dc({cmd:c,key:d,newTarget:T.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=fe(m)),{result:A,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let _=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,m),A=await a(_);if(Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.5"]),Dc({cmd:c,key:d,newTarget:b,logger:m,updatedWithAI:!1}),w){let N=T.decisions.filter(G=>G.matched);if(N.length!==1)m.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let G=N[0].type;n.recordTargetAutoHeal({healType:G})}}return{result:A,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed();let _="unknown";T instanceof Pr&&T.cacheMissReason&&(_=T.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.5",`missReason:${_}`]);let A=!1;if((T instanceof Ir||pd(T)||hd(T)||fd(T)||Zf(T)||md(T)||eS(T))&&(A=!0),T instanceof R&&!A)throw m.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){m.info({err:T},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Hh(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("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 gs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(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 R("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&&yf(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await oR({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{Lc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>ig(e)}}async resolveCommandTemplateStrings(e,t){return Oc({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()?iu({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 R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return iu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=tE(n.schema);if(f)throw new R("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:fe(a)});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("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 R("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 R("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(!xi(n.url)&&!Mi(n.url,this.browser.baseUrl))throw new R("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:m=>this.browser.click(m,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 m,h;if(n.target&&xr(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:w=>this.browser.hover(w),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=x}let f=this.browser.getViewport()?.height??Tn.height,E=this.browser.getViewport()?.width??Tn.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:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(xr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=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 Hc(m,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(xr(n.fromTarget)&&xr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(xr(n.fromTarget)||xr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,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:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&xr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(m,h,f,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=w}else await this.browser.mouseDrag(m,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!gn(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ma(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);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 m;try{n.environment==="BROWSER"?(m=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:m},"Executed JavaScript in browser")):m=await zr({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 R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&xr(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 m=this.browser.url(),h,f,E=RR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:w,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{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:ma(n)}});h=w,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 Hc(m,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(xr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"FOCUS":{if(!gn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"BLUR":{if(n.target&&!gn(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:m,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:m,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 Hc(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 m=new wz,h=Az(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:pl(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await CR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return vR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await $w({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=Ey.optional().parse(m)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(ER(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 iu({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&&ls(n,E.cache?.memory.traces,a)}}let f=await bR({command:n,tracer:t,timeoutMs:m,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 m=await gr({action:async()=>wR({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:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new Un(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await dg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new Un(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>m.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new Un(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Un(n.requestMatcher),async(h,f)=>{let E=await zr({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=zy.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(m=>{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:fe(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 eu({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:fe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:fe(this.logger)})}};import{cloneDeep as Cz}from"lodash-es";import IR from"truncate-json";var xR=1e3,MR=5e6,Rz=5*1024*1024;function OR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=IR(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":_R(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":_R(n),OR(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 _R(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function PR(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 uu(r,e){let t=Cz(r);if(OR(t,e),t.length>xR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,xR);let n=PR(t,e);if(n.length>MR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>MR;)t.pop(),n=PR(t,e);let{jsonString:o}=IR(n,Rz);try{return Ut.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 xz}from"async_hooks";var hs=new xz;function Mz(r){hs.enterWith({activeTracers:[r]})}function _z(r,e){let t=hs.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Pz(r,e){let t=hs.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return hs.run({activeTracers:n},e)}var an={globalAls:hs,initializeRootTracerContext:Mz,withChildTracer:_z,withChildTracerAsync:Pz};var Ro=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 an.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 an.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await an.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,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`}):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 ee(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Ro}async function LR(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=Iz(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 Iz(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 Xz}from"fs";import{tmpdir as Jz}from"os";import BR from"path";import{diff as Kz}from"deep-object-diff";import{cloneDeep as Yz}from"lodash-es";import kR from"fontoxpath";import Oz from"@prettier/plugin-xml";import Lz from"prettier";import{DOMParser as Nz,XMLSerializer as Dz}from"slimdom";var kz=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 fs(r){let e=r.toLowerCase();return e.endsWith("webview")||kz.has(e)}function Uz(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 Fz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Bz=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"]),zz=new Set(["text","hint"]),Hz=new Set(["live-region","drawing-order"]),Gz=new Set(["displayed","enabled"]);function Vz(r,e){let t={};for(let[n,o]of Object.entries(e))Fz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Bz.has(n)&&o==="false"||zz.has(n)&&o===""||Gz.has(n)&&o==="true"||Hz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function NR(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 g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=Vz(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),fs(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(`
|
|
4344
4344
|
${p}
|
|
4345
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p;if(!$z(m,s?.viewportBounds))continue;let h=n.createElement(Uz(m.tagName));NR(r,m,h),t.appendChild(h)}}}function Wz(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;NR(a,e,s);let c=new Dz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function DR(r,e){let t=new Nz,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}=Wz(t,i,o,e);return{xml:await Lz.format(c,{parser:"xml",plugins:[Oz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function jz(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 du(r,e){let t=r.idToElement.get(e);if(t)return jz(t)}function kg(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 xo(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 $z(r,e){if(!e)return!0;let t=xo(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function Ug(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function FR({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=xo(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=kg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Ug(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:g,requirements:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Ug(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return fs(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},{target:p,resolvedNode:n}}var UR=(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=xo(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 pu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ee();if(e.type==="WEBVIEW")return qz(e,r);let a=kR.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 g of p){let m=kR.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);UR(m,g.requirements)}})}let s=xo(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");UR(a,e.requirements,e.bounds);let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=kg(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function qz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ee(),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 Ni(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ei.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function mu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var Xe=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,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),p=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:p}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let p=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:fe(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=p,p})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new yn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=FR({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let p=await this.stateManager.getActiveWebview();if(!p||!p.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await p.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:p.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d;if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=e.retriesWithAI??1,g=!1,m=Yz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,m=void 0),s&&(g=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,m=void 0),!m){p--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Ni({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSection("Resolve target cache",async(w,T)=>{let{resolvedTarget:_}=await pu({target:m,domState:f,stateManager:this.stateManager,logger:this.logger}),A=mu(_),N=Kz(m,A);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),T.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:A}}),x=await t(E);return Ni({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),m.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.4"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(m.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.4"]),this.throwIfAborted(),p>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:p-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function Qz(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 Di=class extends Xe{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=BR.join(Jz(),"momentic","downloads"),s=BR.join(a,this.orgId,i);return Xz(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 ee().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=ee(),n=Qz(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 zn=class extends Xe{async doPress({keycode:e,longPress:t}){await ee().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var zR=25,gu=class extends Xe{async doType(e){let t=ee();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:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}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 ee().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??zR};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Di(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ee(),n=e.keyPressDelayMs??zR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){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=ee();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, 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 zn(this.constructPerformerParams()).doPress({keycode:67})}};import $t from"zod";var HR=.8,Hn=.2,Zz=$t.object({navigationBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()}),statusBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()})}),ki=class extends Xe{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Zz.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*Hn),n=Math.floor(e.height*Hn);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*Hn),l=Math.floor(s*Hn);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=ee();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>ee().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}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*Hn),s=Math.floor(i*Hn);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 swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Hn),u=Math.floor(c.height*Hn),d=Math.max(1,c.width-l*2),p=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+p/2},m=(s?p:d)*(t.viewportPercent??HR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=m,await o.browser.mouseDragUsingVisualCoordinates(s?0:m,s?m:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=HR,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{execSync as qR}from"child_process";import r1 from"pixelmatch";import{_android as n1,chromium as o1}from"playwright";import{PNG as KR}from"pngjs";import{z as Ge}from"zod";var GR=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),VR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),WR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),jR=Ge.array(WR.extend({info:GR.optional(),pages:Ge.array(VR).optional()})),m_e=Ge.array(WR.extend({info:GR,pages:Ge.array(VR)}));function Fg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=KR.sync.read(n),a=KR.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return r1(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var hu=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{let m=(await n1.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:m.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),m.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(m.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=m[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=2){let t=ee(),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:3e3})}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 ee().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1;for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(Fg(c,u)<=o){l=!0;break}c=u,await q(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");(fs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:xo(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ee().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 ee().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await DR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ee().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}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.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await ee().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=qR(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 ee().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=jR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4345
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p;if(!$z(m,s?.viewportBounds))continue;let h=n.createElement(Uz(m.tagName));NR(r,m,h),t.appendChild(h)}}}function Wz(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;NR(a,e,s);let c=new Dz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function DR(r,e){let t=new Nz,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}=Wz(t,i,o,e);return{xml:await Lz.format(c,{parser:"xml",plugins:[Oz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function jz(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 du(r,e){let t=r.idToElement.get(e);if(t)return jz(t)}function kg(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 xo(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 $z(r,e){if(!e)return!0;let t=xo(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function Ug(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function FR({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=xo(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=kg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Ug(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:g,requirements:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Ug(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return fs(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},{target:p,resolvedNode:n}}var UR=(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=xo(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 pu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ee();if(e.type==="WEBVIEW")return qz(e,r);let a=kR.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 g of p){let m=kR.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);UR(m,g.requirements)}})}let s=xo(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");UR(a,e.requirements,e.bounds);let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=kg(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function qz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ee(),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 Ni(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ei.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function mu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var Xe=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,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),p=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:p}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let p=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:fe(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=p,p})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new yn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=FR({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let p=await this.stateManager.getActiveWebview();if(!p||!p.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await p.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:p.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d;if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=e.retriesWithAI??1,g=!1,m=Yz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,m=void 0),s&&(g=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,m=void 0),!m){p--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Ni({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSection("Resolve target cache",async(w,T)=>{let{resolvedTarget:_}=await pu({target:m,domState:f,stateManager:this.stateManager,logger:this.logger}),A=mu(_),N=Kz(m,A);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),T.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:A}}),x=await t(E);return Ni({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),m.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.5"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(m.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.5"]),this.throwIfAborted(),p>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:p-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function Qz(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 Di=class extends Xe{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=BR.join(Jz(),"momentic","downloads"),s=BR.join(a,this.orgId,i);return Xz(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 ee().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=ee(),n=Qz(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 zn=class extends Xe{async doPress({keycode:e,longPress:t}){await ee().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var zR=25,gu=class extends Xe{async doType(e){let t=ee();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:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}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 ee().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??zR};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Di(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ee(),n=e.keyPressDelayMs??zR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){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=ee();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, 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 zn(this.constructPerformerParams()).doPress({keycode:67})}};import $t from"zod";var HR=.8,Hn=.2,Zz=$t.object({navigationBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()}),statusBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()})}),ki=class extends Xe{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Zz.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*Hn),n=Math.floor(e.height*Hn);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*Hn),l=Math.floor(s*Hn);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=ee();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>ee().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}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*Hn),s=Math.floor(i*Hn);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 swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Hn),u=Math.floor(c.height*Hn),d=Math.max(1,c.width-l*2),p=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+p/2},m=(s?p:d)*(t.viewportPercent??HR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=m,await o.browser.mouseDragUsingVisualCoordinates(s?0:m,s?m:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=HR,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{execSync as qR}from"child_process";import r1 from"pixelmatch";import{_android as n1,chromium as o1}from"playwright";import{PNG as KR}from"pngjs";import{z as Ge}from"zod";var GR=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),VR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),WR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),jR=Ge.array(WR.extend({info:GR.optional(),pages:Ge.array(VR).optional()})),m_e=Ge.array(WR.extend({info:GR,pages:Ge.array(VR)}));function Fg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=KR.sync.read(n),a=KR.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return r1(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var hu=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{let m=(await n1.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:m.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),m.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(m.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=m[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=2){let t=ee(),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:3e3})}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 ee().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1;for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(Fg(c,u)<=o){l=!0;break}c=u,await q(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");(fs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:xo(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ee().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 ee().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await DR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ee().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}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.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await ee().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=qR(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 ee().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=jR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4346
4346
|
${o}
|
|
4347
4347
|
Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;if(!o.info||!o.pages)return!1;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?!!i:(this.logger.debug({context:o},"Webview has no qualified pages, skipping"),!1)})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await ee().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await ms.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{autoExpandIframes:!0,visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new cu({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new _l})})}async connectPlaywrightToWebview(e,t){return ee().startAsyncSection("Connect headless browser client to webview",async()=>{for(let o=0;o<2;o++)try{return await this.connectPlaywrightToWebviewHelper(e,t)}catch(i){this.logger.warn({err:i},"Failed to connect Playwright to webview, retrying...")}},{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}extractSocketNameFromWebview(e,t){if("_socketName"in e&&typeof e._socketName=="string")return e._socketName;if("_data"in e&&e._data?.socketName)return e._data.socketName;t.warn({pkg:e.pkg()},"Could not extract socket name from webview")}async connectPlaywrightToWebviewHelper(e,t){let n=this.device.webViews(),o=n.find(l=>!(l.pkg()!==e||this.extractSocketNameFromWebview(l,this.logger)!==t));if(!o){let l=`Could not find webview for ${e} with socket name ${t}`;throw this.logger.warn({webviews:n.map(u=>({pkg:u.pkg,name:this.extractSocketNameFromWebview(u,this.logger)}))},l),new Error(l)}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){let l=`Webview ${e} with socket ${t} is not a valid webview`;this.logger.warn({pageUrl:a},l);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await ee().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 o1.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=qR(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 YR=5,XR=.8,i1=1,fu=class extends ki{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??XR,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer(e,t){let n=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:n.width,height:n.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,n)};let o=ee(),i=e.target.description;if(t){let c=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:c},"Got container bounds from native cache"),{bounds:c,cache:t}}let{resolvedTarget:a}=await this.findElement({description:i,tracer:o});if(a.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${i}" resolved to a webview element. Custom containers must be native elements.`);let s=this.getBoundsFromNativeCache(a);return this.logger.info({bounds:s},"Got container bounds from AI"),{bounds:s,cache:a}}async tryUseCachedScrollPosition(e,t){let n=e.cache?.target;return n?n.type==="WEBVIEW"?this.tryUseWebviewCache(e,t):n.scrollDetails?this.tryUseNativeScrollCache(e,t,n):null:null}async tryUseWebviewCache(e,t){let n=ee();try{let{thoughts:o}=await this.wrapTargetingAction({command:e,tracer:n,description:t,action:async i=>{if(i.type==="NATIVE")throw new Error("Expected WEBVIEW target but got NATIVE");await this.scrollWebviewTargetIntoView(i)}});return{success:!0,message:o}}catch(o){return this.logger.warn({err:o},"Failed to use webview cache, falling back to search"),null}}async tryUseNativeScrollCache(e,t,n){let o=n.scrollDetails,i=ee(),a=e.scrollStepPercent??XR,s=o.scrollableElement.type==="CUSTOM"?o.scrollableElement.cache:void 0;await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:o.direction,scrollStepPercent:a});try{let l=await this.tryFindElement({cmd:e,description:t,tracer:i,scrollDetails:o,useAIIfCacheFails:!1});if(l)return l;this.logger.info("Element not found at cached position, undoing scroll")}catch(l){this.logger.warn({err:l},"Error finding element at cached position, will undo scroll")}let c=o.direction==="down"?"up":"down";return this.logger.info({pixelDelta:o.pixelDelta,originalDirection:o.direction,undoDirection:c,scrollableElementType:o.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:c,scrollStepPercent:a}),null}async tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:o,useAIIfCacheFails:i=!0}){let a,s,c=e.cache?.target;if(c&&c.resolvedDescription===t&&!e.disableCache){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let u=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0});try{let{resolvedTarget:d}=await pu({target:c,domState:u,stateManager:this.stateManager,logger:this.logger});a=d,s="Successfully resolved scroll to target with cache.",this.logger.info("Successfully resolved scroll to target from cache")}catch(d){this.logger.warn({err:d},"Failed to resolve target from cache")}}if(!a&&!i)return null;if(!a)try{let u=await this.findElement({description:t,tracer:n});a=u.resolvedTarget,s=u.thoughts}catch(u){if(this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u instanceof yn)return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),Ni({command:e,updatedCache:mu(a),updatedWithAI:!0}),{success:!0,message:s}):(Ni({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=ee(),i=await this.resolveContainer(e.scrollableElement);return this.scrollAndSearch(e,t,o,n,i)}async scrollAndSearch(e,t,n,o,i){let a=0,s=i.bounds,c=s.height*o,l=!0;for(let u=0;u<YR;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),p=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(p)return p;if(!l)throw new Error(`ActionFailureError: Could not find element "${t}" after scrolling to the end`);this.logger.debug({attempt:u,cumulativePixelDelta:a},"Element not found, scrolling further");let g=a1(e.scrollableElement);l=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:g}),a+=e.direction==="down"?c:-c}throw new Error(`ActionFailureError: Could not find element "${t}" after ${YR} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollWebviewTargetIntoView(e){let{controller:t,resolution:n}=e;await t.browser.hover({locator:n.locator})}async scrollByPage({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o}){return ee().startAsyncSpan("EMULATOR_INTERACTION",async a=>(a.attributes.containerBounds=t,a.attributes.direction=e,this.executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o})),{name:`Scroll ${e} by one page`})}async scrollByPixelDelta({pixelDelta:e,scrollableElement:t,containerCache:n,direction:o,scrollStepPercent:i}){if(e===0)return;let a=ee(),s,c,l;if(t.type==="CUSTOM_COORDINATES")s=t.startX,c=t.startY,l=t.deltaPixels;else{let p=(await this.resolveContainer(t,n)).bounds,g=p.height*i,m=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:g});s=m.startX,c=m.startY,l=m.actualDelta}let u=Math.ceil(Math.abs(e)/l);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:s,startY:c,maxScrollPerStep:l,numScrolls:u},"scrollByPixelDelta calculated parameters"),await a.startAsyncSpan("EMULATOR_INTERACTION",async d=>{d.attributes.pixelDelta=e,d.attributes.numScrolls=u,d.attributes.maxScrollPerStep=l,d.attributes.startX=s,d.attributes.startY=c;let p=0;for(let g=0;g<u;g++){this.throwIfAborted();let m=Math.abs(e)-p,h=Math.min(l,m);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:this.invertDirection(o)}),p+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=i1,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,c,l;if(i)s=i.startX,c=i.startY,l=i.deltaPixels;else{let g=t.height*n,m=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:g});s=m.startX,c=m.startY,l=m.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=Fg(a,u),p=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:p,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),p}};function a1(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as s1}from"crypto";import ys from"fs";import{tmpdir as l1}from"os";import Ui from"path";var Su=class extends Xe{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 ${Ui.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(ys.existsSync(n))o=n;else if(ys.existsSync(Ui.join("/",n)))o=Ui.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{ys.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=Ui.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{ys.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=Ui.extname(t)||".apk",o=Ui.join(l1(),`momentic-apk-${s1()}${n}`);return ys.writeFileSync(o,e),o}};import{existsSync as c1,readFileSync as u1}from"fs";import d1 from"zod";var p1=d1.string().url();async function JR(r){if(p1.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(!c1(r))throw new Error(`File does not exist at path: ${r}`);return u1(r).toString("base64")}var yu=class extends Xe{async dragNative(e,t,n){let{left:o,top:i,width:a,height:s}=this.getBoundsFromNativeCache(e),{left:c,top:l,width:u,height:d}=this.getBoundsFromNativeCache(t),p=o+a/2,g=i+s/2,m=c+u/2,h=l+d/2,f=n?.hoverDuration??500,E=n?.dragDuration??1e3;await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:p,y:g},{type:"pointerDown",button:0},{type:"pause",duration:f},{type:"pointerMove",duration:E,x:m,y:h},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}async dragWebview(e,t,n){let{controller:o}=e;if(e.controller!==t.controller)throw new Error("ActionFailureError: Cannot drag and drop between different webviews");let i=n?.hoverDuration?n.hoverDuration/1e3:void 0,a;n?.dragDuration&&(a=Math.max(1,Math.floor(n.dragDuration/200))),await o.browser.dragAndDrop(e.resolution.locator,t.resolution.locator,{hoverSeconds:i,steps:a})}async executeDragAndDrop({command:e}){let t=ee();if(e.fromTarget.type!=="description"||e.toTarget.type!=="description")throw new Error("ActionFailureError: Drag and drop only supports description targets for now");let n=e.fromTarget.description,{result:o,thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,description:n,cacheKey:"cache",targetName:"fromTarget",action:async l=>l}),a=e.toTarget.description,{result:s,thoughts:c}=await this.wrapTargetingAction({command:e,tracer:t,description:a,cacheKey:"cache",targetName:"toTarget",action:async l=>l});if(o.type!==s.type)throw new Error(`ActionFailureError: Drag and drop targets must be in the same context (both native or both webview). Found: From=${o.type}, To=${s.type}`);return await t.startAsyncSpan("EMULATOR_INTERACTION",async l=>{o.type==="NATIVE"&&s.type==="NATIVE"?await this.dragNative(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}):o.type==="WEBVIEW"&&s.type==="WEBVIEW"&&(l.withinWebview=!0,await this.dragWebview(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}))},{name:"Drag and drop"}),{success:!0,message:`${i}
|
|
4348
4348
|
${c}`}}};import{cloneDeep as QR}from"lodash-es";var m1=5e3,g1={getTextContent:async r=>await r.textContent()??"",getAttribute:async(r,e)=>await r.getAttribute(e,{timeout:3e3})??"",getTagName:async r=>await r.evaluate(e=>e.tagName),isEditable:async r=>await r.isEditable({timeout:zt*1e3}),isEnabled:async r=>await r.isEnabled({timeout:zt*1e3}),isFocused:async r=>await r.evaluate(e=>e===document.activeElement),getStyleProperty:async(r,e)=>await r.evaluate((t,n)=>window.getComputedStyle(t).getPropertyValue(n),e)},ZR=r=>{let e=[],t=r.getAttribute("text")??"",n=r.getAttribute("hint")??"",o=r.getAttribute("showing-hint")==="true";t.trim()&&!o&&t.trim()!==n.trim()&&e.push(t.trim());for(let i of Array.from(r.childNodes??[]))if(i.nodeType===3){let a=i.nodeValue??"";a.trim()&&e.push(a.trim())}else if(i.nodeType===1){let a=ZR(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()},h1={getTextContent:async r=>ZR(r),getAttribute:async(r,e)=>r.getAttribute(e)??"",getTagName:async r=>r.tagName,isEditable:async r=>{throw new Error("Cannot perform editable check on native element")},isEnabled:async r=>r.getAttribute("enabled")==="true",isFocused:async r=>r.getAttribute("focused")==="true",getStyleProperty:async(r,e)=>{throw new Error("Cannot perform computed style checks on native element")}},bu=class extends Xe{async executeElementCheck(e){let t=Date.now(),n=(e.timeout??zt)*1e3,o=n+1e4,i,a=0,s=500,c=QR(e.cache);if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");for(;a-t<n;){if(Date.now()-t>o){this.logger.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),i=await this.executeElementCheckHelper(e),a=Date.now(),!i.success)e.cache=c,c=QR(c),await q(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),m1);else return i}let l=await this.executeElementCheckHelper(e,{cacheIsInvalidAfterResolution:!0});return l.success||c&&(e.cache=this.restoreCachePreserveMemory(c,e.cache)),l}restoreCachePreserveMemory(e,t){return t?.target?.memory&&e?.target?.memory&&e.target.memory!==t.target.memory?{...e,target:{...e.target,memory:t.target.memory},updatedAt:t.updatedAt}:e}async executeElementCheckHelper(e,t){let n=ee();if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");let o=Nc(e.assertion);try{return(await this.wrapTargetingAction({...t??{},command:e,tracer:n,action:async a=>"type"in a&&a.type==="NATIVE"?await this.executeNativeElementCheck(e,a):await this.executeWebviewElementCheck(e,a),description:e.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).result}catch(i){return o&&(i instanceof yn||i instanceof Sn)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=ee(),{assertion:o}=e,i=t.resolvedNode;return await n.startAsyncSection("Execute native element check",async(a,s)=>await this.executeElementAssertion({assertion:o,element:i,elementCallbacks:h1,trace:s}))}async executeWebviewElementCheck(e,t){let n=ee(),o=t.resolution.locator,i=e.assertion;return await n.startAsyncSection("Execute webview element check",async(a,s)=>(await t.controller.browser.highlight(o),await this.executeElementAssertion({assertion:i,element:o,elementCallbacks:g1,trace:s})))}async executeElementAssertion({assertion:e,element:t,elementCallbacks:n,trace:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=gt(i,500,!0),Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${dr(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{"evaluate"in t&&(o.attributes.elementOuterHtml=gt(await t.evaluate(a=>a.cloneNode(!1).outerHTML),500,!0));let i;try{i=await n.getAttribute(t,e.attr)}catch(a){return{success:!1,message:`The element does not have an attribute named ${e.attr}: ${a}`}}if(!Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=dr(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${dr(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${dr(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=dr(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};var f1=5e3,Eu=class extends Xe{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??zt)*1e3,i=o+1e4,a=0,s=500;for(;a-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let c=await this.executeScreenCheckHelper(e);if(a=Date.now(),!c.success)await q(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),f1);else return c}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await ee().startAsyncSection("Execute screen check",async(n,o)=>{let[i,a]=await Promise.all([this.executeNativeScreenCheckHelper({span:o,command:e}),this.executeWebviewScreenCheckHelper(e)]);return a?e.assertion.negated?i.success&&a.success?i:i.success?a:i:i.success?i:a:i})}async executeNativeScreenCheckHelper({span:e,command:t}){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let o=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!o)throw new Error("Failed to get screen HTML");let i=o.includes(n.value)===!n.negated;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),i?{success:!0}:(e.attributes.screenContent=o,{success:!1,message:`The screen ${Um(n)}.`})}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}async executeWebviewScreenCheckHelper(e){let t=await this.stateManager.getActiveWebview();if(!t||!t.browserController)return;let n=t.browserController.browser;return await lu({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var Tu=class extends Xe{async doUninstallApk(e){return await this.uninstallApkPackage(e.packageName),{success:!0,message:"Uninstalled APK."}}async uninstallApkPackage(e){let t=e.replace(/^package:/,""),n=await this.stateManager.executeRawADBCommand(`shell pm list packages | grep -E "^package:${t}$" || true`);if(n.length===0)throw new Error(`Package ${t} not found`);if(n.split(`
|
|
@@ -4384,7 +4384,7 @@ Momentic users value the following:
|
|
|
4384
4384
|
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return C.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function AH(r){let e=TH(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${zi}`)),n=AbortSignal.timeout(2e3),o;try{o=await hH(t,{absolute:!1,cwd:qg(),dotRelative:!1,maxDepth:$g,nodir:!0,signal:n})}catch(a){throw C.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${Kg} is misconfigured.`),a}let i=[];for(let a of o){let s=_o.join(qg(),a),c=Yg(s);c&&i.push({configFilePath:s,config:c,rootDir:wx(s)})}return i}async function wH(r){if(r){r=_o.resolve(r);let t=Yg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:_o.dirname(r)}]}if(dH(Kg)){let t=await AH(Kg);if(t)return t}return vH()}function xx(r,e){let t=Cx.stringify(r);gH(e,t)}import{z as Xg}from"zod";var Mx="test-results";var UDe=Xg.object({width:Xg.number(),height:Xg.number()});import{execFile as CH}from"node:child_process";import{promisify as RH}from"node:util";import xH from"simple-git";var Le=xH(),_x=RH(CH);async function MH(r){let e=await Ne(r,Le.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4385
4385
|
`)){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 _H(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 _x("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 _x("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function PH(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return _H(r,e,t);if(o)return}catch{}}function xu(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 Ne(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function IH(){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 OH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.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 LH(r){let[e,t,n]=await Promise.all([Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.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 NH(r){let[e,t,n,o]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??t,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?xu(i):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:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function DH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?xu(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 kH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?xu(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 UH(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Ne(r,Le.revparse(["HEAD"])),Ne(r,Le.revparse(["--short","HEAD"])),Ne(r,Le.revparse(["--abbrev-ref","HEAD"])),Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"])),e?Ne(r,Le.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),MH(r)]),d=l?await Ne(r,Le.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?xu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await PH(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?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function FH(){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 BH(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function vs(r,e){let t=IH();if(!t)return UH(r,e);switch(t){case"GithubActions":return OH(r);case"GitlabCI":return LH(r);case"CircleCI":return NH(r);case"Buildkite":return DH(r);case"AzureDevOps":return kH(r);case"GCPCloudBuild":return FH()}}async function zH(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 HH(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 GH(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await HH(r,e,n,o,t)}else if(t.gitlabProjectPath)return await zH(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Hi(r,e,t){let n=await BH(t),o=await vs(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 GH(r,e,i);return{...n,...o,...a}}import{diff as Px}from"deep-object-diff";import Vn from"fs";import{cloneDeep as VH}from"lodash-es";import Mu from"path";import{v4 as WH}from"uuid";import As from"yaml";function Ix({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Vn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Vn.readFileSync(i,"utf-8"),s=As.parse(a),c={...s,...r,schemaVersion:e},l=bo({fileType:Oe.MOBILE_MODULE,...Ca.parse(c),steps:ir.array().parse(r.steps)}),u=Px(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=As.stringify(l);Vn.writeFileSync(i,d,"utf-8"),Gn(i,n.config)}function Ox({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=ws(i,o),s={...a,...e},c=bo({fileType:Oe.MOBILE_MODULE,...yl.parse(s)}),l=Px(c,a);if(l&&Object.keys(l).length===0)return;let u=As.stringify(c);Vn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${Xr(e.name)}.module.yaml`;if(d=Mu.join(Mu.dirname(i),p),Vn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Vn.renameSync(i,d)}Gn(d||i,n.config)}async function Lx({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Xr(r),s=Mu.join(o,`${a}.module.yaml`),c=WH(),{stepsToSave:l}=await Nn({steps:n}),u={schemaVersion:bn,moduleId:c,description:e,enabled:t},d={fileType:Oe.MOBILE_MODULE,...u,steps:l},p=As.stringify(Fy.parse(d));return Vn.writeFileSync(s,p,"utf-8"),Gn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function ws(r,e){let t=Vn.readFileSync(r,"utf-8"),n=As.parse(t);try{return{...yl.parse(n),name:Mu.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 Jg(r,e,t,n){let o=ws(r.fullFilePath,t),{resolvedSteps:i}=await Fc({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 ws(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]=VH(a)),a}async function Nx(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Jg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as jH}from"crypto";import Po from"fs";import Zg from"path";import _u from"yaml";import Qg from"zod";function Dx({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Xr(r)}.test.yaml`,s=Zg.join(o,a);if(Po.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:Oe.MOBILE_TEST,id:jH(),description:e,schemaVersion:Zn,settings:n,steps:t},l=_u.stringify(c);return Po.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function $H(r){if(!Po.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=Po.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4386
4386
|
`),t=_u.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function Pu(r,e,t){let n=$H(r),o;try{o=Er.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await xw({rawStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return ws(c,e)}});return{...o,steps:i.steps}}async function kx({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i,schemaVersion:a}){let s=Zg.isAbsolute(r)?r:Zg.join(n,r);if(!Po.existsSync(s))throw new Error(`Test file not found: ${s}`);let c=Po.readFileSync(s,"utf-8").replace(/\r\n|\r/g,`
|
|
4387
|
-
`),l=_u.parse(c),u=ip.extend({steps:Qg.record(Qg.string(),Qg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Oe.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Nn({steps:e}));let p={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=_u.stringify(p);for(let m of d?.moduleUpdates??[])Ix({content:m,schemaVersion:Zn,momenticFiles:i,project:o});Po.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as qH}from"crypto";import Wn from"fs";import Gi from"path";var Ux=new Set([".DS_Store","__MACOSX"]),Fx={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 KH(r,e,t){if(Fx[t]){let i=Fx[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 eh=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 Bx(r,e){try{let t=Gi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new eh(r,e)}}function zx(r,e,t){let n=qH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ux.has(c)).map(c=>Gi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Wn.mkdirSync(e,{recursive:!0});let a={...Bx(t,i[0]),id:n};for(let c of i){let l=Gi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Bx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let g=p;a[g]=KH(a,u,g)}let d=Wn.readdirSync(l);for(let p of d){if(Ux.has(p))continue;let g=Gi.join(l,p),m=Gi.join(e,"runs",p);Wn.cpSync(g,m,{recursive:!0})}}let s=Gi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Gx from"adm-zip";import ah from"fs";import{z as rG}from"zod";var U="v1",th="mobile-cli",Io="0.9.4";var YH=9e4,XH=3,JH=1500,QH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function ZH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var rh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Io&&(e[Ml]=Io),th&&(e[db]=th),e}async sendRequest(e,t){let{retries:n=XH,requestTimeoutMs:o=YH,initialRetryDelayMs:i=JH,maxRetryDelayMs:a=QH,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 Cr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new xn),c===0)throw u;let g=l-c,m=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,m))}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 ZH(u);throw new Cr(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)}}},$r=class extends rh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[ub]:this.mode??""}}};import{createAnthropic as eG}from"@ai-sdk/anthropic";function tG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ml]:Io??"",...t&&{[mb]:t},...n||{}};return o&&(i[pb]=JSON.stringify(o)),i}var Iu=r=>e=>{let t=tG(r);return eG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Oo=class extends $r{agentConfig;constructor(e,t){let n={...cy,...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 XS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Io,...e},signal:t.abortSignal});return YS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return rG.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 Sb.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 yp.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 fb.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 hb.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 yp.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 gb.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 xd.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 yb.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 Cd.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 MS.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 _S.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 dd.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ly.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 AS.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 RS.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 CS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Fh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Iu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as nh}from"zod";var Rr=class extends $r{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=>{C.warn(`API key check failed: ${t.message}`)}});return Ib.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return xb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Eb.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 vb.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 Ab.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return bb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Pb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ob.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 qb.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 Lb.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 jS.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 Nb.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 Db.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return kb.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 Ub.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Xb.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 La.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 La.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 vp.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 La.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 La.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 vp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return nh.record(nh.string(),nh.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Fb.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 Bb.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 zb.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 Hb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function oh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var Ou=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Vi=class extends $r{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 Bh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Wi=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 nG,en as oG}from"@faker-js/faker";var ji="v1",$i=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 nG({locale:oG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ji}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Cr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function Hx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Lu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await Hx(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 qi=class extends $r{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 dy.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 gy.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Iu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Nu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new ih(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var ih=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=bp(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;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.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}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&&Fm({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Nn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Du from"path";function iG(r){let e=new Gx,t=Du.join(r,"metadata.json"),n=Il.parse(JSON.parse(ah.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of ah.readdirSync(Du.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Gx(Du.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Du.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function ku(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!ah.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Lu(e);try{let{runGroupId:i,buffer:a}=iG(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 aG from"adm-zip";import Tt from"fs";import qt from"path";var Cs=class r{constructor(e){this.filePath=e;Tt.rmSync(this.filePath,{recursive:!0,force:!0}),Tt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(qt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Tt.mkdirSync(qt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=qt.join(this.filePath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.filePath,t);try{Tt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=qt.join(this.filePath,e);return Tt.createWriteStream(t)}createRunArchive(e){return new sh(qt.join(this.filePath,"runs"),e)}},sh=class{constructor(e,t){this.filePath=e;this.tempPath=qt.join(e,`.${t}`),this.finalPath=qt.join(e,`${t}.zip`),Tt.rmSync(this.tempPath,{recursive:!0,force:!0}),Tt.rmSync(this.finalPath,{recursive:!0,force:!0}),Tt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=qt.join(this.tempPath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}mkdir(e){Tt.mkdirSync(qt.join(this.tempPath,e),{recursive:!0})}cd(e){return new Cs(qt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.tempPath,t);Tt.writeFileSync(o,n)}createFileStream(e){let t=qt.join(this.tempPath,e);return Tt.createWriteStream(t)}close(){let e=new aG;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Tt.writeFileSync(this.finalPath,t),Tt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import ju from"fs";import oM from"body-parser";import xG from"cors";import MG from"dedent";import{Router as uG}from"express";import Ft from"fs";import{globSync as dG}from"glob";import ht from"path";import Uu from"fs";import sG from"path";var lG=new $c(30,60*1e3),dh="https://api.momentic.ai",ch,Wx=r=>{dh=r},ph=()=>dh,Rs=()=>ch;var Ki,uh,Vx,jx=async r=>{if(ch&&Ki&&Vx)return Ki;let e=new Rr({baseUrl:dh,apiKey:r,logger:C});ch=e;try{let t=await e.getAuthInfo();return Ki=t.orgId,uh=t.userId,Vx=r,Ki}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Yi=()=>{if(!Ki)throw new Error("Your organization ID is invalid.");return Ki},Fu=()=>{if(!uh)throw new Error("Your user ID is invalid.");return uh};var mh,lh,$x=(r,e)=>{mh=r,lh?.abort(),lh=new AbortController;let t=lh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=sG.resolve(r.rootDir,o.envFile);try{if(Uu.lstatSync(i).isSymbolicLink())return;Uu.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{cG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>mh;function cG({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(lG.increment("setLocalProject")&&C.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.`),mh=await Promise.resolve(e(n.configFilePath)))};Uu.watchFile(o,{persistent:!1},i);let a=()=>{Uu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ms=uG();function xs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function pG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function mG(r,e){let t=Ft.statSync(r),n=pG(r);return pp.parse({name:e,absolutePath:r,relativePath:n.join(ht.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ms.post("/",$e(async(r,e,t)=>{let n;try{n=Xy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=xs(n);if(!Ft.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ht.sep)}`});return}if(!Ft.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Al),l=dG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ht.join(o,d);return mG(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Ms.put("/",$e(async(r,e,t)=>{let n;try{n=Jy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=xs(n);if(Ft.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ht.sep)}`,pathSegments:n});return}Ft.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ht.sep)}`,pathSegments:n};e.status(201).json(i)}));Ms.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Qy.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=xs(n),a=xs(o);if(!Ft.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ht.sep)}`});return}if(Ft.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ht.sep)}`});return}let s=ht.dirname(a);Ft.existsSync(s)||Ft.mkdirSync(s,{recursive:!0}),Ft.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ht.sep)} to ${o.join(ht.sep)}`,pathSegments:o};e.status(200).json(c)}));Ms.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Zy.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=xs(n);if(!Ft.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ht.sep)}`,pathSegments:n});return}if(!Ft.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}if(o)Ft.rmSync(i,{recursive:!0,force:!0});else{if(Ft.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ft.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var gh=Ms;import{Router as fG}from"express";import{hostname as gG}from"os";var hG="0.9.4",_s=ui({app:"desktop-server",hostname:gG(),disableConsoleLogs:!0}).child({cliVersion:hG});(async()=>{try{let r=await vs(_s);r.gitBranchName&&_s.addBinding("branch",r.gitBranchName)}catch{}})();var qx=fG();qx.get("/",async(r,e)=>{let t=Ve(),n=Rs();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Hi(_s,n,t);e.status(200).json(o)});var hh=qx;import _G from"events";import iM,{Router as PG}from"express";import IG from"http";import OG from"path";var Bu=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 Kx=new Bu;import{Router as yG}from"express";import{existsSync as bG}from"fs";import EG from"path";import{hostname as SG}from"os";var fh="0.9.4",vt=ui({app:"mobile-desktop-server",hostname:SG(),disableConsoleLogs:!0}).child({cliVersion:fh});(async()=>{try{let r=await vs(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var Sh=yG();Sh.get("/",$e(async(r,e)=>{let t=Rs();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Sh.post("/upload-url",$e(async(r,e)=>{let t;try{t=ib.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Rs();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=EG.resolve(t.filePath);if(!bG(o)){e.status(400).json({error:`File not found: ${o}`});return}await Pc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vt}),e.sendStatus(204)}));var Yx=Sh;import{Router as AG}from"express";import{Router as TG}from"express";import Xx from"fs";import vG from"path";var Ps=TG();async function yh(r){return(await Nx(r,vt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.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)}Ps.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await yh(n);e.status(200).json(o)}));Ps.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Jg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ps.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ab.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);Ox({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ps.post("/",$e(async(r,e)=>{let t;try{t=sb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{pa(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await hr(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=vG.join(n.rootDir,t.folderPath??"");if(!Xx.existsSync(a)||!Xx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Lx({...t,folder:a,project:n});e.status(201).json(s)}));var Jx=Ps;var Qx=AG();Qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await yh(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 Zx=Qx;import{Router as wG}from"express";var bh=wG();bh.get("/",$e((r,e)=>{let t=Tx(Ve(),vt);e.status(200).json(t)}));bh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var eM=bh;import{Router as CG}from"express";var tM=CG();tM.get("/",(r,e)=>{e.status(200).json({userId:Fu(),orgId:Yi(),cliVersion:fh??"0.0.0"})});var rM=tM;import{Router as RG}from"express";import Eh from"path";var zu=RG();zu.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ob.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=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await hr(o);await kx({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:Zn});let s={message:"ok"};e.status(200).json(s)}));zu.post("/",$e((r,e)=>{let t;try{t=nb.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});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{pa(n)}catch(m){e.status(400).json({error:m.message});return}let s=Ve(),c=Eh.join(s.rootDir,...a),{fullPath:l,testId:u}=Dx({name:n,description:o,steps:[],settings:i,folder:c}),d=Eh.basename(l),p=Eh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));zu.get("/:fileName",$e(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=Ve(),i=await hr(o),s=await Pu(n,vt,i);e.status(200).json(s)}));var nM=zu;var Hu=class extends Wi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return bs(t,o,C)}};var aM="10mb";async function sM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Wx(n),await jx(t);let u=Yi(),d=Fu(),p=r.logger.child({orgId:u,userId:d});$x(i,A=>Ts({configFilePath:A}));let g=iM();g.use(xG()),g.use(oM.json({limit:aM})),g.use(oM.urlencoded({extended:!1,limit:aM}));let m=PG();if(m.use("/folders",gh),m.use("/entities",Zx),m.use("/identify",rM),m.use("/mobile-tests",nM),m.use("/mobile-modules",Jx),m.use("/assets",Yx),m.use("/git",hh),m.use("/environments",eM),g.use("/api",m),g.use((A,N,G)=>{C.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:A.url,method:A.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:A.url,method:A.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((A,N,G,W)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:A.stack,msg:A.message,err:A,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:A.stack,msg:A.message,err:A,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=iM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(A),g.use("*",(N,G)=>{G.sendFile(OG.join(o,"index.html"))})}let h=IG.createServer(g),f=`http://localhost:${e}`;await new Promise(A=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),A()})}catch(N){N.message.includes("EADDRINUSE")?LG(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:ph(),apiKey:t,logger:p},x=new Rr(b),w=Ve(),T={...b,mode:"interactive"},{dispose:_}=bx({baseServer:h,logger:p,authorization:b,globalStateManager:Kx,getOrgId:()=>Yi(),androidDriverFactory:async({socket:A,logger:N,creationOpts:G})=>{let W=Math.floor(Math.random()*1e4)+4e4,ye=await Dl(W,"appium");return _c({logger:N,driverLogLevel:a,apiClient:x,creationOpts:G,socket:A,appiumPort:ye,sessionId:A.id,orgId:Yi(),onStatusUpdate:Se=>{A.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async A=>new qi({baseUrl:ph(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async A=>new Oo(w.config.ai?.agentConfig,T),browserEnricherFactory:async A=>new Vi(T,new Oo(w.config.ai?.agentConfig,T)),storageFactory:async A=>new Hu(x,A),cacheStorageFactory:async A=>{let N=await Hi(p,x,w);return Nu({orgId:A,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new $i({httpClient:x,fakerSeed:void 0}),keepSessionAlive:A=>x.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:w.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(A){C.error({err:A},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{C.info("SIGTERM in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}})}_G.setMaxListeners(25);process.on("warning",r=>{vt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vt.error({err:r},"Uncaught exception on mobile-desktop-server"),C.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),C.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function LG(r){C.error(MG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4387
|
+
`),l=_u.parse(c),u=ip.extend({steps:Qg.record(Qg.string(),Qg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Oe.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Nn({steps:e}));let p={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=_u.stringify(p);for(let m of d?.moduleUpdates??[])Ix({content:m,schemaVersion:Zn,momenticFiles:i,project:o});Po.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as qH}from"crypto";import Wn from"fs";import Gi from"path";var Ux=new Set([".DS_Store","__MACOSX"]),Fx={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 KH(r,e,t){if(Fx[t]){let i=Fx[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 eh=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 Bx(r,e){try{let t=Gi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new eh(r,e)}}function zx(r,e,t){let n=qH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ux.has(c)).map(c=>Gi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Wn.mkdirSync(e,{recursive:!0});let a={...Bx(t,i[0]),id:n};for(let c of i){let l=Gi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Bx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let g=p;a[g]=KH(a,u,g)}let d=Wn.readdirSync(l);for(let p of d){if(Ux.has(p))continue;let g=Gi.join(l,p),m=Gi.join(e,"runs",p);Wn.cpSync(g,m,{recursive:!0})}}let s=Gi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Gx from"adm-zip";import ah from"fs";import{z as rG}from"zod";var U="v1",th="mobile-cli",Io="0.9.5";var YH=9e4,XH=3,JH=1500,QH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function ZH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var rh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Io&&(e[Ml]=Io),th&&(e[db]=th),e}async sendRequest(e,t){let{retries:n=XH,requestTimeoutMs:o=YH,initialRetryDelayMs:i=JH,maxRetryDelayMs:a=QH,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 Cr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new xn),c===0)throw u;let g=l-c,m=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,m))}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 ZH(u);throw new Cr(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)}}},$r=class extends rh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[ub]:this.mode??""}}};import{createAnthropic as eG}from"@ai-sdk/anthropic";function tG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ml]:Io??"",...t&&{[mb]:t},...n||{}};return o&&(i[pb]=JSON.stringify(o)),i}var Iu=r=>e=>{let t=tG(r);return eG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Oo=class extends $r{agentConfig;constructor(e,t){let n={...cy,...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 XS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Io,...e},signal:t.abortSignal});return YS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return rG.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 Sb.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 yp.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 fb.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 hb.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 yp.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 gb.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 xd.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 yb.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 Cd.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 MS.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 _S.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 dd.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ly.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 AS.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 RS.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 CS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Fh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Iu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as nh}from"zod";var Rr=class extends $r{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=>{C.warn(`API key check failed: ${t.message}`)}});return Ib.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return xb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Eb.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 vb.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 Ab.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return bb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Pb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ob.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 qb.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 Lb.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 jS.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 Nb.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 Db.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return kb.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 Ub.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Xb.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 La.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 La.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 vp.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 La.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 La.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 vp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return nh.record(nh.string(),nh.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Fb.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 Bb.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 zb.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 Hb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function oh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var Ou=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Vi=class extends $r{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 Bh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Wi=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 nG,en as oG}from"@faker-js/faker";var ji="v1",$i=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 nG({locale:oG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ji}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Cr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function Hx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Lu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await Hx(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 qi=class extends $r{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 dy.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 gy.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Iu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Nu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new ih(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var ih=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=bp(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;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.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}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&&Fm({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Nn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Du from"path";function iG(r){let e=new Gx,t=Du.join(r,"metadata.json"),n=Il.parse(JSON.parse(ah.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of ah.readdirSync(Du.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Gx(Du.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Du.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function ku(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!ah.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Lu(e);try{let{runGroupId:i,buffer:a}=iG(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 aG from"adm-zip";import Tt from"fs";import qt from"path";var Cs=class r{constructor(e){this.filePath=e;Tt.rmSync(this.filePath,{recursive:!0,force:!0}),Tt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(qt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Tt.mkdirSync(qt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=qt.join(this.filePath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.filePath,t);try{Tt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=qt.join(this.filePath,e);return Tt.createWriteStream(t)}createRunArchive(e){return new sh(qt.join(this.filePath,"runs"),e)}},sh=class{constructor(e,t){this.filePath=e;this.tempPath=qt.join(e,`.${t}`),this.finalPath=qt.join(e,`${t}.zip`),Tt.rmSync(this.tempPath,{recursive:!0,force:!0}),Tt.rmSync(this.finalPath,{recursive:!0,force:!0}),Tt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=qt.join(this.tempPath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}mkdir(e){Tt.mkdirSync(qt.join(this.tempPath,e),{recursive:!0})}cd(e){return new Cs(qt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.tempPath,t);Tt.writeFileSync(o,n)}createFileStream(e){let t=qt.join(this.tempPath,e);return Tt.createWriteStream(t)}close(){let e=new aG;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Tt.writeFileSync(this.finalPath,t),Tt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import ju from"fs";import oM from"body-parser";import xG from"cors";import MG from"dedent";import{Router as uG}from"express";import Ft from"fs";import{globSync as dG}from"glob";import ht from"path";import Uu from"fs";import sG from"path";var lG=new $c(30,60*1e3),dh="https://api.momentic.ai",ch,Wx=r=>{dh=r},ph=()=>dh,Rs=()=>ch;var Ki,uh,Vx,jx=async r=>{if(ch&&Ki&&Vx)return Ki;let e=new Rr({baseUrl:dh,apiKey:r,logger:C});ch=e;try{let t=await e.getAuthInfo();return Ki=t.orgId,uh=t.userId,Vx=r,Ki}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Yi=()=>{if(!Ki)throw new Error("Your organization ID is invalid.");return Ki},Fu=()=>{if(!uh)throw new Error("Your user ID is invalid.");return uh};var mh,lh,$x=(r,e)=>{mh=r,lh?.abort(),lh=new AbortController;let t=lh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=sG.resolve(r.rootDir,o.envFile);try{if(Uu.lstatSync(i).isSymbolicLink())return;Uu.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{cG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>mh;function cG({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(lG.increment("setLocalProject")&&C.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.`),mh=await Promise.resolve(e(n.configFilePath)))};Uu.watchFile(o,{persistent:!1},i);let a=()=>{Uu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ms=uG();function xs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function pG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function mG(r,e){let t=Ft.statSync(r),n=pG(r);return pp.parse({name:e,absolutePath:r,relativePath:n.join(ht.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ms.post("/",$e(async(r,e,t)=>{let n;try{n=Xy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=xs(n);if(!Ft.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ht.sep)}`});return}if(!Ft.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Al),l=dG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ht.join(o,d);return mG(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Ms.put("/",$e(async(r,e,t)=>{let n;try{n=Jy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=xs(n);if(Ft.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ht.sep)}`,pathSegments:n});return}Ft.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ht.sep)}`,pathSegments:n};e.status(201).json(i)}));Ms.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Qy.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=xs(n),a=xs(o);if(!Ft.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ht.sep)}`});return}if(Ft.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ht.sep)}`});return}let s=ht.dirname(a);Ft.existsSync(s)||Ft.mkdirSync(s,{recursive:!0}),Ft.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ht.sep)} to ${o.join(ht.sep)}`,pathSegments:o};e.status(200).json(c)}));Ms.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Zy.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=xs(n);if(!Ft.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ht.sep)}`,pathSegments:n});return}if(!Ft.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}if(o)Ft.rmSync(i,{recursive:!0,force:!0});else{if(Ft.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ft.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var gh=Ms;import{Router as fG}from"express";import{hostname as gG}from"os";var hG="0.9.5",_s=ui({app:"desktop-server",hostname:gG(),disableConsoleLogs:!0}).child({cliVersion:hG});(async()=>{try{let r=await vs(_s);r.gitBranchName&&_s.addBinding("branch",r.gitBranchName)}catch{}})();var qx=fG();qx.get("/",async(r,e)=>{let t=Ve(),n=Rs();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Hi(_s,n,t);e.status(200).json(o)});var hh=qx;import _G from"events";import iM,{Router as PG}from"express";import IG from"http";import OG from"path";var Bu=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 Kx=new Bu;import{Router as yG}from"express";import{existsSync as bG}from"fs";import EG from"path";import{hostname as SG}from"os";var fh="0.9.5",vt=ui({app:"mobile-desktop-server",hostname:SG(),disableConsoleLogs:!0}).child({cliVersion:fh});(async()=>{try{let r=await vs(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var Sh=yG();Sh.get("/",$e(async(r,e)=>{let t=Rs();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Sh.post("/upload-url",$e(async(r,e)=>{let t;try{t=ib.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Rs();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=EG.resolve(t.filePath);if(!bG(o)){e.status(400).json({error:`File not found: ${o}`});return}await Pc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vt}),e.sendStatus(204)}));var Yx=Sh;import{Router as AG}from"express";import{Router as TG}from"express";import Xx from"fs";import vG from"path";var Ps=TG();async function yh(r){return(await Nx(r,vt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.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)}Ps.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await yh(n);e.status(200).json(o)}));Ps.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Jg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ps.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ab.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);Ox({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ps.post("/",$e(async(r,e)=>{let t;try{t=sb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{pa(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await hr(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=vG.join(n.rootDir,t.folderPath??"");if(!Xx.existsSync(a)||!Xx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Lx({...t,folder:a,project:n});e.status(201).json(s)}));var Jx=Ps;var Qx=AG();Qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await yh(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 Zx=Qx;import{Router as wG}from"express";var bh=wG();bh.get("/",$e((r,e)=>{let t=Tx(Ve(),vt);e.status(200).json(t)}));bh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var eM=bh;import{Router as CG}from"express";var tM=CG();tM.get("/",(r,e)=>{e.status(200).json({userId:Fu(),orgId:Yi(),cliVersion:fh??"0.0.0"})});var rM=tM;import{Router as RG}from"express";import Eh from"path";var zu=RG();zu.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ob.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=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await hr(o);await kx({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:Zn});let s={message:"ok"};e.status(200).json(s)}));zu.post("/",$e((r,e)=>{let t;try{t=nb.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});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{pa(n)}catch(m){e.status(400).json({error:m.message});return}let s=Ve(),c=Eh.join(s.rootDir,...a),{fullPath:l,testId:u}=Dx({name:n,description:o,steps:[],settings:i,folder:c}),d=Eh.basename(l),p=Eh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));zu.get("/:fileName",$e(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=Ve(),i=await hr(o),s=await Pu(n,vt,i);e.status(200).json(s)}));var nM=zu;var Hu=class extends Wi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return bs(t,o,C)}};var aM="10mb";async function sM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Wx(n),await jx(t);let u=Yi(),d=Fu(),p=r.logger.child({orgId:u,userId:d});$x(i,A=>Ts({configFilePath:A}));let g=iM();g.use(xG()),g.use(oM.json({limit:aM})),g.use(oM.urlencoded({extended:!1,limit:aM}));let m=PG();if(m.use("/folders",gh),m.use("/entities",Zx),m.use("/identify",rM),m.use("/mobile-tests",nM),m.use("/mobile-modules",Jx),m.use("/assets",Yx),m.use("/git",hh),m.use("/environments",eM),g.use("/api",m),g.use((A,N,G)=>{C.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:A.url,method:A.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:A.url,method:A.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((A,N,G,W)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:A.stack,msg:A.message,err:A,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:A.stack,msg:A.message,err:A,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=iM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(A),g.use("*",(N,G)=>{G.sendFile(OG.join(o,"index.html"))})}let h=IG.createServer(g),f=`http://localhost:${e}`;await new Promise(A=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),A()})}catch(N){N.message.includes("EADDRINUSE")?LG(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:ph(),apiKey:t,logger:p},x=new Rr(b),w=Ve(),T={...b,mode:"interactive"},{dispose:_}=bx({baseServer:h,logger:p,authorization:b,globalStateManager:Kx,getOrgId:()=>Yi(),androidDriverFactory:async({socket:A,logger:N,creationOpts:G})=>{let W=Math.floor(Math.random()*1e4)+4e4,ye=await Dl(W,"appium");return _c({logger:N,driverLogLevel:a,apiClient:x,creationOpts:G,socket:A,appiumPort:ye,sessionId:A.id,orgId:Yi(),onStatusUpdate:Se=>{A.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async A=>new qi({baseUrl:ph(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async A=>new Oo(w.config.ai?.agentConfig,T),browserEnricherFactory:async A=>new Vi(T,new Oo(w.config.ai?.agentConfig,T)),storageFactory:async A=>new Hu(x,A),cacheStorageFactory:async A=>{let N=await Hi(p,x,w);return Nu({orgId:A,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new $i({httpClient:x,fakerSeed:void 0}),keepSessionAlive:A=>x.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:w.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(A){C.error({err:A},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{C.info("SIGTERM in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}})}_G.setMaxListeners(25);process.on("warning",r=>{vt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vt.error({err:r},"Uncaught exception on mobile-desktop-server"),C.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),C.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function LG(r){C.error(MG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4388
4388
|
Using Bash on MacOS or Linux:
|
|
4389
4389
|
lsof -t -i :58888 | xargs kill -9
|
|
4390
4390
|
|
|
@@ -4393,7 +4393,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
|
|
|
4393
4393
|
`)}import QG from"open";import $u from"path";import{fileURLToPath as ZG}from"url";import{InvalidArgumentError as Th,Option as ut}from"@commander-js/extra-typings";import{z as NG}from"zod";var lM=58890;function cM(r){let e=parseInt(r,10);if(isNaN(e))throw new Th("Not a number.");return e}var Is=new ut("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Th("API key is required.");return r}).makeOptionMandatory(),vh=new ut("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Os=new ut("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return NG.string().url().parse(r),r}catch{throw new Th("Not a valid URL.")}}),Ah=new ut("-y, --yes","Skip all confirmation prompts.").env("CI"),wh=new ut("--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}),Ch=new ut("--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}),Rh=new ut("--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}),xh=new ut("--tag <tag>","Tag identifier for the asset."),uM=new ut("--channel <channel>","Channel name for the asset."),dM=new ut("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),pM=new ut("--env <env>","Environment to run all tests in (overrides test-level configuration)."),mM=new ut("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),gM=new ut("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),hM=new ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(cM),Mh=new ut("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),fM=new ut("--upload-results","Upload test results to Momentic Cloud.").default(!1),_h=new ut("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),SM=new ut("--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}),yM=new ut("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(cM);import{randomUUID as $G}from"crypto";import{existsSync as qG}from"fs";import Ph from"fs";import Gu from"path";import{cwd as kG}from"process";async function bM({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=>Ph.existsSync(p)),d=kG();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:
|
|
4394
4394
|
- ${r.join(`
|
|
4395
4395
|
- `)}
|
|
4396
|
-
`),r.forEach(p=>{if(!Ph.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=Ph.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Gu.resolve(p);Object.values(e.mobileTests).filter(f=>m?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(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await Ol("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=Gu.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=Gu.relative(t.rootDir,u),p=await Pu(u,a,e),g=Gu.basename(u,".test.yaml");return{id:p.id,name:g,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 UG}from"crypto";import{existsSync as FG,statSync as BG}from"fs";import{cloneDeep as zG}from"lodash-es";import HG from"path";async function EM(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:zG(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(p.loggerBindings||{}),m=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<m;h++){let f=new Date,E=await GG({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:m},fixtures:{...t,logger:g},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!==m-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 GG(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:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:w,alwaysSaveCache:T,noCache:_,logLevel:A,localAvdId:N,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let W={...a.project.config.emulator,...t.settings?.emulator},ye=G?HG.resolve(G):void 0;if(ye&&(!FG(ye)||!BG(ye).isFile()))throw new Error(`Local APK path "${ye}" does not exist. Provide a valid file path via --local-apk-path.`);let Se=Nu({orgId:u,client:p,gitMetadata:d,regenerateCache:w??!1,alwaysSaveCache:T??!1,noCache:_??!1}),Ae=new Wi(p,u),K={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g,mode:"runner"},j=new qi(K),le=new Oo(b.config.ai?.agentConfig,K),Q=new Vi(K,le),Je=new $i({httpClient:p,fakerSeed:void 0}),De=Math.floor(Math.random()*1e4)+4e4,Bt=await Dl(De,"appium"),Wt=W.region==="local"?ye??t.settings?.defaultApkFilePath?.trim():void 0,ke=f&&!Wt?{channel:f,tag:E}:void 0,Ie;if(N||W.region==="local"){if(!W.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.");Ie={avdId:N??W.localEmulatorSettings?.avdId,apkToInstall:ke,apkFilePath:Wt}}else Ie={region:W.region,apkToInstall:ke,osVersion:W.remoteEmulatorSettings?.androidVersion??Ny};let _t=UG(),dt=await _c({apiClient:p,logger:g,driverLogLevel:A,creationOpts:Ie,onStatusUpdate:Ns=>{g.debug({status:Ns},"Limbar emulator status update")},appiumPort:Bt,orgId:u,sessionId:_t}),qr=await e.startAttempt({emulatorName:dt.emulatorName,runAttemptId:_t}),Lo=g.child(qr.loggerBindings||{}),qu=await Ic({driver:dt.driver,onLogs:Ns=>{qr.appendLogs(Ns)}}),un=x||t.settings?.defaultEnv,kh;un&&(kh=bs(un,b,Lo).variables);let wM=new oi({variablesFromEnvironment:kh??{},envName:un,testName:t.name}),Uh=await Fi.init({driver:dt.driver,generator:j,logger:Lo,limbarClient:dt.limbarClient,playwrightDevice:dt.playwrightDevice,orgId:u,adbPort:dt.adbPort,options:{emulator:W},fixtures:{storage:Ae,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Je,testContext:wM}}),$;try{$=await Cu({containerName:`mobile test ${t.name}`,fixtures:{controller:Uh,logger:Lo,cacheStorage:Se,usageTracker:m},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:qr,callbacks:{}})}finally{await qu(),await dt.cleanup(),await Uh.cleanup()}return await qr.finish({logger:Lo,results:$.results,status:$.status}),$}import{debounce as VG}from"ts-debounce";var Ls="0.9.
|
|
4396
|
+
`),r.forEach(p=>{if(!Ph.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=Ph.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Gu.resolve(p);Object.values(e.mobileTests).filter(f=>m?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(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await Ol("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=Gu.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=Gu.relative(t.rootDir,u),p=await Pu(u,a,e),g=Gu.basename(u,".test.yaml");return{id:p.id,name:g,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 UG}from"crypto";import{existsSync as FG,statSync as BG}from"fs";import{cloneDeep as zG}from"lodash-es";import HG from"path";async function EM(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:zG(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(p.loggerBindings||{}),m=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<m;h++){let f=new Date,E=await GG({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:m},fixtures:{...t,logger:g},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!==m-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 GG(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:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:w,alwaysSaveCache:T,noCache:_,logLevel:A,localAvdId:N,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let W={...a.project.config.emulator,...t.settings?.emulator},ye=G?HG.resolve(G):void 0;if(ye&&(!FG(ye)||!BG(ye).isFile()))throw new Error(`Local APK path "${ye}" does not exist. Provide a valid file path via --local-apk-path.`);let Se=Nu({orgId:u,client:p,gitMetadata:d,regenerateCache:w??!1,alwaysSaveCache:T??!1,noCache:_??!1}),Ae=new Wi(p,u),K={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g,mode:"runner"},j=new qi(K),le=new Oo(b.config.ai?.agentConfig,K),Q=new Vi(K,le),Je=new $i({httpClient:p,fakerSeed:void 0}),De=Math.floor(Math.random()*1e4)+4e4,Bt=await Dl(De,"appium"),Wt=W.region==="local"?ye??t.settings?.defaultApkFilePath?.trim():void 0,ke=f&&!Wt?{channel:f,tag:E}:void 0,Ie;if(N||W.region==="local"){if(!W.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.");Ie={avdId:N??W.localEmulatorSettings?.avdId,apkToInstall:ke,apkFilePath:Wt}}else Ie={region:W.region,apkToInstall:ke,osVersion:W.remoteEmulatorSettings?.androidVersion??Ny};let _t=UG(),dt=await _c({apiClient:p,logger:g,driverLogLevel:A,creationOpts:Ie,onStatusUpdate:Ns=>{g.debug({status:Ns},"Limbar emulator status update")},appiumPort:Bt,orgId:u,sessionId:_t}),qr=await e.startAttempt({emulatorName:dt.emulatorName,runAttemptId:_t}),Lo=g.child(qr.loggerBindings||{}),qu=await Ic({driver:dt.driver,onLogs:Ns=>{qr.appendLogs(Ns)}}),un=x||t.settings?.defaultEnv,kh;un&&(kh=bs(un,b,Lo).variables);let wM=new oi({variablesFromEnvironment:kh??{},envName:un,testName:t.name}),Uh=await Fi.init({driver:dt.driver,generator:j,logger:Lo,limbarClient:dt.limbarClient,playwrightDevice:dt.playwrightDevice,orgId:u,adbPort:dt.adbPort,options:{emulator:W},fixtures:{storage:Ae,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Je,testContext:wM}}),$;try{$=await Cu({containerName:`mobile test ${t.name}`,fixtures:{controller:Uh,logger:Lo,cacheStorage:Se,usageTracker:m},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:qr,callbacks:{}})}finally{await qu(),await dt.cleanup(),await Uh.cleanup()}return await qr.finish({logger:Lo,results:$.results,status:$.status}),$}import{debounce as VG}from"ts-debounce";var Ls="0.9.5";var Vu="assets";function WG(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 jG(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Ih=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Ro,an.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Vu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Vu}/${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:jG(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 Xi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Xi=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(`${Vu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Ih(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:WG(e.status),finishedAt:e.finishedAt}))))}},Oh=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(`
|
|
4397
4397
|
`);this.logStream.write(t+`
|
|
4398
4398
|
`)}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:uu(o,t),beforeResults:i?uu(i,t):void 0,afterResults:a?uu(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 Xi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Xi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Xi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Vu}/${t}.jpeg`)}},Lh=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:bn,runAttemptSchemaVersion:oE,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=VG(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Oh(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Wu=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:rr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Ls,labels:a??[]},c=new Cs(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:Ls,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 Lh(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function TM(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 cn(){try{await k(Promise.all([mE(),Et.flush()]),{milliseconds:5e3})}catch{}}async function vM(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;qG(d)&&C.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await TM(s,a,e.ignoreQuarantine),m=await hr(i),h=await bM({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:C,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Wu.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,w=new Set,T=async()=>KG({runResults:b,startTime:x,ranTests:w,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],A=async Ae=>{C.warn(`${Ae} Stopping tests and printing latest results.`),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(_.map(K=>K())),await cn(),process.exit(1)},N=async()=>{await A("SIGINT received.")};process.once("SIGINT",N);let G;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let Ae=e.timeoutMinutes*60*1e3;G=setTimeout(()=>{A(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},Ae)}let W={};for(let Ae=0;Ae<h.length;Ae++){let K=Object.values(W);K.length===p&&await Promise.race(K.map(Q=>Q.promise));let j=h[Ae],le=`test-${Ae}`;W[le]={done:!1,promise:(async({testDefinition:Q})=>{w.add(le);let Je=Q.relativeFilePath.includes("..")?Q.fullFilePath:Q.relativeFilePath;Da({status:"START",testLogRef:Je,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length});let De=setInterval(()=>Da({status:"RUN",testLogRef:Je,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Bt=$G(),Wt=f.child({testId:Q.id,runId:Bt}),ke=new Gc({logger:Wt,reporter:new Ou(a),runType:"mobile-test-run",runId:Bt,testMetadata:Q,suiteMetadata:void 0});try{let Ie=await EM({metadata:{...o,runId:Bt},fixtures:{...t,tracer:E,logger:Wt,usageTracker:ke},inputs:{...n,project:i,testDefinition:Q,channel:n.channel??Q.settings?.defaultChannel,tag:n.tag??Q.settings?.defaultTag,logUpdate:(_t,dt)=>Da({status:_t,testLogRef:Je,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length,additionalText:dt}),runSigIntHandlers:_},options:e});Da({status:Ie.status,testLogRef:Je,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length}),b.push(Ie)}catch(Ie){let _t=`Encountered unexpected fatal error when running test '${Q.name}': ${Ie.message}
|
|
4399
4399
|
${Ie.stack}`;C.error(_t),Wt.error({err:Ie},`Encountered unexpected fatal error when running test ${Q.name}`)}finally{clearInterval(De),W[le].done=!0,delete W[le]}await ke.flush(s)})({testDefinition:j})}}await Promise.allSettled(Object.values(W).map(Ae=>Ae.promise)),G&&clearTimeout(G);let Se=b.some(Ae=>Ae.status==="FAILED"&&!Ae.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:Se}),process.off("SIGINT",N),T()}async function KG({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=gE({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${xp}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return C.log(""),o?(C.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await ku({client:n,consoleLogger:C,resultsPath:i})):C.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 Nh(){DA(),yE("Chromium")||(co?(await Ol("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Nl({rawBrowsers:["chromium"],force:!1,all:!1})):(C.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)))}CA({serviceName:"mobile-cli"});ar.setApp("mobile-cli");var jn=new YG;jn.name("momentic-mobile").description("Momentic Mobile CLI").version(Ls);var eV=jn.command("assets").description("Manage mobile testing assets");eV.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Is).addOption(Os).addOption(xh).addOption(dM).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=$u.resolve(r);ju.existsSync(a)||(C.error(`File not found: ${a}`),process.exit(1));let s=new Rr({baseUrl:n,apiKey:t,logger:C});/\.apk$/i.test(a)||(C.error(`File is not an APK file: ${a}`),process.exit(1)),await Pc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:C})});jn.command("app").addOption(Is).addOption(Os).addOption(Ah).addOption(vh).addOption(_h).addOption(wh).addOption(Ch).addOption(Rh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=_p(r.logLevel);ar.setApp("mobile-desktop-server");let c=new Rr({baseUrl:t,apiKey:e,logger:ar});await oh({client:c,skipPrompts:n}),C.debug("API key check complete");let l=ZG(import.meta.url),u=$u.dirname(l),d=$u.resolve(u,"..","static");await Nh(),C.debug({appiumHome:as},"Resolved resource paths");let p=await Ts({configFilePath:r.config}),g=lM;await sM({momenticServerUrl:t,serverPort:g,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:s,logger:ar,regenerateCache:a,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${g}`;C.info(`Local app started on: ${m}`),await QG(m)});var AM=jn.command("results").description("Merge and upload test results.");AM.command("merge").description("Merge test results files.").addOption(Mh).addArgument(new Dh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(C.error("Output directory is required."),process.exit(1)),ju.existsSync(r)||(C.warn("Results path does not exist, skipping merge."),process.exit(0)),ju.existsSync(t)&&C.warn(`Output directory ${t} already exists, removing before merging...`),zx(ar,t,r),await cn(),process.exit(0)});var tV=new Dh("<results>","Path to the results archive.").argRequired();AM.command("upload").description("Upload test results to Momentic cloud.").addOption(Is).addOption(Os).addArgument(tV).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=ar,i=new Rr({baseUrl:n,apiKey:t,logger:o});await ku({consoleLogger:C,resultsPath:r,client:i}),await cn(),process.exit(0)});var rV=jn.command("run").alias("test").description("Run tests on the local machine");rV.addOption(Is).addOption(Os).addOption(vh).addOption(Ah).addOption(hM).addOption(_h).addOption(wh).addOption(Ch).addOption(Rh).addOption(Mh).addOption(fM).addOption(SM).addOption(yM).addOption(xh).addOption(uM).addOption(pM).addOption(mM).addOption(gM).addArgument(new Dh("<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=_p(e.logLevel);await Nh(),C.debug({appiumHome:as},"Resolved resource paths");let c=await Ts({configFilePath:e.config}),l=a??c.config.outputDir??Mx,u=e.parallel??c.config.parallel??1;C.debug("Checking API key and dependencies");let d=new Rr({baseUrl:n,apiKey:t,logger:C}),{orgId:p,userId:g}=await oh({client:d,skipPrompts:e.yes});C.debug("API key check and browser installation complete");let m=JG(),h=ar.child({runGroupId:m,orgId:p,userId:g}),f=await Hi(ar,d,c);h.debug(f,"Got local git metadata");try{let E=await vM({options:{...e,parallel:u,outputDir:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:s,timeoutMinutes:e.timeoutMinutes},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:m,orgId:p}});await cn(),E.failed>0?process.exit(1):process.exit(0)}catch(E){C.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),C.error(E),ar.error({err:E},"Failed to run tests locally"),await cn(),process.exit(1)}});jn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new XG("--name <name>","Name of the project")).action(async r=>{C.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|