momentic-mobile 0.9.2 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -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",Oa(e,...t))}error(e,...t){this._log("error",Oa(e,...t))}info(e,...t){this._log("info",Oa(e,...t))}log(e,...t){this._log("log",Oa(e,...t))}warn(e,...t){this._log("warn",Oa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function sE(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 Cm=" ".repeat(6);import BL from"fetch-retry";import zL from"os";import lE,{multistream as HL}from"pino";import GL from"pino-pretty";import VL from"pino-std-serializers";var ii=new Map,WL=!0,cE="Log throttle exceeded",jL=100,$L=5e3,qL=BL(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}}),Rm=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??zL.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=WL?lE(a):lE(a,HL([{stream:GL({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:so(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===cE)return!0;let t=Date.now();return t-this.lastWindowStart>$L&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,cE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<jL?(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(Pa[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=VL.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:Qy({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,ii.set("app",this),ii.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=Zy[e]):(this.minLevelValue=Pa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ai=({app:r,hostname:e,disableConsoleLogs:t})=>(ii.has(r)||ii.set(r,new Rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ii.get(r));async function uE(){await Promise.all([...ii.values()].map(r=>r.flush()))}import{hostname as KL}from"os";var ar=ai({app:"cli",hostname:KL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.2"});function xm(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function dE({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 sE(()=>{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 La=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=si.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=si.bgGreen.white("PASS"),a=3):r.includes("START")?(i=si.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=si.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=si.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=si.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),YL||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import XL from"fs";import{tmpdir as JL}from"os";import QL from"path";import{registry as Na}from"playwright-core/lib/server";import mE from"proper-lockfile";var pE=QL.join(JL(),"momenticBrowserInstallation");var Mm=["chrome","chromium","chrome-for-testing","ffmpeg"],ZL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},gE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function hE(r){let e=gE[ZL[r]??""]??"",t=Na.findExecutable(e);return!t||t.installType==="none"?!1:_m(t)}function _m(r){let e=r.executablePath();return XL.existsSync(e)}function eN(r,e){let t=gE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Na.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&_m(n)))return n}async function tN({browser:r,force:e}){let t=eN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await Na.installDeps([t],!1),await Na.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=Na.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!_m(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?Mm:Array.from(new Set(r));try{await mE.lock(pE,{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 tN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await mE.unlock(pE,{realpath:!1})}if(o)throw o}import{createServer as rN}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=rN();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 ree from"blocked-at";import oee from"why-is-node-running";import L0 from"fs";import{tmpdir as N0}from"os";import D0 from"path";import{remote as k0}from"webdriverio";import{createInstanceClient as R0}from"@limrun/api";import{execSync as x0}from"child_process";import hee,{multistream as See}from"pino";import bee from"pino-pretty";var vee=5*1024,nN="...[truncated]",Aee=Buffer.byteLength(nN,"utf8");import{PostHog as Lee}from"posthog-node";var Rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var fE=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:m}=e;if(m.aborted)return c(fE(m));l=()=>c(fE(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new Rn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Gee}from"posthog-node";import{execSync as oN}from"child_process";import li from"os";import iN from"v8";var SE,Dr,bE=li.platform(),aN=li.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),{}),yE=r=>{try{let e={},t=!1,n=sN(),o=lN(),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=iN.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"),lo&&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 EE(r){if(!Lr)return yE(r),{interval:setInterval(()=>yE(r),2e4),cpuMetadata:aN,platform:bE}}function sN(){let r=li.totalmem(),e=bE==="darwin"?cN():(()=>{let n=li.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function lN(){let r=li.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 SE={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,SE}function cN(){try{let r=oN("/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 m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,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=li.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 uN(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=uN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var qE="=",Gl=";",Hm=",";var KE=8192;var mi={};TM(mi,{getKeyPairs:()=>VN,parseKeyPairsIntoRecord:()=>WN,parsePairKeyValue:()=>YE,serializeKeyPairs:()=>GN});Me();var HN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function GN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Hm:"")+t;return n.length>KE?e:n},"")}function VN(r){return r.getAllEntries().map(function(e){var t=HN(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 YE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(qE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Im(e.join(Gl))),{key:o,value:i,metadata:a}}}}}function WN(r){return typeof r!="string"||r.length===0?{}:r.split(Hm).map(function(e){return YE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var 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 jN=",",$N=["OTEL_SDK_DISABLED"];function qN(r){return $N.indexOf(r)>-1}var KN=["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 YN(r){return KN.indexOf(r)>-1}var XN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function JN(r){return XN.indexOf(r)>-1}var Gm=1/0,Vm=128,QN=128,ZN=128,Wm={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:Gm,OTEL_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:QN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ZN,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 eD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function tD(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 rD(r,e,t,n){n===void 0&&(n=jN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var nD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function oD(r,e,t){var n=t[r];if(typeof n=="string"){var o=nD[n.toUpperCase()];o!=null&&(e[r]=o)}}function XE(r){var e={};for(var t in Wm){var n=t;switch(n){case"OTEL_LOG_LEVEL":oD(n,e,r);break;default:if(qN(n))eD(n,e,r);else if(YN(n))tD(n,e,r);else if(JN(n))rD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=XE(process.env);return Object.assign({},Wm,r)}function JE(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=JE(r.charCodeAt(n)),i=JE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var QE="1.25.1";var iD="deployment.environment";var aD="process.runtime.name";var sD="service.name";var lD="service.instance.id";var cD="telemetry.sdk.name",uD="telemetry.sdk.language",dD="telemetry.sdk.version";var ZE=iD;var eT=aD;var jl=sD;var tT=lD;var Ha=cD,Ga=uD,Va=dD;var mD="nodejs";var rT=mD;var pi,$l=(pi={},pi[Ha]="opentelemetry",pi[eT]="node",pi[Ga]=rT,pi[Va]=QE,pi);var pD=9,gD=6,hD=Math.pow(10,gD),fD=Math.pow(10,pD);function nT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*hD);return[t,n]}function oT(r){return r[0]*fD+r[1]}function Wa(r){return r[0]*1e6+r[1]/1e3}var uo;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(uo||(uo={}));var iT=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 SD=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},yD=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))},aT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new iT}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,yD([this._that],SD(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 bD=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 mne=function(r){bD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function sT(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var 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 lT=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 ED=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 TD(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 jm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=TD(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=sT(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 $m=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jm(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 jm(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 jm(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=ED(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}();Me();var qm=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},Km=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))},Ym=function(){function r(e,t,n,o){e===void 0&&(e=new vD),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 vD=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,Km([n,this._counts.length-t],qm(this._counts.slice(t)),!1)),o.splice.apply(o,Km([0,t],qm(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(Km([],qm(this._counts),!1))},r}();var cT=52,AD=2146435072,wD=1048575,Xm=1023,ql=-Xm+1,Kl=Xm,ja=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&AD)>>20;return n-Xm}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&wD)*Math.pow(2,32);return o+n}function $a(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function dT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var CD=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)}}(),xn=function(r){CD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var pT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ja)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,cT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new xn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new xn("overflow: "+e+" is > maximum lower boundary: "+n);return $a(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 gT=function(){function r(e){this._scale=e,this._scaleFactor=$a(Math.LOG2E,e),this._inverseFactor=$a(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ja)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 xn("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 xn("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 hT=-10,fT=20,RD=Array.from({length:31},function(r,e){return e>10?new gT(e-10):new pT(e-10)});function Jm(r){if(r>fT||r<hT)throw new xn("expected scale >= "+hT+" && <= "+fT+", got: "+r);return RD[r+10]}var xD=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}(),MD=20,_D=160,Qm=2,PD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_D),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 Ym),u===void 0&&(u=new Ym),d===void 0&&(d=Jm(MD)),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<Qm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Qm),this._maxSize=Qm)}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=dT(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=Jm(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 ST=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PD(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=xD(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 ID=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},Zm=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=nT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var yT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zm(e)},r.prototype.merge=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(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=ID(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();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},qa=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 ep=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new qa(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qa(t.startTime,this.monotonic,o,t.reset):new qa(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 qa(t.startTime,this.monotonic,o,!0):new qa(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=OD(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 RT},r.Sum=function(){return xT},r.LastValue=function(){return MT},r.Histogram=function(){return _T},r.ExponentialHistogram=function(){return LD},r.Default=function(){return ND},r}();var bT=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 lT,e}(Ur);var ET=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 ep(!0),e.NON_MONOTONIC_INSTANCE=new ep(!1),e}(Ur);var TT=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 yT,e}(Ur);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 $m([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var AT=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 $m(this._boundaries,this._recordMinMax)},e}(Ur);var wT=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 ST(this._maxSize,this._recordMinMax)},e}(Ur);var CT=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 xT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return MT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new AT(t.advice.explicitBucketBoundaries):_T}return H.warn("Unable to recognize instrument type: "+t.type),RT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var RT=new bT,xT=new ET,MT=new TT,_T=new vT,LD=new wT,ND=new CT;Me();function Ql(){return"unknown_service:"+process.argv0}var Mn=function(){return Mn=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},Mn.apply(this,arguments)},DD=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())})},kD=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}}},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},tp=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[Ga]=$l[Ga],e[Ha]=$l[Ha],e[Va]=$l[Va],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 DD(this,void 0,void 0,function(){return kD(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=Mn(Mn({},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=UD(a,2),l=c[0],u=c[1];return Mn(Mn(Mn(Mn({},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 po;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(po||(po={}));Me();var FD=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())})},BD=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}}},rp=function(){return sr.CUMULATIVE},PT=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}},IT=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 zD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?rp:e==="delta"?PT:e==="lowmemory"?IT:(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."),rp)}function HD(r){return r!=null?r===po.DELTA?PT:r===po.LOWMEMORY?IT:rp:zD()}function GD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var OT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=GD(t),this._aggregationTemporalitySelector=HD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return FD(this,void 0,void 0,function(){return BD(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var 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},LT=1e4,NT=5,DT=1e3,kT=5e3,UT=1.5;function Ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=VD(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 np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function op(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 ip(r){return typeof r=="number"?r<=0?ap(r,LT):r:WD()}function WD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ap(e,LT):e}function ap(r,e){return H.warn("Timeout must be greater than 0",r),e}function FT(r){var e=[429,502,503,504];return e.includes(r)}function BT(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 zT=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 aT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ip(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:uo.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:uo.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:uo.SUCCESS})}).catch(function(n){t({code:uo.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}();Me();import*as sp from"url";import*as ec from"http";import*as tc from"https";import*as HT from"zlib";import{Readable as $D}from"stream";var _n;(function(r){r.NONE="none",r.GZIP="gzip"})(_n||(_n={}));var jD=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)}}(),gi=function(r){jD(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 lp(r,e,t,n,o){var i=r.timeoutMillis,a=new sp.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 gi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={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,p=function(h,f){switch(h===void 0&&(h=NT),f===void 0&&(f=DT),l=g(m,function(b){var x="";b.on("data",function(v){return x+=v}),b.on("aborted",function(){if(u){var v=new gi("Request Timeout");o(v)}}),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&&FT(b.statusCode)&&h>0){var v=void 0;f=UT*f,b.headers["retry-after"]?v=BT(b.headers["retry-after"]):v=Math.round(Math.random()*(kT-f)+f),c=setTimeout(function(){p(h-1,f)},v)}else{var A=new gi(b.statusMessage,b.statusCode,x);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new gi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new gi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case _n.GZIP:{l.setHeader("Content-Encoding","gzip");var E=qD(e);E.on("error",o).pipe(HT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};p()}function qD(r){var e=new $D;return e.push(r),e.push(null),e}function cp(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 sp.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 up(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===_n.GZIP?_n.GZIP:_n.NONE}Me();var KD=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){KD(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,Ka(t.headers),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=cp(t),i.compression=up(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;lp(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}(zT);function VT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function YD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function WT(r){var e=VT(r);return YD(e)}function XD(r){var e=VT(r);return e.toString()}var JD=typeof BigInt<"u"?XD:oT;function GT(r){return r}function jT(r){if(r!==void 0)return Wl(r)}var QD={encodeHrTime:WT,encodeSpanContext:Wl,encodeOptionalSpanContext:jT};function $T(r){var e,t;if(r===void 0)return QD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?WT:JD,encodeSpanContext:o?GT:Wl,encodeOptionalSpanContext:o?GT:jT}}var ZD=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 qT(r){return{name:r.name,version:r.version}}function hi(r){return Object.keys(r).map(function(e){return KT(e,r[e])})}function KT(r,e){return{key:r,value:YT(e)}}function YT(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(YT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ZD(t,2),o=n[0],i=n[1];return KT(o,i)})}}:{}}function XT(r){return{attributes:hi(r.attributes),droppedAttributesCount:0}}Me();function QT(r,e){var t=$T(e);return{resource:XT(r.resource),schemaUrl:void 0,scopeMetrics:ek(r.scopeMetrics,t)}}function ek(r,e){return Array.from(r.map(function(t){return{scope:qT(t.scope),metrics:t.metrics.map(function(n){return tk(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function tk(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=ik(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:JT(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:JT(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:nk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ok(r,e)};break}return t}function rk(r,e,t){var n={attributes:hi(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 JT(r,e){return r.dataPoints.map(function(t){return rk(t,r.descriptor.valueType,e)})}function nk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ok(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ik(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function ZT(r,e){return{resourceMetrics:r.map(function(t){return QT(t,e)})}}var dp={serializeRequest:function(r){var e=ZT(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 ev="0.52.1";var tv=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)}}(),fi=function(){return fi=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},fi.apply(this,arguments)},rv="v1/metrics",ak="http://localhost:4318/"+rv,sk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+ev},lk=function(r){tv(e,r);function e(t){var n=r.call(this,t,dp,"application/json")||this;return n.headers=fi(fi(fi(fi({},n.headers),sk),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?op(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?np(bt().OTEL_EXPORTER_OTLP_ENDPOINT,rv):ak},e}(rc),nv=function(r){tv(e,r);function e(t){return r.call(this,new lk(t),t)||this}return e}(OT);var Si;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Si||(Si={}));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={}));Me();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)}}(),ov=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())})},iv=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}}},uk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dk=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))},mk=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 av(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 sv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var mp=function(r){ck(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Pn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new mp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function lv(r){return ov(this,void 0,void 0,function(){var e=this;return iv(this,function(t){return[2,Promise.all(r.map(function(n){return ov(e,void 0,void 0,function(){var o,i;return iv(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 cv(r){return r.status==="rejected"}function pp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,dk([],uk(e(n)),!1))}),t}function uv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=mk(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 dv(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 mv(r,e){return r.toLowerCase()===e.toLowerCase()}Me();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 gp=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}();Me();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 gk(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 pv(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 gv(r,e){return mv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var pk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function gk(r){return r.match(pk)!=null}var 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};function fk(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=fk(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=dv(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=hk(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}();Me();var hp=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},fp=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))},Sp=function(){function r(e,t,n,o){e===void 0&&(e=new Sk),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 Sk=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,fp([n,this._counts.length-t],hp(this._counts.slice(t)),!1)),o.splice.apply(o,fp([0,t],hp(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(fp([],hp(this._counts),!1))},r}();var hv=52,yk=2146435072,bk=1048575,yp=1023,ac=-yp+1,sc=yp,Ya=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&yk)>>20;return n-yp}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&bk)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Sv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Ek=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)}}(),In=function(r){Ek(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var bv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,hv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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 Ev=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 Tv=-10,vv=20,Tk=Array.from({length:31},function(r,e){return e>10?new Ev(e-10):new bv(e-10)});function bp(r){if(r>vv||r<Tv)throw new In("expected scale >= "+Tv+" && <= "+vv+", got: "+r);return Tk[r+10]}var vk=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}(),Ak=20,wk=160,Ep=2,Av=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=wk),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 Sp),u===void 0&&(u=new Sp),d===void 0&&(d=bp(Ak)),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<Ep&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ep),this._maxSize=Ep)}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=Sv(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=bp(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 Tp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Av(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=vk(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}();Me();var Ck=Om("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function wv(r){return r.setValue(Ck,!0)}Me();function Cv(){return function(r){H.error(Rk(r))}}function Rk(r){return typeof r=="string"?r:JSON.stringify(xk(r))}function xk(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 Mk=Cv();function dc(r){try{Mk(r)}catch{}}var Rv="1.30.1";var _k="process.runtime.name";var Pk="service.name";var Ik="telemetry.sdk.name",Ok="telemetry.sdk.language",Lk="telemetry.sdk.version";var xv=_k;var Mv=Pk;var Ja=Ik,Qa=Ok,Za=Lk;var Nk="nodejs";var _v=Nk;var yi,go=(yi={},yi[Ja]="opentelemetry",yi[xv]="node",yi[Qa]=_v,yi[Za]=Rv,yi);function es(r){r.unref()}var Hk=9,Gk=6,Vk=Math.pow(10,Gk),fae=Math.pow(10,Hk);function ho(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Vk);return[t,n]}function bi(r){return r[0]*1e6+r[1]/1e3}var ts;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ts||(ts={}));Me();function Pv(r,e){return new Promise(function(t){di.with(wv(di.active()),function(){r.export(e,function(n){t(n)})})})}var Iv={_export:Pv};var Wk=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},mc=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=ho(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vp=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new mc(e)},r.prototype.merge=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(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=Wk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var jk=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},Ei=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 pc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new Ei(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ei(t.startTime,this.monotonic,o,t.reset):new Ei(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 Ei(t.startTime,this.monotonic,o,!0):new Ei(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=jk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var fo=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 Fv},r.Sum=function(){return Bv},r.LastValue=function(){return zv},r.Histogram=function(){return Hv},r.ExponentialHistogram=function(){return $k},r.Default=function(){return qk},r}();var Ov=function(r){fo(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 gp,e}(ur);var Lv=function(r){fo(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 pc(!0),e.NON_MONOTONIC_INSTANCE=new pc(!1),e}(ur);var Nv=function(r){fo(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 vp,e}(ur);var Dv=function(r){fo(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 rs=function(r){fo(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 kv=function(r){fo(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 Tp(this._maxSize,this._recordMinMax)},e}(ur);var Uv=function(r){fo(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 Bv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return zv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new rs(t.advice.explicitBucketBoundaries):Hv}return H.warn("Unable to recognize instrument type: "+t.type),Fv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Fv=new Ov,Bv=new Lv,zv=new Nv,Hv=new Dv,$k=new kv,qk=new Uv;var Gv=function(r){return ur.Default()},Vv=function(r){return Si.CUMULATIVE};var Ap=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())})},wp=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}}},Wv=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},Kk=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))},jv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Gv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:Vv,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 Ap(this,void 0,void 0,function(){var t,n,o,i,a,s;return wp(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(Kk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Wv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Wv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(pp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(pp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var Yk=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}}},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},Jk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Cp=function(r){Yk(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,Pn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof mp?(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,Jk(["PeriodicExportingMetricReader: metrics collection errors"],Xk(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,Iv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ts.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),es(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}(jv);Me();Me();function fc(){return"unknown_service:"+process.argv0}var On=function(){return On=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},On.apply(this,arguments)},Qk=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())})},Zk=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}}},e0=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[Mv]=fc(),e[Qa]=go[Qa],e[Ja]=go[Ja],e[Za]=go[Za],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 Qk(this,void 0,void 0,function(){return Zk(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=On(On({},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=e0(a,2),l=c[0],u=c[1];return On(On(On(On({},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 $v=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var 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)}}(),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=di.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,ho(Date.now()))},r}();var qv=function(r){So(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 Kv=function(r){So(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 Yv=function(r){So(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 Xv=function(r){So(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 Jv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Qv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function ns(r){return r instanceof bc}var eA=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 Yv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Kv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new qv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Qv(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 Jv(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 Zv(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 t0=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)}}(),tA=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}}},r0=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 tA(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 tA(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){t0(e,r);function e(){return r.call(this,nc)||this}return e}(r0);var n0=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=n0(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 m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,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 Rp=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.")},rA=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===Si.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=o0(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=Rp(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=Rp(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=rA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,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=Rp(e.keys()),s=a.next();!s.done;s=a.next()){var c=rA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function o0(r){return Array.from(r.entries())}var i0=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)}}(),a0=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},nA=function(r){i0(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=a0(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);Me();function xp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
27
|
+
`),globalThis.console=e}}var Cm=" ".repeat(6);import BL from"fetch-retry";import zL from"os";import lE,{multistream as HL}from"pino";import GL from"pino-pretty";import VL from"pino-std-serializers";var ii=new Map,WL=!0,cE="Log throttle exceeded",jL=100,$L=5e3,qL=BL(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}}),Rm=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??zL.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=WL?lE(a):lE(a,HL([{stream:GL({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:so(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===cE)return!0;let t=Date.now();return t-this.lastWindowStart>$L&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,cE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<jL?(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(Pa[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=VL.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:Qy({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,ii.set("app",this),ii.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=Zy[e]):(this.minLevelValue=Pa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ai=({app:r,hostname:e,disableConsoleLogs:t})=>(ii.has(r)||ii.set(r,new Rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ii.get(r));async function uE(){await Promise.all([...ii.values()].map(r=>r.flush()))}import{hostname as KL}from"os";var ar=ai({app:"cli",hostname:KL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.3"});function xm(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function dE({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 sE(()=>{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 La=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=si.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=si.bgGreen.white("PASS"),a=3):r.includes("START")?(i=si.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=si.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=si.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=si.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),YL||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import XL from"fs";import{tmpdir as JL}from"os";import QL from"path";import{registry as Na}from"playwright-core/lib/server";import mE from"proper-lockfile";var pE=QL.join(JL(),"momenticBrowserInstallation");var Mm=["chrome","chromium","chrome-for-testing","ffmpeg"],ZL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},gE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function hE(r){let e=gE[ZL[r]??""]??"",t=Na.findExecutable(e);return!t||t.installType==="none"?!1:_m(t)}function _m(r){let e=r.executablePath();return XL.existsSync(e)}function eN(r,e){let t=gE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Na.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&_m(n)))return n}async function tN({browser:r,force:e}){let t=eN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await Na.installDeps([t],!1),await Na.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=Na.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!_m(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?Mm:Array.from(new Set(r));try{await mE.lock(pE,{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 tN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await mE.unlock(pE,{realpath:!1})}if(o)throw o}import{createServer as rN}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=rN();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 ree from"blocked-at";import oee from"why-is-node-running";import L0 from"fs";import{tmpdir as N0}from"os";import D0 from"path";import{remote as k0}from"webdriverio";import{createInstanceClient as R0}from"@limrun/api";import{execSync as x0}from"child_process";import hee,{multistream as See}from"pino";import bee from"pino-pretty";var vee=5*1024,nN="...[truncated]",Aee=Buffer.byteLength(nN,"utf8");import{PostHog as Lee}from"posthog-node";var Rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var fE=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:m}=e;if(m.aborted)return c(fE(m));l=()=>c(fE(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new Rn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Gee}from"posthog-node";import{execSync as oN}from"child_process";import li from"os";import iN from"v8";var SE,Dr,bE=li.platform(),aN=li.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),{}),yE=r=>{try{let e={},t=!1,n=sN(),o=lN(),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=iN.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"),lo&&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 EE(r){if(!Lr)return yE(r),{interval:setInterval(()=>yE(r),2e4),cpuMetadata:aN,platform:bE}}function sN(){let r=li.totalmem(),e=bE==="darwin"?cN():(()=>{let n=li.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function lN(){let r=li.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 SE={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,SE}function cN(){try{let r=oN("/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 m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,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=li.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 uN(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=uN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var qE="=",Gl=";",Hm=",";var KE=8192;var mi={};TM(mi,{getKeyPairs:()=>VN,parseKeyPairsIntoRecord:()=>WN,parsePairKeyValue:()=>YE,serializeKeyPairs:()=>GN});Me();var HN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function GN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Hm:"")+t;return n.length>KE?e:n},"")}function VN(r){return r.getAllEntries().map(function(e){var t=HN(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 YE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(qE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Im(e.join(Gl))),{key:o,value:i,metadata:a}}}}}function WN(r){return typeof r!="string"||r.length===0?{}:r.split(Hm).map(function(e){return YE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var 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 jN=",",$N=["OTEL_SDK_DISABLED"];function qN(r){return $N.indexOf(r)>-1}var KN=["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 YN(r){return KN.indexOf(r)>-1}var XN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function JN(r){return XN.indexOf(r)>-1}var Gm=1/0,Vm=128,QN=128,ZN=128,Wm={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:Gm,OTEL_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:QN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ZN,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 eD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function tD(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 rD(r,e,t,n){n===void 0&&(n=jN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var nD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function oD(r,e,t){var n=t[r];if(typeof n=="string"){var o=nD[n.toUpperCase()];o!=null&&(e[r]=o)}}function XE(r){var e={};for(var t in Wm){var n=t;switch(n){case"OTEL_LOG_LEVEL":oD(n,e,r);break;default:if(qN(n))eD(n,e,r);else if(YN(n))tD(n,e,r);else if(JN(n))rD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=XE(process.env);return Object.assign({},Wm,r)}function JE(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=JE(r.charCodeAt(n)),i=JE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var QE="1.25.1";var iD="deployment.environment";var aD="process.runtime.name";var sD="service.name";var lD="service.instance.id";var cD="telemetry.sdk.name",uD="telemetry.sdk.language",dD="telemetry.sdk.version";var ZE=iD;var eT=aD;var jl=sD;var tT=lD;var Ha=cD,Ga=uD,Va=dD;var mD="nodejs";var rT=mD;var pi,$l=(pi={},pi[Ha]="opentelemetry",pi[eT]="node",pi[Ga]=rT,pi[Va]=QE,pi);var pD=9,gD=6,hD=Math.pow(10,gD),fD=Math.pow(10,pD);function nT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*hD);return[t,n]}function oT(r){return r[0]*fD+r[1]}function Wa(r){return r[0]*1e6+r[1]/1e3}var uo;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(uo||(uo={}));var iT=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 SD=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},yD=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))},aT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new iT}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,yD([this._that],SD(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 bD=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 mne=function(r){bD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function sT(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var 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 lT=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 ED=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 TD(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 jm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=TD(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=sT(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 $m=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jm(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 jm(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 jm(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=ED(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}();Me();var qm=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},Km=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))},Ym=function(){function r(e,t,n,o){e===void 0&&(e=new vD),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 vD=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,Km([n,this._counts.length-t],qm(this._counts.slice(t)),!1)),o.splice.apply(o,Km([0,t],qm(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(Km([],qm(this._counts),!1))},r}();var cT=52,AD=2146435072,wD=1048575,Xm=1023,ql=-Xm+1,Kl=Xm,ja=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&AD)>>20;return n-Xm}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&wD)*Math.pow(2,32);return o+n}function $a(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function dT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var CD=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)}}(),xn=function(r){CD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var pT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ja)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,cT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new xn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new xn("overflow: "+e+" is > maximum lower boundary: "+n);return $a(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 gT=function(){function r(e){this._scale=e,this._scaleFactor=$a(Math.LOG2E,e),this._inverseFactor=$a(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ja)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 xn("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 xn("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 hT=-10,fT=20,RD=Array.from({length:31},function(r,e){return e>10?new gT(e-10):new pT(e-10)});function Jm(r){if(r>fT||r<hT)throw new xn("expected scale >= "+hT+" && <= "+fT+", got: "+r);return RD[r+10]}var xD=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}(),MD=20,_D=160,Qm=2,PD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_D),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 Ym),u===void 0&&(u=new Ym),d===void 0&&(d=Jm(MD)),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<Qm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Qm),this._maxSize=Qm)}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=dT(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=Jm(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 ST=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PD(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=xD(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 ID=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},Zm=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=nT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var yT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zm(e)},r.prototype.merge=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(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=ID(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();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},qa=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 ep=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new qa(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qa(t.startTime,this.monotonic,o,t.reset):new qa(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 qa(t.startTime,this.monotonic,o,!0):new qa(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=OD(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 RT},r.Sum=function(){return xT},r.LastValue=function(){return MT},r.Histogram=function(){return _T},r.ExponentialHistogram=function(){return LD},r.Default=function(){return ND},r}();var bT=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 lT,e}(Ur);var ET=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 ep(!0),e.NON_MONOTONIC_INSTANCE=new ep(!1),e}(Ur);var TT=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 yT,e}(Ur);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 $m([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var AT=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 $m(this._boundaries,this._recordMinMax)},e}(Ur);var wT=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 ST(this._maxSize,this._recordMinMax)},e}(Ur);var CT=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 xT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return MT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new AT(t.advice.explicitBucketBoundaries):_T}return H.warn("Unable to recognize instrument type: "+t.type),RT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var RT=new bT,xT=new ET,MT=new TT,_T=new vT,LD=new wT,ND=new CT;Me();function Ql(){return"unknown_service:"+process.argv0}var Mn=function(){return Mn=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},Mn.apply(this,arguments)},DD=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())})},kD=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}}},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},tp=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[Ga]=$l[Ga],e[Ha]=$l[Ha],e[Va]=$l[Va],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 DD(this,void 0,void 0,function(){return kD(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=Mn(Mn({},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=UD(a,2),l=c[0],u=c[1];return Mn(Mn(Mn(Mn({},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 po;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(po||(po={}));Me();var FD=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())})},BD=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}}},rp=function(){return sr.CUMULATIVE},PT=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}},IT=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 zD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?rp:e==="delta"?PT:e==="lowmemory"?IT:(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."),rp)}function HD(r){return r!=null?r===po.DELTA?PT:r===po.LOWMEMORY?IT:rp:zD()}function GD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var OT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=GD(t),this._aggregationTemporalitySelector=HD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return FD(this,void 0,void 0,function(){return BD(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var 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},LT=1e4,NT=5,DT=1e3,kT=5e3,UT=1.5;function Ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=VD(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 np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function op(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 ip(r){return typeof r=="number"?r<=0?ap(r,LT):r:WD()}function WD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ap(e,LT):e}function ap(r,e){return H.warn("Timeout must be greater than 0",r),e}function FT(r){var e=[429,502,503,504];return e.includes(r)}function BT(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 zT=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 aT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ip(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:uo.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:uo.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:uo.SUCCESS})}).catch(function(n){t({code:uo.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}();Me();import*as sp from"url";import*as ec from"http";import*as tc from"https";import*as HT from"zlib";import{Readable as $D}from"stream";var _n;(function(r){r.NONE="none",r.GZIP="gzip"})(_n||(_n={}));var jD=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)}}(),gi=function(r){jD(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 lp(r,e,t,n,o){var i=r.timeoutMillis,a=new sp.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 gi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={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,p=function(h,f){switch(h===void 0&&(h=NT),f===void 0&&(f=DT),l=g(m,function(b){var x="";b.on("data",function(v){return x+=v}),b.on("aborted",function(){if(u){var v=new gi("Request Timeout");o(v)}}),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&&FT(b.statusCode)&&h>0){var v=void 0;f=UT*f,b.headers["retry-after"]?v=BT(b.headers["retry-after"]):v=Math.round(Math.random()*(kT-f)+f),c=setTimeout(function(){p(h-1,f)},v)}else{var A=new gi(b.statusMessage,b.statusCode,x);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new gi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new gi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case _n.GZIP:{l.setHeader("Content-Encoding","gzip");var E=qD(e);E.on("error",o).pipe(HT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};p()}function qD(r){var e=new $D;return e.push(r),e.push(null),e}function cp(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 sp.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 up(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===_n.GZIP?_n.GZIP:_n.NONE}Me();var KD=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){KD(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,Ka(t.headers),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=cp(t),i.compression=up(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;lp(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}(zT);function VT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function YD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function WT(r){var e=VT(r);return YD(e)}function XD(r){var e=VT(r);return e.toString()}var JD=typeof BigInt<"u"?XD:oT;function GT(r){return r}function jT(r){if(r!==void 0)return Wl(r)}var QD={encodeHrTime:WT,encodeSpanContext:Wl,encodeOptionalSpanContext:jT};function $T(r){var e,t;if(r===void 0)return QD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?WT:JD,encodeSpanContext:o?GT:Wl,encodeOptionalSpanContext:o?GT:jT}}var ZD=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 qT(r){return{name:r.name,version:r.version}}function hi(r){return Object.keys(r).map(function(e){return KT(e,r[e])})}function KT(r,e){return{key:r,value:YT(e)}}function YT(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(YT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ZD(t,2),o=n[0],i=n[1];return KT(o,i)})}}:{}}function XT(r){return{attributes:hi(r.attributes),droppedAttributesCount:0}}Me();function QT(r,e){var t=$T(e);return{resource:XT(r.resource),schemaUrl:void 0,scopeMetrics:ek(r.scopeMetrics,t)}}function ek(r,e){return Array.from(r.map(function(t){return{scope:qT(t.scope),metrics:t.metrics.map(function(n){return tk(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function tk(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=ik(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:JT(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:JT(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:nk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ok(r,e)};break}return t}function rk(r,e,t){var n={attributes:hi(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 JT(r,e){return r.dataPoints.map(function(t){return rk(t,r.descriptor.valueType,e)})}function nk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ok(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ik(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function ZT(r,e){return{resourceMetrics:r.map(function(t){return QT(t,e)})}}var dp={serializeRequest:function(r){var e=ZT(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 ev="0.52.1";var tv=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)}}(),fi=function(){return fi=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},fi.apply(this,arguments)},rv="v1/metrics",ak="http://localhost:4318/"+rv,sk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+ev},lk=function(r){tv(e,r);function e(t){var n=r.call(this,t,dp,"application/json")||this;return n.headers=fi(fi(fi(fi({},n.headers),sk),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?op(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?np(bt().OTEL_EXPORTER_OTLP_ENDPOINT,rv):ak},e}(rc),nv=function(r){tv(e,r);function e(t){return r.call(this,new lk(t),t)||this}return e}(OT);var Si;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Si||(Si={}));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={}));Me();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)}}(),ov=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())})},iv=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}}},uk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dk=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))},mk=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 av(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 sv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var mp=function(r){ck(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Pn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new mp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function lv(r){return ov(this,void 0,void 0,function(){var e=this;return iv(this,function(t){return[2,Promise.all(r.map(function(n){return ov(e,void 0,void 0,function(){var o,i;return iv(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 cv(r){return r.status==="rejected"}function pp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,dk([],uk(e(n)),!1))}),t}function uv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=mk(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 dv(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 mv(r,e){return r.toLowerCase()===e.toLowerCase()}Me();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 gp=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}();Me();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 gk(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 pv(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 gv(r,e){return mv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var pk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function gk(r){return r.match(pk)!=null}var 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};function fk(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=fk(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=dv(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=hk(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}();Me();var hp=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},fp=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))},Sp=function(){function r(e,t,n,o){e===void 0&&(e=new Sk),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 Sk=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,fp([n,this._counts.length-t],hp(this._counts.slice(t)),!1)),o.splice.apply(o,fp([0,t],hp(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(fp([],hp(this._counts),!1))},r}();var hv=52,yk=2146435072,bk=1048575,yp=1023,ac=-yp+1,sc=yp,Ya=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&yk)>>20;return n-yp}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&bk)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Sv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Ek=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)}}(),In=function(r){Ek(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var bv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,hv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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 Ev=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 Tv=-10,vv=20,Tk=Array.from({length:31},function(r,e){return e>10?new Ev(e-10):new bv(e-10)});function bp(r){if(r>vv||r<Tv)throw new In("expected scale >= "+Tv+" && <= "+vv+", got: "+r);return Tk[r+10]}var vk=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}(),Ak=20,wk=160,Ep=2,Av=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=wk),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 Sp),u===void 0&&(u=new Sp),d===void 0&&(d=bp(Ak)),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<Ep&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ep),this._maxSize=Ep)}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=Sv(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=bp(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 Tp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Av(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=vk(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}();Me();var Ck=Om("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function wv(r){return r.setValue(Ck,!0)}Me();function Cv(){return function(r){H.error(Rk(r))}}function Rk(r){return typeof r=="string"?r:JSON.stringify(xk(r))}function xk(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 Mk=Cv();function dc(r){try{Mk(r)}catch{}}var Rv="1.30.1";var _k="process.runtime.name";var Pk="service.name";var Ik="telemetry.sdk.name",Ok="telemetry.sdk.language",Lk="telemetry.sdk.version";var xv=_k;var Mv=Pk;var Ja=Ik,Qa=Ok,Za=Lk;var Nk="nodejs";var _v=Nk;var yi,go=(yi={},yi[Ja]="opentelemetry",yi[xv]="node",yi[Qa]=_v,yi[Za]=Rv,yi);function es(r){r.unref()}var Hk=9,Gk=6,Vk=Math.pow(10,Gk),fae=Math.pow(10,Hk);function ho(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Vk);return[t,n]}function bi(r){return r[0]*1e6+r[1]/1e3}var ts;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ts||(ts={}));Me();function Pv(r,e){return new Promise(function(t){di.with(wv(di.active()),function(){r.export(e,function(n){t(n)})})})}var Iv={_export:Pv};var Wk=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},mc=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=ho(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vp=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new mc(e)},r.prototype.merge=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(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=Wk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var jk=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},Ei=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 pc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new Ei(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ei(t.startTime,this.monotonic,o,t.reset):new Ei(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 Ei(t.startTime,this.monotonic,o,!0):new Ei(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=jk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var fo=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 Fv},r.Sum=function(){return Bv},r.LastValue=function(){return zv},r.Histogram=function(){return Hv},r.ExponentialHistogram=function(){return $k},r.Default=function(){return qk},r}();var Ov=function(r){fo(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 gp,e}(ur);var Lv=function(r){fo(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 pc(!0),e.NON_MONOTONIC_INSTANCE=new pc(!1),e}(ur);var Nv=function(r){fo(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 vp,e}(ur);var Dv=function(r){fo(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 rs=function(r){fo(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 kv=function(r){fo(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 Tp(this._maxSize,this._recordMinMax)},e}(ur);var Uv=function(r){fo(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 Bv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return zv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new rs(t.advice.explicitBucketBoundaries):Hv}return H.warn("Unable to recognize instrument type: "+t.type),Fv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Fv=new Ov,Bv=new Lv,zv=new Nv,Hv=new Dv,$k=new kv,qk=new Uv;var Gv=function(r){return ur.Default()},Vv=function(r){return Si.CUMULATIVE};var Ap=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())})},wp=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}}},Wv=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},Kk=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))},jv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Gv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:Vv,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 Ap(this,void 0,void 0,function(){var t,n,o,i,a,s;return wp(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(Kk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Wv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Wv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(pp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(pp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var Yk=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}}},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},Jk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Cp=function(r){Yk(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,Pn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof mp?(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,Jk(["PeriodicExportingMetricReader: metrics collection errors"],Xk(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,Iv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ts.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),es(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}(jv);Me();Me();function fc(){return"unknown_service:"+process.argv0}var On=function(){return On=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},On.apply(this,arguments)},Qk=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())})},Zk=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}}},e0=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[Mv]=fc(),e[Qa]=go[Qa],e[Ja]=go[Ja],e[Za]=go[Za],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 Qk(this,void 0,void 0,function(){return Zk(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=On(On({},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=e0(a,2),l=c[0],u=c[1];return On(On(On(On({},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 $v=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var 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)}}(),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=di.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,ho(Date.now()))},r}();var qv=function(r){So(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 Kv=function(r){So(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 Yv=function(r){So(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 Xv=function(r){So(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 Jv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Qv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function ns(r){return r instanceof bc}var eA=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 Yv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Kv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new qv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Qv(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 Jv(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 Zv(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 t0=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)}}(),tA=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}}},r0=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 tA(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 tA(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){t0(e,r);function e(){return r.call(this,nc)||this}return e}(r0);var n0=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=n0(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 m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,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 Rp=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.")},rA=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===Si.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=o0(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=Rp(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=Rp(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=rA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,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=Rp(e.keys()),s=a.next();!s.done;s=a.next()){var c=rA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function o0(r){return Array.from(r.entries())}var i0=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)}}(),a0=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},nA=function(r){i0(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=a0(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);Me();function xp(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+`'
|
|
@@ -4235,9 +4235,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!bo(o.url,this.logger)){
|
|
|
4235
4235
|
`),tokenLength:d}),u=[],d=0,m=g.length?[g[g.length-1].id]:[],p=!1);let h=c[l],f=wr(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(eR)).map(K=>K&&K.length>=3?{tagName:K[1],id:K[2]}:void 0).filter(K=>!!K),A=Array.from(h.matchAll($B)).map(K=>K&&(K[2]||K[4])).filter(K=>!!K);A.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let K of x)m.push(K.id),g.push(K);for(let K of A){let j=g[g.length-1];j&&j.tagName===K&&g.pop()}let w=g.some(K=>KB.includes(K.tagName)),N=c[l+1]??"",G=wr(N),ye=Array.from(N.matchAll(eR)).map(K=>K&&K.length>2?K[1]:void 0).filter(K=>!!K),Se=ye.some(K=>nR.includes(K)),Ae=ye.some(K=>qB.includes(K));d+G>=i&&(p=!0),d>=n&&(Se&&!w||A.some(K=>YB.includes(K)))&&(p=!0),d>=o&&Ae&&!w&&(p=!0),l++}return u.length&&s.push({ids:m,content:u.join(`
|
|
4236
4236
|
`),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 QB=75e4,ou=3e5;async function wo(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>QB)try{let m=nu({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await ez({...r,tokenLimit:ou-1e4,chunks:m.chunks}),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*Dn),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 m=nu({serializedTree:u,options:rR,logger:i}),g=JB();l=await k(ZB({...r,chunks:m.chunks,callId:g}),{milliseconds:12e3,signal:c}),u=l.serialize();let p=wr(u);i.info({oldTokens:d,newTokens:p,langfuseCallId:g},"Filtered page using AI chunk ranking"),d=p}else{let m=nu({serializedTree:u,options:tR,logger:i});l=await k(tz({...r,chunkResult:m,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(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*Dn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function ZB({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((m,g)=>{l.indices.includes(g)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function ez(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,p)=>g+p.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 tz(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 Og(r,e){if(!r.description)throw new R("UserConfigurationError","Cannot locate element with empty description");return gr({action:async()=>rz(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function rz(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:m,browser:g,localCodeEvalTools:p,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await is({orgId:m,s:E,context:n,localTools:p,signal:f,logger:l})),a&&(E=oz(E,a));let{serializedTree:x,tree:v}=await jr(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),A,_=Date.now(),w;for(;!A&&Date.now()-_<3e3;){f.throwIfAborted();try{A=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Q){w=Q}}if(!A)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: ${w?.message}`);let N=x,G=!1,ye=`data:image/jpeg;base64,${A.toString("base64")}`;N=await wo({type:"locator",description:E,screenshot:ye,serializedTree:x,options:{aiPageFiltering:c},tree:v,fixtures:{generator:h,signal:f,logger:l,orgId:m}}),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 fn(`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 nz=["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:"],oR="<select> element:",iR="text input or contenteditable element:",aR="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:",sR="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:",Ig=[oR,iR,aR,sR,...nz];function lR(r,e){if(r===e)return!0;for(let t of Ig){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Ig.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Ig.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function oz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${oR} ${r}`;case"TYPE":return`${iR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${aR}
|
|
4237
4237
|
${r}`;case"ELEMENT_CHECK":return`${sR}
|
|
4238
|
-
${r}`;default:return r}}var iz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iz}){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(),m,g,p;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(m=await gr({action:async()=>{let b=await cR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(g=b,uR({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}),m?.success){m?.updatedMemory&&as(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),p=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(!m?.success)try{m=await gr({action:async()=>uR({command:r,state:await cR(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(),p=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&as(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw p&&(f+=` Latest result: ${p.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function cR(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 uR({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:m}=t,g={type:"ASSERTION"},{serializedTree:p,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",v=p;x!=="VISION_ONLY"&&(v=await wo({type:"assertion",serializedTree:p,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),v!==p&&(g.ragUsed=!0),g.pageState=v);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:fe(l)});return(w.result||i)&&w.relevantElements&&(g.relevantElementsSerialized=w.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await az(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function az(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 sz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function dR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lz(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 lz(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(cz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>uz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uz(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 is({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(m)>sz)throw new au;s.throwIfAborted();let p;try{p=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,${p.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as pR}from"lodash-es";async function gR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Wh(e.cache)?e.cache:void 0,a=i(),s=pR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=jA(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,m=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Ns(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let p=i();return d.success&&p?.target&&!g&&(p.target=Fp(p.target),p.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!pn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=pR(r);try{let{elementInteractedDisplayString:m,result:g,thoughts:p}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ca(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:m,thoughts:p},u=!0,g.success||(s.warn({aiThoughts:p,elementString:m,err:g.err},"Element check found an element but failed"),l={...g,thoughts:p}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await mz(r,e.assertion)}async function mz(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 hR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pz}from"jimp";async function ms(r,e){let t=await r.screenshot(e),n=await pz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as fR}from"jimp";import Lg from"jpeg-js";import gz from"pixelmatch";async function SR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!pn(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=>ms(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ms(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 fR.fromBuffer(l.buffer),m={width:l.width,height:l.height},g=await fR.fromBuffer(u.buffer),p={width:u.width,height:u.height},h,f=m.width*m.height,E=p.width*p.height,b=Math.abs(m.height-p.height),x=Math.abs(m.width-p.width);if(f>E){let W=d.cover({w:p.width,h:p.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=p.width,l.height=p.height}else if(E>f){let W=g.cover({w:m.width,h:m.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,w=gz(Lg.decode(u.buffer).data,Lg.decode(l.buffer).data,v.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=w>A*100,G=`Visual diff of ${w.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${A*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:Lg.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hz=3e4;function fz(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??hz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),c;if(Ai(r.url)&&(c=r.url),t&&wi(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 p=fz(r);return await n(g,{headers:{...p.contentType?{"Content-Type":p.contentType}:{},...i},method:r.method,body:p.content})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{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(p){g=`Failed to read response body: ${p}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,p)=>{d[p]=g});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Sz=5e3;async function bR({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),Sz);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(yR,{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(yR,{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 yR({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 yz=3e4;async function ER({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??yz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Ai(r.url)&&(s=r.url),t&&wi(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,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}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}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=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 wo({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}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{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")}`,m=await wo({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:m,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(p){throw new R("InternalWebAgentError",`Error generating command: ${p instanceof Error?p.message:p}`,{errOptions:{cause:p}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Og({...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 m=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async p=>p,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(p=>p.result)),m=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",g=u.map((p,h)=>p.thoughts?`${m(o[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(p=>p.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&&dd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(gd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(hd(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:m,source:g}=s,p=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=TR(e.cache);if((!b||l)&&!Yu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(p.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&&!lR(o.elementDescriptor,b.inputDescription)&&(p.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=A=>!!A&&Ns(A),v=!0;if(!x(b)){v=!1,p.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await dR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:p,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await Og({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:p},this.getControllerFixtures(t))}catch(N){if(N instanceof fn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:p,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,p),w=await a(_);return Dc({cmd:c,key:d,newTarget:A.target,logger:p,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=fe(p)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:p,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let _=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,p),w=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.2"]),Dc({cmd:c,key:d,newTarget:b,logger:p,updatedWithAI:!1}),v){let N=A.decisions.filter(G=>G.matched);if(N.length!==1)p.warn({decisions:A.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:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let _="unknown";A instanceof Pr&&A.cacheMissReason&&(_=A.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.2",`missReason:${_}`]);let w=!1;if((A instanceof Ir||dd(A)||gd(A)||hd(A)||Jf(A)||md(A)||Qf(A))&&(w=!0),A instanceof R&&!w)throw p.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){p.info({err:A},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Bh(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",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return ms(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&&ff(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:te}),this.options?.autoFollowNewTabs&&await ZC({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:()=>ng(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=Qb(n.schema);if(f)throw new R("UserConfigurationError",f)}let p=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:p,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(!Ai(n.url)&&!wi(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:p=>this.browser.click(p,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 p,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:v=>this.browser.hover(v),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=b,h=x}let f=this.browser.getViewport()?.height??En.height,E=this.browser.getViewport()?.width??En.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:p,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 p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{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 p=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(p,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:p,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:p[0],thoughts:h}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(p)||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(p,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async A=>this.browser.mouseDrag(p,h,f,A.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=v}else await this.browser.mouseDrag(p,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!pn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ca(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=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(p)}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:p}}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 p=this.browser.url(),h,f,E=TR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:v,thoughts:A}=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:ca(n)}});h=v,f=A}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(p,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:p,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:p,thoughts:h}}case"FOCUS":{if(!pn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"BLUR":{if(n.target&&!pn(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:p,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:p,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 m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Hc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;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 p=new Ez,h=bz(fetch,p),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:ul(p,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ER({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,p=await Hw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let h;try{h=yy.optional().parse(p)}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 p=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hR(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&&as(n,E.cache?.memory.traces,a)}}let f=await gR({command:n,tracer:t,timeoutMs:p,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 p=await gr({action:async()=>bR({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new kn(n.requestMatcher),h=this.browser.registerRequestListener(p);return this.registeredListeners[n.key]=h.then(async f=>await cg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(p,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new kn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>p.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 p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new kn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new kn(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=Uy.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(p=>{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 Tz}from"lodash-es";import RR from"truncate-json";var vR=1e3,AR=5e6,vz=5*1024*1024;function xR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=RR(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":wR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":wR(n),xR(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 wR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function CR(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=Tz(r);if(xR(t,e),t.length>vR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,vR);let n=CR(t,e);if(n.length>AR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>AR;)t.pop(),n=CR(t,e);let{jsonString:o}=RR(n,vz);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 Az}from"async_hooks";var ps=new Az;function wz(r){ps.enterWith({activeTracers:[r]})}function Cz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Rz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ps.run({activeTracers:n},e)}var an={globalAls:ps,initializeRootTracerContext:wz,withChildTracer:Cz,withChildTracerAsync:Rz};var Co=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 re(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Co}async function MR(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=xz(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 xz(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 $z}from"fs";import{tmpdir as qz}from"os";import NR from"path";import{diff as Wz}from"deep-object-diff";import{cloneDeep as jz}from"lodash-es";import IR from"fontoxpath";import Mz from"@prettier/plugin-xml";import _z from"prettier";import{DOMParser as Pz,XMLSerializer as Iz}from"slimdom";var Oz=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 gs(r){let e=r.toLowerCase();return e.endsWith("webview")||Oz.has(e)}function Lz(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 Nz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Dz=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"]),kz=new Set(["text","hint"]),Uz=new Set(["live-region","drawing-order"]),Fz=new Set(["displayed","enabled"]);function Bz(r,e){let t={};for(let[n,o]of Object.entries(e))Nz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Dz.has(n)&&o==="false"||kz.has(n)&&o===""||Fz.has(n)&&o==="true"||Uz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function _R(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 m of e.attributes){let g=m.name,p=m.value;p!=null&&(l[g]=String(p))}let u=Bz(e.tagName,l);for(let[m,g]of Object.entries(u))t.setAttribute(m,g);if(o.set(c,e),i.set(c,t),gs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4238
|
+
${r}`;default:return r}}var iz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iz}){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(),m,g,p;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(m=await gr({action:async()=>{let b=await cR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(g=b,uR({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}),m?.success){m?.updatedMemory&&as(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),p=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(!m?.success)try{m=await gr({action:async()=>uR({command:r,state:await cR(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(),p=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&as(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw p&&(f+=` Latest result: ${p.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function cR(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 uR({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:m}=t,g={type:"ASSERTION"},{serializedTree:p,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",v=p;x!=="VISION_ONLY"&&(v=await wo({type:"assertion",serializedTree:p,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),v!==p&&(g.ragUsed=!0),g.pageState=v);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:fe(l)});return(w.result||i)&&w.relevantElements&&(g.relevantElementsSerialized=w.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await az(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function az(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 sz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function dR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lz(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 lz(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(cz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>uz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uz(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 is({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(m)>sz)throw new au;s.throwIfAborted();let p;try{p=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,${p.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as pR}from"lodash-es";async function gR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Wh(e.cache)?e.cache:void 0,a=i(),s=pR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=jA(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,m=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Ns(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let p=i();return d.success&&p?.target&&!g&&(p.target=Fp(p.target),p.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!pn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=pR(r);try{let{elementInteractedDisplayString:m,result:g,thoughts:p}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ca(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:m,thoughts:p},u=!0,g.success||(s.warn({aiThoughts:p,elementString:m,err:g.err},"Element check found an element but failed"),l={...g,thoughts:p}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await mz(r,e.assertion)}async function mz(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 hR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pz}from"jimp";async function ms(r,e){let t=await r.screenshot(e),n=await pz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as fR}from"jimp";import Lg from"jpeg-js";import gz from"pixelmatch";async function SR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!pn(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=>ms(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ms(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 fR.fromBuffer(l.buffer),m={width:l.width,height:l.height},g=await fR.fromBuffer(u.buffer),p={width:u.width,height:u.height},h,f=m.width*m.height,E=p.width*p.height,b=Math.abs(m.height-p.height),x=Math.abs(m.width-p.width);if(f>E){let W=d.cover({w:p.width,h:p.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=p.width,l.height=p.height}else if(E>f){let W=g.cover({w:m.width,h:m.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,w=gz(Lg.decode(u.buffer).data,Lg.decode(l.buffer).data,v.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=w>A*100,G=`Visual diff of ${w.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${A*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:Lg.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hz=3e4;function fz(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??hz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),c;if(Ai(r.url)&&(c=r.url),t&&wi(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 p=fz(r);return await n(g,{headers:{...p.contentType?{"Content-Type":p.contentType}:{},...i},method:r.method,body:p.content})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{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(p){g=`Failed to read response body: ${p}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,p)=>{d[p]=g});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Sz=5e3;async function bR({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),Sz);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(yR,{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(yR,{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 yR({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 yz=3e4;async function ER({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??yz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Ai(r.url)&&(s=r.url),t&&wi(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,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}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}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=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 wo({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}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{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")}`,m=await wo({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:m,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(p){throw new R("InternalWebAgentError",`Error generating command: ${p instanceof Error?p.message:p}`,{errOptions:{cause:p}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Og({...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 m=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async p=>p,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(p=>p.result)),m=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",g=u.map((p,h)=>p.thoughts?`${m(o[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(p=>p.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&&dd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(gd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(hd(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:m,source:g}=s,p=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=TR(e.cache);if((!b||l)&&!Yu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(p.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&&!lR(o.elementDescriptor,b.inputDescription)&&(p.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=A=>!!A&&Ns(A),v=!0;if(!x(b)){v=!1,p.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await dR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:p,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await Og({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:p},this.getControllerFixtures(t))}catch(N){if(N instanceof fn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:p,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,p),w=await a(_);return Dc({cmd:c,key:d,newTarget:A.target,logger:p,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=fe(p)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:p,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let _=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,p),w=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.3"]),Dc({cmd:c,key:d,newTarget:b,logger:p,updatedWithAI:!1}),v){let N=A.decisions.filter(G=>G.matched);if(N.length!==1)p.warn({decisions:A.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:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let _="unknown";A instanceof Pr&&A.cacheMissReason&&(_=A.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.3",`missReason:${_}`]);let w=!1;if((A instanceof Ir||dd(A)||gd(A)||hd(A)||Jf(A)||md(A)||Qf(A))&&(w=!0),A instanceof R&&!w)throw p.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){p.info({err:A},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Bh(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",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return ms(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&&ff(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:te}),this.options?.autoFollowNewTabs&&await ZC({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:()=>ng(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=Qb(n.schema);if(f)throw new R("UserConfigurationError",f)}let p=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:p,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(!Ai(n.url)&&!wi(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:p=>this.browser.click(p,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 p,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:v=>this.browser.hover(v),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=b,h=x}let f=this.browser.getViewport()?.height??En.height,E=this.browser.getViewport()?.width??En.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:p,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 p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{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 p=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(p,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:p,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:p[0],thoughts:h}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(p)||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(p,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async A=>this.browser.mouseDrag(p,h,f,A.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=v}else await this.browser.mouseDrag(p,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!pn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ca(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=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(p)}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:p}}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 p=this.browser.url(),h,f,E=TR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:v,thoughts:A}=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:ca(n)}});h=v,f=A}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(p,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:p,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:p,thoughts:h}}case"FOCUS":{if(!pn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"BLUR":{if(n.target&&!pn(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:p,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:p,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 m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Hc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;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 p=new Ez,h=bz(fetch,p),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:ul(p,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ER({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,p=await Hw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let h;try{h=yy.optional().parse(p)}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 p=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hR(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&&as(n,E.cache?.memory.traces,a)}}let f=await gR({command:n,tracer:t,timeoutMs:p,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 p=await gr({action:async()=>bR({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new kn(n.requestMatcher),h=this.browser.registerRequestListener(p);return this.registeredListeners[n.key]=h.then(async f=>await cg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(p,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new kn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>p.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 p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new kn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new kn(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=Uy.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(p=>{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 Tz}from"lodash-es";import RR from"truncate-json";var vR=1e3,AR=5e6,vz=5*1024*1024;function xR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=RR(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":wR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":wR(n),xR(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 wR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function CR(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=Tz(r);if(xR(t,e),t.length>vR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,vR);let n=CR(t,e);if(n.length>AR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>AR;)t.pop(),n=CR(t,e);let{jsonString:o}=RR(n,vz);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 Az}from"async_hooks";var ps=new Az;function wz(r){ps.enterWith({activeTracers:[r]})}function Cz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Rz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ps.run({activeTracers:n},e)}var an={globalAls:ps,initializeRootTracerContext:wz,withChildTracer:Cz,withChildTracerAsync:Rz};var Co=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 re(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Co}async function MR(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=xz(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 xz(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 $z}from"fs";import{tmpdir as qz}from"os";import NR from"path";import{diff as Wz}from"deep-object-diff";import{cloneDeep as jz}from"lodash-es";import IR from"fontoxpath";import Mz from"@prettier/plugin-xml";import _z from"prettier";import{DOMParser as Pz,XMLSerializer as Iz}from"slimdom";var Oz=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 gs(r){let e=r.toLowerCase();return e.endsWith("webview")||Oz.has(e)}function Lz(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 Nz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Dz=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"]),kz=new Set(["text","hint"]),Uz=new Set(["live-region","drawing-order"]),Fz=new Set(["displayed","enabled"]);function Bz(r,e){let t={};for(let[n,o]of Object.entries(e))Nz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Dz.has(n)&&o==="false"||kz.has(n)&&o===""||Fz.has(n)&&o==="true"||Uz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function _R(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 m of e.attributes){let g=m.name,p=m.value;p!=null&&(l[g]=String(p))}let u=Bz(e.tagName,l);for(let[m,g]of Object.entries(u))t.setAttribute(m,g);if(o.set(c,e),i.set(c,t),gs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4239
4239
|
${m}
|
|
4240
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let g=m.nodeType;if(g===3){let p=m.nodeValue;p&&p.trim().length>0&&t.appendChild(n.createTextNode(p));continue}if(g===1){let p=m;if(!Gz(p,s?.viewportBounds))continue;let h=n.createElement(Lz(p.tagName));_R(r,p,h),t.appendChild(h)}}}function zz(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;_R(a,e,s);let c=new Iz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function PR(r,e){let t=new Pz,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}=zz(t,i,o,e);return{xml:await _z.format(c,{parser:"xml",plugins:[Mz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function Hz(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 Hz(t)}function Ng(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 Ro(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 Gz(r,e){if(!e)return!0;let t=Ro(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 Dg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function LR({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=Ro(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=Ng(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Dg(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:p})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:p.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Dg(h,p.attributesRequired),requiredBounds:p.boundsRequired}}:void 0}).filter(g=>!!g));let m;return gs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},{target:m,resolvedNode:n}}var OR=(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=Ro(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 mu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=re();if(e.type==="WEBVIEW")return Vz(e,r);let a=IR.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 m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of m){let p=IR.evaluateXPathToFirstNode(g.xPath,o);if(!p)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);OR(p,g.requirements)}})}let s=Ro(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");OR(a,e.requirements,e.bounds);let c;for(let[m,g]of n.idToElement.entries())if(g===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Ng(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function Vz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=re(),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 Pi(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ml.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function pu(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 at=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}),m=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:m}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let m=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=m,m})}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 Sn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=LR({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 m=await this.stateManager.getActiveWebview();if(!m||!m.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await m.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:m.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=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,m=e.retriesWithAI??1,g=!1,p=jz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,p=void 0),s&&(g=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,p=void 0),!p){m--,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 Pi({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(v,A)=>{let{resolvedTarget:_}=await mu({target:p,domState:f,stateManager:this.stateManager,logger:this.logger}),w=pu(_),N=Wz(p,w);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),A.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:w}}),x=await t(E);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.2"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.2"]),this.throwIfAborted(),m>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:m-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 Kz(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 Ii=class extends at{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,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}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=NR.join(qz(),"momentic","downloads"),s=NR.join(a,this.orgId,i);return $z(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 re().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=re(),n=Kz(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 at{async doPress({keycode:e,longPress:t}){await re().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var DR=25,gu=class extends at{async doType(e){let t=re();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 re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??DR};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 Ii(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=re(),n=e.keyPressDelayMs??DR;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=re();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 kR=.8,Hn=.2,Yz=$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()})}),Oi=class extends at{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Yz.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=re();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=>re().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),m=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+m/2},p=(s?m:d)*(t.viewportPercent??kR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=p,await o.browser.mouseDragUsingVisualCoordinates(s?0:p,s?p:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=kR,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 GR}from"child_process";import Qz from"pixelmatch";import{_android as Zz,chromium as e1}from"playwright";import{PNG as VR}from"pngjs";import{z as Ge}from"zod";var UR=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()}),FR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),BR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),zR=Ge.array(BR.extend({info:UR.optional(),pages:Ge.array(FR).optional()})),c_e=Ge.array(BR.extend({info:UR,pages:Ge.array(FR)}));function kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=VR.sync.read(n),a=VR.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 Qz(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,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let p=(await Zz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(p.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(p.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.`);m=p[0]}return new r({driver:e,context:d,logger:t,device:m,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=re(),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 re().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(kg(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");(gs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Ro(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await re().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 re().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 PR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await re().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 re().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=GR(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 re().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=zR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4240
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let g=m.nodeType;if(g===3){let p=m.nodeValue;p&&p.trim().length>0&&t.appendChild(n.createTextNode(p));continue}if(g===1){let p=m;if(!Gz(p,s?.viewportBounds))continue;let h=n.createElement(Lz(p.tagName));_R(r,p,h),t.appendChild(h)}}}function zz(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;_R(a,e,s);let c=new Iz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function PR(r,e){let t=new Pz,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}=zz(t,i,o,e);return{xml:await _z.format(c,{parser:"xml",plugins:[Mz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function Hz(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 Hz(t)}function Ng(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 Ro(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 Gz(r,e){if(!e)return!0;let t=Ro(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 Dg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function LR({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=Ro(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=Ng(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Dg(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:p})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:p.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Dg(h,p.attributesRequired),requiredBounds:p.boundsRequired}}:void 0}).filter(g=>!!g));let m;return gs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},{target:m,resolvedNode:n}}var OR=(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=Ro(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 mu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=re();if(e.type==="WEBVIEW")return Vz(e,r);let a=IR.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 m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of m){let p=IR.evaluateXPathToFirstNode(g.xPath,o);if(!p)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);OR(p,g.requirements)}})}let s=Ro(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");OR(a,e.requirements,e.bounds);let c;for(let[m,g]of n.idToElement.entries())if(g===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Ng(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function Vz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=re(),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 Pi(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ml.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function pu(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 at=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}),m=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:m}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let m=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=m,m})}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 Sn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=LR({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 m=await this.stateManager.getActiveWebview();if(!m||!m.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await m.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:m.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=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,m=e.retriesWithAI??1,g=!1,p=jz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,p=void 0),s&&(g=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,p=void 0),!p){m--,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 Pi({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(v,A)=>{let{resolvedTarget:_}=await mu({target:p,domState:f,stateManager:this.stateManager,logger:this.logger}),w=pu(_),N=Wz(p,w);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),A.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:w}}),x=await t(E);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.3"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.3"]),this.throwIfAborted(),m>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:m-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 Kz(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 Ii=class extends at{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,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}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=NR.join(qz(),"momentic","downloads"),s=NR.join(a,this.orgId,i);return $z(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 re().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=re(),n=Kz(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 at{async doPress({keycode:e,longPress:t}){await re().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var DR=25,gu=class extends at{async doType(e){let t=re();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 re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??DR};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 Ii(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=re(),n=e.keyPressDelayMs??DR;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=re();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 kR=.8,Hn=.2,Yz=$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()})}),Oi=class extends at{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Yz.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=re();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=>re().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),m=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+m/2},p=(s?m:d)*(t.viewportPercent??kR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=p,await o.browser.mouseDragUsingVisualCoordinates(s?0:p,s?p:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=kR,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 GR}from"child_process";import Qz from"pixelmatch";import{_android as Zz,chromium as e1}from"playwright";import{PNG as VR}from"pngjs";import{z as Ge}from"zod";var UR=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()}),FR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),BR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),zR=Ge.array(BR.extend({info:UR.optional(),pages:Ge.array(FR).optional()})),c_e=Ge.array(BR.extend({info:UR,pages:Ge.array(FR)}));function kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=VR.sync.read(n),a=VR.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 Qz(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,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let p=(await Zz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(p.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(p.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.`);m=p[0]}return new r({driver:e,context:d,logger:t,device:m,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=re(),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 re().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(kg(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");(gs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Ro(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await re().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 re().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 PR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await re().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 re().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=GR(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 re().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=zR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4241
4241
|
${o}
|
|
4242
4242
|
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 re().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await ds.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 re().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 re().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 e1.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=GR(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 WR=5,jR=.8,t1=1,fu=class extends Oi{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??jR,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=re(),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=re();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=re(),a=e.scrollStepPercent??jR,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 mu({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 Sn)return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),Pi({command:e,updatedCache:pu(a),updatedWithAI:!0}),{success:!0,message:s}):(Pi({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=re(),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<WR;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),m=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(m)return m;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=r1(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 ${WR} 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 re().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=re(),s,c,l;if(t.type==="CUSTOM_COORDINATES")s=t.startX,c=t.startY,l=t.deltaPixels;else{let m=(await this.resolveContainer(t,n)).bounds,g=m.height*i,p=this.calculateSwipeCoordinates({containerBounds:m,direction:o,desiredDelta:g});s=p.startX,c=p.startY,l=p.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 m=0;for(let g=0;g<u;g++){this.throwIfAborted();let p=Math.abs(e)-m,h=Math.min(l,p);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:this.invertDirection(o)}),m+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=t1,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,p=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:g});s=p.startX,c=p.startY,l=p.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=kg(a,u),m=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:m,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),m}};function r1(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as n1}from"crypto";import fs from"fs";import{tmpdir as o1}from"os";import Li from"path";var Su=class extends at{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 ${Li.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(fs.existsSync(n))o=n;else if(fs.existsSync(Li.join("/",n)))o=Li.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{fs.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=Li.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{fs.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=Li.extname(t)||".apk",o=Li.join(o1(),`momentic-apk-${n1()}${n}`);return fs.writeFileSync(o,e),o}};import{existsSync as i1,readFileSync as a1}from"fs";import s1 from"zod";var l1=s1.string().url();async function $R(r){if(l1.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(!i1(r))throw new Error(`File does not exist at path: ${r}`);return a1(r).toString("base64")}import{cloneDeep as qR}from"lodash-es";var c1=5e3,u1={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)},KR=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=KR(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()},d1={getTextContent:async r=>KR(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")}},yu=class extends at{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),c1);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=re();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 Sn||i instanceof fn)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=re(),{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:d1,trace:s}))}async executeWebviewElementCheck(e,t){let n=re(),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:u1,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 m1=5e3,bu=class extends at{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),m1);else return c}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await re().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 ${Dp(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 Eu=class extends at{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(`
|
|
4243
4243
|
`).filter(i=>!!i).length>1)throw new Error(`Multiple packages found for ${t}`);try{await this.stateManager.executeRawADBCommand(`uninstall ${t}`)}catch(i){throw new Error(`Failed to uninstall package ${t}: ${i}`)}}};var Ni=class r extends at{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c,limbarClient:l,playwrightDevice:u}){let d={controller:s},m=await hu.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),g=new r({driver:e,generator:t,stateManager:m,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await g.initializeSettings(),g}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${g1.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Oc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Lc(e.command,n)}}async executeCommandHelper({command:e}){let t=re();switch(e.type){case"TAP":return new Ii(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new gu(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Bc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await q(i,this.abortSignal),c=Date.now();try{let d="",m="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,m=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async p=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:fe(this.logger)});return p.result={thoughts:h.thoughts,result:h.result},h});if(g.result)return{success:g.result,message:g.thoughts};{let p=`AssertionFailureError: ${g.thoughts}`;u=new Error(p)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Oi(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new bu(this.constructPerformerParams()).executeScreenCheck(e);case"ELEMENT_CHECK":return await new yu(this.constructPerformerParams()).executeElementCheck(e);case"SCROLL_TO":return new fu(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n=await zr({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new h1,i=p1(fetch,o),a=Date.now(),s=await su({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=ul(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new zn(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
@@ -4278,7 +4278,7 @@ Momentic users value the following:
|
|
|
4278
4278
|
${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 bH(r){let e=SH(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${ki}`)),n=AbortSignal.timeout(2e3),o;try{o=await dH(t,{absolute:!1,cwd:jg(),dotRelative:!1,maxDepth:Wg,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 ${$g} is misconfigured.`),a}let i=[];for(let a of o){let s=Mo.join(jg(),a),c=qg(s);c&&i.push({configFilePath:s,config:c,rootDir:bx(s)})}return i}async function EH(r){if(r){r=Mo.resolve(r);let t=qg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Mo.dirname(r)}]}if(sH($g)){let t=await bH($g);if(t)return t}return yH()}function vx(r,e){let t=Ex.stringify(r);uH(e,t)}import{z as Kg}from"zod";var Ax="test-results";var CDe=Kg.object({width:Kg.number(),height:Kg.number()});import{execFile as TH}from"node:child_process";import{promisify as vH}from"node:util";import AH from"simple-git";var Le=AH(),wx=vH(TH);async function wH(r){let e=await Ne(r,Le.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4279
4279
|
`)){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 CH(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 wx("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 wx("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function RH(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return CH(r,e,t);if(o)return}catch{}}function Ru(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 xH(){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 MH(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 _H(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 PH(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?Ru(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 IH(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?Ru(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 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["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ru(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 LH(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),wH(r)]),d=l?await Ne(r,Le.show(["--no-patch","--format=%ci",l])):void 0,m=i?.includes("github.com"),g=i?.includes("gitlab.com"),p=i?Ru(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await RH(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:m?p:void 0,gitlabProjectPath:g?p:void 0,pipelineId:void 0}}async function NH(){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 DH(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Es(r,e){let t=xH();if(!t)return LH(r,e);switch(t){case"GithubActions":return MH(r);case"GitlabCI":return _H(r);case"CircleCI":return PH(r);case"Buildkite":return IH(r);case"AzureDevOps":return OH(r);case"GCPCloudBuild":return NH()}}async function kH(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 UH(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 FH(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await UH(r,e,n,o,t)}else if(t.gitlabProjectPath)return await kH(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ui(r,e,t){let n=await DH(t),o=await Es(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 FH(r,e,i);return{...n,...o,...a}}import{diff as Cx}from"deep-object-diff";import Vn from"fs";import{cloneDeep as BH}from"lodash-es";import xu from"path";import{v4 as zH}from"uuid";import Ts from"yaml";function Rx({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=Ts.parse(a),c={...s,...r,schemaVersion:e},l=yo({fileType:Ie.MOBILE_MODULE,...Aa.parse(c),steps:ir.array().parse(r.steps)}),u=Cx(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=Ts.stringify(l);Vn.writeFileSync(i,d,"utf-8"),Gn(i,n.config)}function xx({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=vs(i,o),s={...a,...e},c=yo({fileType:Ie.MOBILE_MODULE,...yl.parse(s)}),l=Cx(c,a);if(l&&Object.keys(l).length===0)return;let u=Ts.stringify(c);Vn.writeFileSync(i,u,"utf-8");let d;if(e.name){let m=`${Xr(e.name)}.module.yaml`;if(d=xu.join(xu.dirname(i),m),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 Mx({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Xr(r),s=xu.join(o,`${a}.module.yaml`),c=zH(),{stepsToSave:l}=await Ln({steps:n}),u={schemaVersion:yn,moduleId:c,description:e,enabled:t},d={fileType:Ie.MOBILE_MODULE,...u,steps:l},m=Ts.stringify(Dy.parse(d));return Vn.writeFileSync(s,m,"utf-8"),Gn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function vs(r,e){let t=Vn.readFileSync(r,"utf-8"),n=Ts.parse(t);try{return{...yl.parse(n),name:xu.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 Yg(r,e,t,n){let o=vs(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 vs(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]=BH(a)),a}async function _x(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Yg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as HH}from"crypto";import _o from"fs";import Jg from"path";import Mu from"yaml";import Xg from"zod";function Px({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Xr(r)}.test.yaml`,s=Jg.join(o,a);if(_o.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:Ie.MOBILE_TEST,id:HH(),description:e,schemaVersion:Zn,settings:n,steps:t},l=Mu.stringify(c);return _o.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function GH(r){if(!_o.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=_o.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4280
4280
|
`),t=Mu.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function _u(r,e,t){let n=GH(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 vw({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 vs(c,e)}});return{...o,steps:i.steps}}async function Ix({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i,schemaVersion:a}){let s=Jg.isAbsolute(r)?r:Jg.join(n,r);if(!_o.existsSync(s))throw new Error(`Test file not found: ${s}`);let c=_o.readFileSync(s,"utf-8").replace(/\r\n|\r/g,`
|
|
4281
|
-
`),l=Mu.parse(c),u=nm.extend({steps:Xg.record(Xg.string(),Xg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Ie.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Ln({steps:e}));let m={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Mu.stringify(m);for(let p of d?.moduleUpdates??[])Rx({content:p,schemaVersion:Zn,momenticFiles:i,project:o});_o.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as VH}from"crypto";import Wn from"fs";import Fi from"path";var Ox=new Set([".DS_Store","__MACOSX"]),Lx={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 WH(r,e,t){if(Lx[t]){let i=Lx[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 Qg=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 Nx(r,e){try{let t=Fi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new Qg(r,e)}}function Dx(r,e,t){let n=VH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ox.has(c)).map(c=>Fi.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={...Nx(t,i[0]),id:n};for(let c of i){let l=Fi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Nx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let g=m;a[g]=WH(a,u,g)}let d=Wn.readdirSync(l);for(let m of d){if(Ox.has(m))continue;let g=Fi.join(l,m),p=Fi.join(e,"runs",m);Wn.cpSync(g,p,{recursive:!0})}}let s=Fi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Ux from"adm-zip";import oh from"fs";import{z as QH}from"zod";var U="v1",Zg="mobile-cli",Po="0.9.2";var jH=9e4,$H=3,qH=1500,KH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function YH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var eh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Po&&(e[Ml]=Po),Zg&&(e[lb]=Zg),e}async sendRequest(e,t){let{retries:n=$H,requestTimeoutMs:o=jH,initialRetryDelayMs:i=qH,maxRetryDelayMs:a=KH,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(m){u=m;try{s?.(u)}catch{}if(m instanceof Cr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Rn),c===0)throw u;let g=l-c,p=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,p))}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 m=await YH(u);throw new Cr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}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 eh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[sb]:this.mode??""}}};import{createAnthropic as XH}from"@ai-sdk/anthropic";function JH(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ml]:Po??"",...t&&{[ub]:t},...n||{}};return o&&(i[cb]=JSON.stringify(o)),i}var Pu=r=>e=>{let t=JH(r);return XH({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Io=class extends $r{agentConfig;constructor(e,t){let n={...sy,...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 KS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Po,...e},signal:t.abortSignal});return qS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return QH.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 gb.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 fm.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 pb.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 mb.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 fm.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 db.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 Rd.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 hb.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 wd.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 RS.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 xS.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 ud.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ay.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 TS.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 wS.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 AS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return kh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as th}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 Mb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Sb.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 bb.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 Eb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _b.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 Wb.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 Pb.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 VS.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 Ib.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 Ob.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Lb.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 Nb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return qb.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 Ia.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 Ia.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 Em.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 Ia.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 Ia.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 Em.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return th.record(th.string(),th.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Db.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 kb.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 Ub.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 Fb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function rh(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 Iu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Bi=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 Uh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var zi=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 ZH,en as eG}from"@faker-js/faker";var Hi="v1",Gi=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 ZH({locale:eG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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 kx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ou=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kx(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 Vi=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 cy.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 my.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Lu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new nh(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var nh=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=Sm(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&&kp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Ln({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Nu from"path";function tG(r){let e=new Ux,t=Nu.join(r,"metadata.json"),n=Il.parse(JSON.parse(oh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of oh.readdirSync(Nu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Ux(Nu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Nu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Du(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!oh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Ou(e);try{let{runGroupId:i,buffer:a}=tG(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 rG from"adm-zip";import Tt from"fs";import qt from"path";var As=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 ih(qt.join(this.filePath,"runs"),e)}},ih=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 As(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 rG;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 Wu from"fs";import Zx from"body-parser";import AG from"cors";import wG from"dedent";import{Router as aG}from"express";import Ft from"fs";import{globSync as sG}from"glob";import ht from"path";import ku from"fs";import nG from"path";var oG=new $c(30,60*1e3),ch="https://api.momentic.ai",sh,Bx=r=>{ch=r},uh=()=>ch,ws=()=>sh;var Wi,lh,Fx,zx=async r=>{if(sh&&Wi&&Fx)return Wi;let e=new Rr({baseUrl:ch,apiKey:r,logger:C});sh=e;try{let t=await e.getAuthInfo();return Wi=t.orgId,lh=t.userId,Fx=r,Wi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ji=()=>{if(!Wi)throw new Error("Your organization ID is invalid.");return Wi},Uu=()=>{if(!lh)throw new Error("Your user ID is invalid.");return lh};var dh,ah,Hx=(r,e)=>{dh=r,ah?.abort(),ah=new AbortController;let t=ah.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=nG.resolve(r.rootDir,o.envFile);try{if(ku.lstatSync(i).isSymbolicLink())return;ku.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{iG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>dh;function iG({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()&&(oG.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.`),dh=await Promise.resolve(e(n.configFilePath)))};ku.watchFile(o,{persistent:!1},i);let a=()=>{ku.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 Rs=aG();function Cs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function lG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function cG(r,e){let t=Ft.statSync(r),n=lG(r);return um.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})}Rs.post("/",$e(async(r,e,t)=>{let n;try{n=qy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Cs(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=sG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ht.join(o,d);return cG(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Rs.put("/",$e(async(r,e,t)=>{let n;try{n=Ky.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Cs(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)}));Rs.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Yy.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=Cs(n),a=Cs(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)}));Rs.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Xy.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=Cs(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 mh=Rs;import{Router as mG}from"express";import{hostname as uG}from"os";var dG="0.9.2",xs=ai({app:"desktop-server",hostname:uG(),disableConsoleLogs:!0}).child({cliVersion:dG});(async()=>{try{let r=await Es(xs);r.gitBranchName&&xs.addBinding("branch",r.gitBranchName)}catch{}})();var Gx=mG();Gx.get("/",async(r,e)=>{let t=Ve(),n=ws();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ui(xs,n,t);e.status(200).json(o)});var ph=Gx;import CG from"events";import eM,{Router as RG}from"express";import xG from"http";import MG from"path";var Fu=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 Vx=new Fu;import{Router as gG}from"express";import{existsSync as hG}from"fs";import fG from"path";import{hostname as pG}from"os";var gh="0.9.2",vt=ai({app:"mobile-desktop-server",hostname:pG(),disableConsoleLogs:!0}).child({cliVersion:gh});(async()=>{try{let r=await Es(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var hh=gG();hh.get("/",$e(async(r,e)=>{let t=ws();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));hh.post("/upload-url",$e(async(r,e)=>{let t;try{t=rb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ws();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=fG.resolve(t.filePath);if(!hG(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 Wx=hh;import{Router as bG}from"express";import{Router as SG}from"express";import jx from"fs";import yG from"path";var Ms=SG();async function fh(r){return(await _x(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)}Ms.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n);e.status(200).json(o)}));Ms.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 Yg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ms.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=nb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);xx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ms.post("/",$e(async(r,e)=>{let t;try{t=ob.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{la(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=yG.join(n.rootDir,t.folderPath??"");if(!jx.existsSync(a)||!jx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Mx({...t,folder:a,project:n});e.status(201).json(s)}));var $x=Ms;var qx=bG();qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(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 Kx=qx;import{Router as EG}from"express";var Sh=EG();Sh.get("/",$e((r,e)=>{let t=fx(Ve(),vt);e.status(200).json(t)}));Sh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var Yx=Sh;import{Router as TG}from"express";var Xx=TG();Xx.get("/",(r,e)=>{e.status(200).json({userId:Uu(),orgId:ji(),cliVersion:gh??"0.0.0"})});var Jx=Xx;import{Router as vG}from"express";import yh from"path";var Bu=vG();Bu.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=tb.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 Ix({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)}));Bu.post("/",$e((r,e)=>{let t;try{t=eb.parse(r.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});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{la(n)}catch(p){e.status(400).json({error:p.message});return}let s=Ve(),c=yh.join(s.rootDir,...a),{fullPath:l,testId:u}=Px({name:n,description:o,steps:[],settings:i,folder:c}),d=yh.basename(l),m=yh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(g)}));Bu.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 _u(n,vt,i);e.status(200).json(s)}));var Qx=Bu;var zu=class extends zi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return Ss(t,o,C)}};var tM="10mb";async function rM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Bx(n),await zx(t);let u=ji(),d=Uu(),m=r.logger.child({orgId:u,userId:d});Hx(i,w=>bs({configFilePath:w}));let g=eM();g.use(AG()),g.use(Zx.json({limit:tM})),g.use(Zx.urlencoded({extended:!1,limit:tM}));let p=RG();if(p.use("/folders",mh),p.use("/entities",Kx),p.use("/identify",Jx),p.use("/mobile-tests",Qx),p.use("/mobile-modules",$x),p.use("/assets",Wx),p.use("/git",ph),p.use("/environments",Yx),g.use("/api",p),g.use((w,N,G)=>{C.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((w,N,G,W)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=eM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(w),g.use("*",(N,G)=>{G.sendFile(MG.join(o,"index.html"))})}let h=xG.createServer(g),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(N){N.message.includes("EADDRINUSE")?_G(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:uh(),apiKey:t,logger:m},x=new Rr(b),v=Ve(),A={...b,mode:"interactive"},{dispose:_}=gx({baseServer:h,logger:m,authorization:b,globalStateManager:Vx,getOrgId:()=>ji(),androidDriverFactory:async({socket:w,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:w,appiumPort:ye,sessionId:w.id,orgId:ji(),onStatusUpdate:Se=>{w.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async w=>new Vi({baseUrl:uh(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new Io(v.config.ai?.agentConfig,A),browserEnricherFactory:async w=>new Bi(A,new Io(v.config.ai?.agentConfig,A)),storageFactory:async w=>new zu(x,w),cacheStorageFactory:async w=>{let N=await Ui(m,x,v);return Lu({orgId:w,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Gi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:v.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(w){C.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{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))}})}CG.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 _G(r){C.error(wG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4281
|
+
`),l=Mu.parse(c),u=nm.extend({steps:Xg.record(Xg.string(),Xg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Ie.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Ln({steps:e}));let m={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Mu.stringify(m);for(let p of d?.moduleUpdates??[])Rx({content:p,schemaVersion:Zn,momenticFiles:i,project:o});_o.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as VH}from"crypto";import Wn from"fs";import Fi from"path";var Ox=new Set([".DS_Store","__MACOSX"]),Lx={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 WH(r,e,t){if(Lx[t]){let i=Lx[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 Qg=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 Nx(r,e){try{let t=Fi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new Qg(r,e)}}function Dx(r,e,t){let n=VH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ox.has(c)).map(c=>Fi.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={...Nx(t,i[0]),id:n};for(let c of i){let l=Fi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Nx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let g=m;a[g]=WH(a,u,g)}let d=Wn.readdirSync(l);for(let m of d){if(Ox.has(m))continue;let g=Fi.join(l,m),p=Fi.join(e,"runs",m);Wn.cpSync(g,p,{recursive:!0})}}let s=Fi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Ux from"adm-zip";import oh from"fs";import{z as QH}from"zod";var U="v1",Zg="mobile-cli",Po="0.9.3";var jH=9e4,$H=3,qH=1500,KH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function YH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var eh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Po&&(e[Ml]=Po),Zg&&(e[lb]=Zg),e}async sendRequest(e,t){let{retries:n=$H,requestTimeoutMs:o=jH,initialRetryDelayMs:i=qH,maxRetryDelayMs:a=KH,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(m){u=m;try{s?.(u)}catch{}if(m instanceof Cr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Rn),c===0)throw u;let g=l-c,p=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,p))}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 m=await YH(u);throw new Cr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}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 eh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[sb]:this.mode??""}}};import{createAnthropic as XH}from"@ai-sdk/anthropic";function JH(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ml]:Po??"",...t&&{[ub]:t},...n||{}};return o&&(i[cb]=JSON.stringify(o)),i}var Pu=r=>e=>{let t=JH(r);return XH({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Io=class extends $r{agentConfig;constructor(e,t){let n={...sy,...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 KS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Po,...e},signal:t.abortSignal});return qS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return QH.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 gb.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 fm.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 pb.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 mb.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 fm.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 db.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 Rd.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 hb.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 wd.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 RS.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 xS.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 ud.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ay.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 TS.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 wS.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 AS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return kh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as th}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 Mb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Sb.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 bb.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 Eb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _b.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 Wb.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 Pb.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 VS.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 Ib.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 Ob.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Lb.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 Nb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return qb.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 Ia.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 Ia.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 Em.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 Ia.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 Ia.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 Em.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return th.record(th.string(),th.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Db.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 kb.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 Ub.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 Fb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function rh(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 Iu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Bi=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 Uh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var zi=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 ZH,en as eG}from"@faker-js/faker";var Hi="v1",Gi=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 ZH({locale:eG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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(`/${Hi}/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 kx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ou=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kx(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 Vi=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 cy.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 my.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Lu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new nh(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var nh=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=Sm(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&&kp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Ln({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Nu from"path";function tG(r){let e=new Ux,t=Nu.join(r,"metadata.json"),n=Il.parse(JSON.parse(oh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of oh.readdirSync(Nu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Ux(Nu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Nu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Du(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!oh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Ou(e);try{let{runGroupId:i,buffer:a}=tG(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 rG from"adm-zip";import Tt from"fs";import qt from"path";var As=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 ih(qt.join(this.filePath,"runs"),e)}},ih=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 As(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 rG;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 Wu from"fs";import Zx from"body-parser";import AG from"cors";import wG from"dedent";import{Router as aG}from"express";import Ft from"fs";import{globSync as sG}from"glob";import ht from"path";import ku from"fs";import nG from"path";var oG=new $c(30,60*1e3),ch="https://api.momentic.ai",sh,Bx=r=>{ch=r},uh=()=>ch,ws=()=>sh;var Wi,lh,Fx,zx=async r=>{if(sh&&Wi&&Fx)return Wi;let e=new Rr({baseUrl:ch,apiKey:r,logger:C});sh=e;try{let t=await e.getAuthInfo();return Wi=t.orgId,lh=t.userId,Fx=r,Wi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ji=()=>{if(!Wi)throw new Error("Your organization ID is invalid.");return Wi},Uu=()=>{if(!lh)throw new Error("Your user ID is invalid.");return lh};var dh,ah,Hx=(r,e)=>{dh=r,ah?.abort(),ah=new AbortController;let t=ah.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=nG.resolve(r.rootDir,o.envFile);try{if(ku.lstatSync(i).isSymbolicLink())return;ku.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{iG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>dh;function iG({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()&&(oG.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.`),dh=await Promise.resolve(e(n.configFilePath)))};ku.watchFile(o,{persistent:!1},i);let a=()=>{ku.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 Rs=aG();function Cs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function lG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function cG(r,e){let t=Ft.statSync(r),n=lG(r);return um.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})}Rs.post("/",$e(async(r,e,t)=>{let n;try{n=qy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Cs(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=sG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ht.join(o,d);return cG(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Rs.put("/",$e(async(r,e,t)=>{let n;try{n=Ky.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Cs(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)}));Rs.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Yy.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=Cs(n),a=Cs(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)}));Rs.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Xy.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=Cs(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 mh=Rs;import{Router as mG}from"express";import{hostname as uG}from"os";var dG="0.9.3",xs=ai({app:"desktop-server",hostname:uG(),disableConsoleLogs:!0}).child({cliVersion:dG});(async()=>{try{let r=await Es(xs);r.gitBranchName&&xs.addBinding("branch",r.gitBranchName)}catch{}})();var Gx=mG();Gx.get("/",async(r,e)=>{let t=Ve(),n=ws();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ui(xs,n,t);e.status(200).json(o)});var ph=Gx;import CG from"events";import eM,{Router as RG}from"express";import xG from"http";import MG from"path";var Fu=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 Vx=new Fu;import{Router as gG}from"express";import{existsSync as hG}from"fs";import fG from"path";import{hostname as pG}from"os";var gh="0.9.3",vt=ai({app:"mobile-desktop-server",hostname:pG(),disableConsoleLogs:!0}).child({cliVersion:gh});(async()=>{try{let r=await Es(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var hh=gG();hh.get("/",$e(async(r,e)=>{let t=ws();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));hh.post("/upload-url",$e(async(r,e)=>{let t;try{t=rb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ws();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=fG.resolve(t.filePath);if(!hG(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 Wx=hh;import{Router as bG}from"express";import{Router as SG}from"express";import jx from"fs";import yG from"path";var Ms=SG();async function fh(r){return(await _x(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)}Ms.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n);e.status(200).json(o)}));Ms.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 Yg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ms.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=nb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);xx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ms.post("/",$e(async(r,e)=>{let t;try{t=ob.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{la(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=yG.join(n.rootDir,t.folderPath??"");if(!jx.existsSync(a)||!jx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Mx({...t,folder:a,project:n});e.status(201).json(s)}));var $x=Ms;var qx=bG();qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(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 Kx=qx;import{Router as EG}from"express";var Sh=EG();Sh.get("/",$e((r,e)=>{let t=fx(Ve(),vt);e.status(200).json(t)}));Sh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var Yx=Sh;import{Router as TG}from"express";var Xx=TG();Xx.get("/",(r,e)=>{e.status(200).json({userId:Uu(),orgId:ji(),cliVersion:gh??"0.0.0"})});var Jx=Xx;import{Router as vG}from"express";import yh from"path";var Bu=vG();Bu.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=tb.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 Ix({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)}));Bu.post("/",$e((r,e)=>{let t;try{t=eb.parse(r.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});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{la(n)}catch(p){e.status(400).json({error:p.message});return}let s=Ve(),c=yh.join(s.rootDir,...a),{fullPath:l,testId:u}=Px({name:n,description:o,steps:[],settings:i,folder:c}),d=yh.basename(l),m=yh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(g)}));Bu.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 _u(n,vt,i);e.status(200).json(s)}));var Qx=Bu;var zu=class extends zi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return Ss(t,o,C)}};var tM="10mb";async function rM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Bx(n),await zx(t);let u=ji(),d=Uu(),m=r.logger.child({orgId:u,userId:d});Hx(i,w=>bs({configFilePath:w}));let g=eM();g.use(AG()),g.use(Zx.json({limit:tM})),g.use(Zx.urlencoded({extended:!1,limit:tM}));let p=RG();if(p.use("/folders",mh),p.use("/entities",Kx),p.use("/identify",Jx),p.use("/mobile-tests",Qx),p.use("/mobile-modules",$x),p.use("/assets",Wx),p.use("/git",ph),p.use("/environments",Yx),g.use("/api",p),g.use((w,N,G)=>{C.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((w,N,G,W)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=eM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(w),g.use("*",(N,G)=>{G.sendFile(MG.join(o,"index.html"))})}let h=xG.createServer(g),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(N){N.message.includes("EADDRINUSE")?_G(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:uh(),apiKey:t,logger:m},x=new Rr(b),v=Ve(),A={...b,mode:"interactive"},{dispose:_}=gx({baseServer:h,logger:m,authorization:b,globalStateManager:Vx,getOrgId:()=>ji(),androidDriverFactory:async({socket:w,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:w,appiumPort:ye,sessionId:w.id,orgId:ji(),onStatusUpdate:Se=>{w.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async w=>new Vi({baseUrl:uh(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new Io(v.config.ai?.agentConfig,A),browserEnricherFactory:async w=>new Bi(A,new Io(v.config.ai?.agentConfig,A)),storageFactory:async w=>new zu(x,w),cacheStorageFactory:async w=>{let N=await Ui(m,x,v);return Lu({orgId:w,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Gi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:v.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(w){C.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{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))}})}CG.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 _G(r){C.error(wG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4282
4282
|
Using Bash on MacOS or Linux:
|
|
4283
4283
|
lsof -t -i :58888 | xargs kill -9
|
|
4284
4284
|
|
|
@@ -4287,7 +4287,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
|
|
|
4287
4287
|
`)}import KG from"open";import ju from"path";import{fileURLToPath as YG}from"url";import{InvalidArgumentError as bh,Option as ut}from"@commander-js/extra-typings";import{z as PG}from"zod";var nM=58890;function oM(r){let e=parseInt(r,10);if(isNaN(e))throw new bh("Not a number.");return e}var _s=new ut("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new bh("API key is required.");return r}).makeOptionMandatory(),Eh=new ut("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Ps=new ut("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return PG.string().url().parse(r),r}catch{throw new bh("Not a valid URL.")}}),Th=new ut("-y, --yes","Skip all confirmation prompts.").env("CI"),vh=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}),Ah=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}),wh=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}),Ch=new ut("--tag <tag>","Tag identifier for the asset."),iM=new ut("--channel <channel>","Channel name for the asset."),aM=new ut("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),sM=new ut("--env <env>","Environment to run all tests in (overrides test-level configuration)."),lM=new ut("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),cM=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."),uM=new ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(oM),Rh=new ut("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),dM=new ut("--upload-results","Upload test results to Momentic Cloud.").default(!1),xh=new ut("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),mM=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}),pM=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(oM);import{randomUUID as GG}from"crypto";import{existsSync as VG}from"fs";import Mh from"fs";import Hu from"path";import{cwd as OG}from"process";async function gM({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(m=>Mh.existsSync(m)),d=OG();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:
|
|
4288
4288
|
- ${r.join(`
|
|
4289
4289
|
- `)}
|
|
4290
|
-
`),r.forEach(m=>{if(!Mh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let g,p;try{g=Mh.statSync(m),p=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Hu.resolve(m);Object.values(e.mobileTests).filter(f=>p?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(m=>{r.some(g=>m.relativePath.includes(g))&&c.add(m.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=Hu.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Hu.relative(t.rootDir,u),m=await _u(u,a,e),g=Hu.basename(u,".test.yaml");return{id:m.id,name:g,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as LG}from"crypto";import{existsSync as NG,statSync as DG}from"fs";import{cloneDeep as kG}from"lodash-es";import UG from"path";async function hM(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,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:kG(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(m.loggerBindings||{}),p=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<p;h++){let f=new Date,E=await FG({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:p},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.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!==p-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.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 FG(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:m,logger:g,usageTracker:p}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:v,alwaysSaveCache:A,noCache:_,logLevel:w,localAvdId:N,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let W={...a.project.config.emulator,...t.settings?.emulator},ye=G?UG.resolve(G):void 0;if(ye&&(!NG(ye)||!DG(ye).isFile()))throw new Error(`Local APK path "${ye}" does not exist. Provide a valid file path via --local-apk-path.`);let Se=Lu({orgId:u,client:m,gitMetadata:d,regenerateCache:v??!1,alwaysSaveCache:A??!1,noCache:_??!1}),Ae=new zi(m,u),K={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:g,mode:"runner"},j=new Vi(K),le=new Io(b.config.ai?.agentConfig,K),Q=new Bi(K,le),Xe=new Gi({httpClient:m,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,Pe;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.");Pe={avdId:N??W.localEmulatorSettings?.avdId,apkToInstall:ke,apkFilePath:Wt}}else Pe={region:W.region,apkToInstall:ke,osVersion:W.remoteEmulatorSettings?.androidVersion??Iy};let _t=LG(),dt=await _c({apiClient:m,logger:g,driverLogLevel:w,creationOpts:Pe,onStatusUpdate:Os=>{g.debug({status:Os},"Limbar emulator status update")},appiumPort:Bt,orgId:u,sessionId:_t}),qr=await e.startAttempt({emulatorName:dt.emulatorName,runAttemptId:_t}),Oo=g.child(qr.loggerBindings||{}),$u=await Ic({driver:dt.driver,onLogs:Os=>{qr.appendLogs(Os)}}),cn=x||t.settings?.defaultEnv,Nh;cn&&(Nh=Ss(cn,b,Oo).variables);let bM=new ei({variablesFromEnvironment:Nh??{},envName:cn,testName:t.name}),Dh=await Ni.init({driver:dt.driver,generator:j,logger:Oo,limbarClient:dt.limbarClient,playwrightDevice:dt.playwrightDevice,orgId:u,adbPort:dt.adbPort,options:{emulator:W},fixtures:{storage:Ae,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Xe,testContext:bM}}),$;try{$=await wu({containerName:`mobile test ${t.name}`,fixtures:{controller:Dh,logger:Oo,cacheStorage:Se,usageTracker:p},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:qr,callbacks:{}})}finally{await $u(),await dt.cleanup(),await Dh.cleanup()}return await qr.finish({logger:Oo,results:$.results,status:$.status}),$}import{debounce as BG}from"ts-debounce";var Is="0.9.
|
|
4290
|
+
`),r.forEach(m=>{if(!Mh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let g,p;try{g=Mh.statSync(m),p=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Hu.resolve(m);Object.values(e.mobileTests).filter(f=>p?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(m=>{r.some(g=>m.relativePath.includes(g))&&c.add(m.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=Hu.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Hu.relative(t.rootDir,u),m=await _u(u,a,e),g=Hu.basename(u,".test.yaml");return{id:m.id,name:g,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as LG}from"crypto";import{existsSync as NG,statSync as DG}from"fs";import{cloneDeep as kG}from"lodash-es";import UG from"path";async function hM(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,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:kG(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(m.loggerBindings||{}),p=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<p;h++){let f=new Date,E=await FG({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:p},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.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!==p-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.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 FG(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:m,logger:g,usageTracker:p}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:v,alwaysSaveCache:A,noCache:_,logLevel:w,localAvdId:N,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let W={...a.project.config.emulator,...t.settings?.emulator},ye=G?UG.resolve(G):void 0;if(ye&&(!NG(ye)||!DG(ye).isFile()))throw new Error(`Local APK path "${ye}" does not exist. Provide a valid file path via --local-apk-path.`);let Se=Lu({orgId:u,client:m,gitMetadata:d,regenerateCache:v??!1,alwaysSaveCache:A??!1,noCache:_??!1}),Ae=new zi(m,u),K={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:g,mode:"runner"},j=new Vi(K),le=new Io(b.config.ai?.agentConfig,K),Q=new Bi(K,le),Xe=new Gi({httpClient:m,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,Pe;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.");Pe={avdId:N??W.localEmulatorSettings?.avdId,apkToInstall:ke,apkFilePath:Wt}}else Pe={region:W.region,apkToInstall:ke,osVersion:W.remoteEmulatorSettings?.androidVersion??Iy};let _t=LG(),dt=await _c({apiClient:m,logger:g,driverLogLevel:w,creationOpts:Pe,onStatusUpdate:Os=>{g.debug({status:Os},"Limbar emulator status update")},appiumPort:Bt,orgId:u,sessionId:_t}),qr=await e.startAttempt({emulatorName:dt.emulatorName,runAttemptId:_t}),Oo=g.child(qr.loggerBindings||{}),$u=await Ic({driver:dt.driver,onLogs:Os=>{qr.appendLogs(Os)}}),cn=x||t.settings?.defaultEnv,Nh;cn&&(Nh=Ss(cn,b,Oo).variables);let bM=new ei({variablesFromEnvironment:Nh??{},envName:cn,testName:t.name}),Dh=await Ni.init({driver:dt.driver,generator:j,logger:Oo,limbarClient:dt.limbarClient,playwrightDevice:dt.playwrightDevice,orgId:u,adbPort:dt.adbPort,options:{emulator:W},fixtures:{storage:Ae,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Xe,testContext:bM}}),$;try{$=await wu({containerName:`mobile test ${t.name}`,fixtures:{controller:Dh,logger:Oo,cacheStorage:Se,usageTracker:p},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:qr,callbacks:{}})}finally{await $u(),await dt.cleanup(),await Dh.cleanup()}return await qr.finish({logger:Oo,results:$.results,status:$.status}),$}import{debounce as BG}from"ts-debounce";var Is="0.9.3";var Gu="assets";function zG(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 HG(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var _h=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Co,an.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Gu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Gu}/${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:HG(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 $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},$i=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(`${Gu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new _h(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:zG(e.status),finishedAt:e.finishedAt}))))}},Ph=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(`
|
|
4291
4291
|
`);this.logStream.write(t+`
|
|
4292
4292
|
`)}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 $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Gu}/${t}.jpeg`)}},Ih=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:yn,runAttemptSchemaVersion:tE,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=BG(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Ph(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Vu=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:Is,labels:a??[]},c=new As(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:Is,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 Ih(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function fM(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 ln(){try{await k(Promise.all([uE(),Et.flush()]),{milliseconds:5e3})}catch{}}async function SM(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:m}=e;VG(d)&&C.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await fM(s,a,e.ignoreQuarantine),p=await hr(i),h=await gM({tests:n.tests,yes:e.yes,project:i,momenticFiles:p,logger:C,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Vu.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,v=new Set,A=async()=>WG({runResults:b,startTime:x,ranTests:v,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],w=async Ae=>{C.warn(`${Ae} Stopping tests and printing latest results.`),await E.finish({logger:f,status:"CANCELLED"}),await A(),await Promise.allSettled(_.map(K=>K())),await ln(),process.exit(1)},N=async()=>{await w("SIGINT received.")};process.once("SIGINT",N);let G;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let Ae=e.timeoutMinutes*60*1e3;G=setTimeout(()=>{w(`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===m&&await Promise.race(K.map(Q=>Q.promise));let j=h[Ae],le=`test-${Ae}`;W[le]={done:!1,promise:(async({testDefinition:Q})=>{v.add(le);let Xe=Q.relativeFilePath.includes("..")?Q.fullFilePath:Q.relativeFilePath;La({status:"START",testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length});let De=setInterval(()=>La({status:"RUN",testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Bt=GG(),Wt=f.child({testId:Q.id,runId:Bt}),ke=new Gc({logger:Wt,reporter:new Iu(a),runType:"mobile-test-run",runId:Bt,testMetadata:Q,suiteMetadata:void 0});try{let Pe=await hM({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)=>La({status:_t,testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length,additionalText:dt}),runSigIntHandlers:_},options:e});La({status:Pe.status,testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length}),b.push(Pe)}catch(Pe){let _t=`Encountered unexpected fatal error when running test '${Q.name}': ${Pe.message}
|
|
4293
4293
|
${Pe.stack}`;C.error(_t),Wt.error({err:Pe},`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),A()}async function WG({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=dE({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Cm}- ${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 Du({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 Oh(){PA(),hE("Chromium")||(lo?(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)))}vA({serviceName:"mobile-cli"});ar.setApp("mobile-cli");var jn=new jG;jn.name("momentic-mobile").description("Momentic Mobile CLI").version(Is);var XG=jn.command("assets").description("Manage mobile testing assets");XG.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(_s).addOption(Ps).addOption(Ch).addOption(aM).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=ju.resolve(r);Wu.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(_s).addOption(Ps).addOption(Th).addOption(Eh).addOption(xh).addOption(vh).addOption(Ah).addOption(wh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=xm(r.logLevel);ar.setApp("mobile-desktop-server");let c=new Rr({baseUrl:t,apiKey:e,logger:ar});await rh({client:c,skipPrompts:n}),C.debug("API key check complete");let l=YG(import.meta.url),u=ju.dirname(l),d=ju.resolve(u,"..","static");await Oh(),C.debug({appiumHome:os},"Resolved resource paths");let m=await bs({configFilePath:r.config}),g=nM;await rM({momenticServerUrl:t,serverPort:g,apiKey:e,staticDir:d,initialProject:m,driverLogLevel:s,logger:ar,regenerateCache:a,noCache:o,alwaysSaveCache:i});let p=`http://localhost:${g}`;C.info(`Local app started on: ${p}`),await KG(p)});var yM=jn.command("results").description("Merge and upload test results.");yM.command("merge").description("Merge test results files.").addOption(Rh).addArgument(new Lh("<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)),Wu.existsSync(r)||(C.warn("Results path does not exist, skipping merge."),process.exit(0)),Wu.existsSync(t)&&C.warn(`Output directory ${t} already exists, removing before merging...`),Dx(ar,t,r),await ln(),process.exit(0)});var JG=new Lh("<results>","Path to the results archive.").argRequired();yM.command("upload").description("Upload test results to Momentic cloud.").addOption(_s).addOption(Ps).addArgument(JG).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=ar,i=new Rr({baseUrl:n,apiKey:t,logger:o});await Du({consoleLogger:C,resultsPath:r,client:i}),await ln(),process.exit(0)});var QG=jn.command("run").alias("test").description("Run tests on the local machine");QG.addOption(_s).addOption(Ps).addOption(Eh).addOption(Th).addOption(uM).addOption(xh).addOption(vh).addOption(Ah).addOption(wh).addOption(Rh).addOption(dM).addOption(mM).addOption(pM).addOption(Ch).addOption(iM).addOption(sM).addOption(lM).addOption(cM).addArgument(new Lh("<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=xm(e.logLevel);await Oh(),C.debug({appiumHome:os},"Resolved resource paths");let c=await bs({configFilePath:e.config}),l=a??c.config.outputDir??Ax,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:m,userId:g}=await rh({client:d,skipPrompts:e.yes});C.debug("API key check and browser installation complete");let p=qG(),h=ar.child({runGroupId:p,orgId:m,userId:g}),f=await Ui(ar,d,c);h.debug(f,"Got local git metadata");try{let E=await SM({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:p,orgId:m}});await ln(),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 ln(),process.exit(1)}});jn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new $G("--name <name>","Name of the project")).action(async r=>{C.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|