momentic-mobile 0.0.19 → 0.0.20

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
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- var $A=Object.defineProperty;var Ie=(r,e)=>()=>(r&&(e=r(r=0)),e);var qA=(r,e)=>{for(var t in e)$A(r,t,{get:e[t],enumerable:!0})};var CS,xS=Ie(()=>{"use strict";CS=typeof globalThis=="object"?globalThis:global});var _S=Ie(()=>{"use strict";xS()});var MS=Ie(()=>{"use strict";_S()});var Cr,ku=Ie(()=>{"use strict";Cr="1.9.0"});function wM(r){var e=new Set([r]),t=new Set,n=r.match(IS);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(IS);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var IS,PS,OS=Ie(()=>{"use strict";ku();IS=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;PS=wM(Cr)});function bo(r,e,t,n){var o;n===void 0&&(n=!1);var i=ki[Di]=(o=ki[Di])!==null&&o!==void 0?o:{version:Cr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Cr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Cr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Cr+"."),!0}function xr(r){var e,t,n=(e=ki[Di])===null||e===void 0?void 0:e.version;if(!(!n||!PS(n)))return(t=ki[Di])===null||t===void 0?void 0:t[r]}function To(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Cr+".");var t=ki[Di];t&&delete t[r]}var CM,Di,ki,Ui=Ie(()=>{"use strict";MS();ku();OS();CM=Cr.split(".")[0],Di=Symbol.for("opentelemetry.js.api."+CM),ki=CS});function Fi(r,e,t){var n=xr("diag");if(n)return t.unshift(e),n[r].apply(n,_M([],xM(t),!1))}var xM,_M,LS,NS=Ie(()=>{"use strict";Ui();xM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_M=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))},LS=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fi("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fi("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fi("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fi("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fi("verbose",this._namespace,e)},r}()});var we,Ps=Ie(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(we||(we={}))});function DS(r,e){r<we.NONE?r=we.NONE:r>we.ALL&&(r=we.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var kS=Ie(()=>{"use strict";Ps()});var MM,IM,PM,dr,Bi=Ie(()=>{"use strict";NS();kS();Ps();Ui();MM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},IM=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))},PM="diag",dr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=xr("diag");if(l)return l[o].apply(l,IM([],MM(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:we.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=xr("diag"),d=DS((l=i.logLevel)!==null&&l!==void 0?l:we.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return bo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){To(PM,t)},t.createComponentLogger=function(o){return new LS(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var US,FS=Ie(()=>{"use strict";US=Symbol("BaggageEntryMetadata")});function Uu(r){return typeof r!="string"&&(OM.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:US,toString:function(){return r}}}var OM,BS=Ie(()=>{"use strict";Bi();FS();OM=dr.instance()});function Fu(r){return Symbol.for(r)}var LM,Bu,zu=Ie(()=>{"use strict";LM=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Bu=new LM});function Vu(){return Hu}var _n,NM,Os,DM,kM,UM,FM,Gu,BM,zM,GM,Hu,HM,VM,jM,WM,$M,qM,KM,ju=Ie(()=>{"use strict";_n=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),NM=function(){function r(){}return r.prototype.createGauge=function(e,t){return VM},r.prototype.createHistogram=function(e,t){return jM},r.prototype.createCounter=function(e,t){return HM},r.prototype.createUpDownCounter=function(e,t){return WM},r.prototype.createObservableGauge=function(e,t){return qM},r.prototype.createObservableCounter=function(e,t){return $M},r.prototype.createObservableUpDownCounter=function(e,t){return KM},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Os=function(){function r(){}return r}(),DM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Os),kM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Os),UM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Os),FM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Os),Gu=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),BM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gu),zM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gu),GM=function(r){_n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gu),Hu=new NM,HM=new DM,VM=new UM,jM=new FM,WM=new kM,$M=new BM,qM=new zM,KM=new GM});var _t,zS=Ie(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(_t||(_t={}))});var YM,XM,GS,HS=Ie(()=>{"use strict";zu();YM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},XM=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))},GS=function(){function r(){}return r.prototype.active=function(){return Bu},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,XM([n],YM(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var JM,QM,Wu,ZM,VS,jS=Ie(()=>{"use strict";HS();Ui();Bi();JM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QM=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))},Wu="context",ZM=new GS,VS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return bo(Wu,e,dr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,QM([e,t,n],JM(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return xr(Wu)||ZM},r.prototype.disable=function(){this._getContextManager().disable(),To(Wu,dr.instance())},r}()});var vo,WS=Ie(()=>{"use strict";jS();vo=VS.getInstance()});var F,$S=Ie(()=>{"use strict";Bi();F=dr.instance()});var eI,qS,KS=Ie(()=>{"use strict";ju();eI=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Hu},r}(),qS=new eI});var $u,YS,XS=Ie(()=>{"use strict";KS();Ui();Bi();$u="metrics",YS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return bo($u,e,dr.instance())},r.prototype.getMeterProvider=function(){return xr($u)||qS},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){To($u,dr.instance())},r}()});var Ls,JS=Ie(()=>{"use strict";XS();Ls=YS.getInstance()});var he=Ie(()=>{"use strict";BS();zu();Ps();ju();zS();WS();$S();JS()});import{Argument as Em,Command as lU,Option as cU}from"@commander-js/extra-typings";import QA from"appium";import{tmpdir as ZA}from"os";import{remote as eR}from"webdriverio";import{createInstanceClient as KA}from"@limrun/api";import{execSync as YA}from"child_process";import{hostname as XA}from"os";import JA from"path";async function bm(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:l,adbUrl:c,name:s,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:XA()}),p;try{YA("adb --version"),p="adb"}catch{if(process.env.ANDROID_HOME)p=JA.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("adb not found in PATH and ANDROID_HOME not set")}t.info({emulatorName:s,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let g=await KA({adbUrl:c,endpointUrl:l,token:a,logLevel:i,adbPath:p}),m=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];u&&m.push(u);let h=n.apkToInstall?.channel,f=n.apkToInstall?.tag;o(`Installing APK${h?` with channel ${h}`:""}${f?` and tag ${f}`:""}`),await Promise.all(m.map(b=>g.sendAsset(b))),o("Starting tunnel");let E=await g.startAdbTunnel();return{port:E.address.port,close:E.close,token:a,webRtcUrl:l,emulatorName:s}}async function Ca({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,logLevel:o,appiumPort:i,socket:a}){let l=Date.now(),{close:c,port:s,limbarToken:u,limbarUrl:d,emulatorName:p}=await nR({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),g=[()=>t.deleteAndroidEmulator(p),c],m=async()=>{for(let f=g.length-1;f>=0;f-=1)try{await g[f]()}catch(E){if(E instanceof Error&&E.message.includes("ECONNREFUSED"))return;n.warn({err:E},"Error running cleanup task")}},h=async()=>{if(a&&!a.connected)throw await m(),new Error("Client disconnected before Appium driver could be started")};await h();try{let f=await tR({logger:n,logLevel:o,appiumPort:i,port:s,limbarStart:l,emulatorName:p,apiClient:t,onStatusUpdate:r,creationOpts:e});return g.push(f.appiumClose),g.push(async()=>f.driver.deleteSession()),await h(),{...f,emulatorName:p,limbarToken:u,limbarUrl:d,adbTunnelPort:s,cleanup:m,appiumPort:i}}catch(f){throw await m(),new Error(`Failed to start Appium driver: ${f}`)}}async function tR({logger:r,logLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:l,logFile:c}=await rR({logger:r,logLevel:e,appiumPort:i}),s={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":300,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0},u={hostname:"localhost",port:i,logLevel:e,capabilities:s,connectionRetryTimeout:3e4,connectionRetryCount:2},d=Date.now(),p=await eR(u);await p.updateSettings({enableMultiWindows:!0});let g=new Map;return p.on("command",m=>{g.set(m.command,Date.now())}),p.on("result",m=>{let h=g.get(m.command);if(!h)return;let f=Date.now()-h;m.result instanceof Error?r.warn({err:m.result,command:m.command,args:m.body,durationMs:f},"Appium cmd failed"):f>1e4&&r.warn({command:m.command,args:m.body,durationMs:f},"Appium cmd took very long"),g.delete(m.command)}),r.info({timings:{limbarDuration:a-n,appiumDuration:d-a,wdioDuration:Date.now()-d},capabilities:s,emulatorName:o},"Started Appium driver"),{driver:p,appiumClose:l,appiumPort:i,appiumLogFile:c}}async function rR({logger:r,logLevel:e,appiumPort:t}){let n=`${ZA()}/appium-port-${Date.now()}.log`,o=await QA.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}async function nR({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:l,emulatorName:c}=await bm({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:l,emulatorName:c}}import Tm from"crypto";import oR from"fs";async function xa({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await oR.promises.readFile(t),a=Tm.createHash("md5").update(i).digest("base64"),l=Tm.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===l)){o.info({channel:e,tag:r,md5:a,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let s=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(s.status!==200)throw new Error(`Got error response from emulator platform: ${s.status} ${await s.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(s){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:s},"Failed to upload asset"),s}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as Cf}from"child_process";import{existsSync as D_}from"fs";import{platform as xf}from"os";import{dirname as k_,join as U_,resolve as F_}from"path";import{z as vm}from"zod";var LU=vm.object({input:vm.string()});import{z as $e}from"zod";var kU=$e.object({srcs:$e.array($e.string()),urls:$e.array($e.string()),desiredSrc:$e.string().optional(),desiredUrl:$e.string().optional()}),Am=$e.object({srcRegex:$e.string().optional(),urlRegex:$e.string().optional()}),Rm=$e.object({x:$e.number(),y:$e.number(),correlation:$e.number()}),UU=$e.object({searchImageBase64String:$e.string(),pageImageBase64String:$e.string(),id:$e.string().uuid(),timeoutMs:$e.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as iR}from"zod-openapi";iR(L);var Or=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Or||{}),aR=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),fc=L.object({result:L.number(),traceId:L.string()}).array(),_a=L.object({type:L.literal("GCS_TRACES"),traces:fc}),wm=L.object({text:L.string().optional(),attributes:L.record(L.string(),L.string()).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),sR=L.object({selectors:L.string().array(),requirements:wm.optional()}),Lr=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:wm.optional(),additionalElements:sR.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:aR.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Or).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:_a.optional()}).openapi({ref:"ElementTargetCache"});function Ma(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function Cm(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var lR=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),cR=L.object({x:L.number(),y:L.number()}),uR=L.object({type:L.literal("coordinates"),pixels:cR}).openapi({ref:"CoordinatesTarget"});function Nr(r){return r.type==="description"}function nr(r){return r.type==="coordinates"}var it=L.discriminatedUnion("type",[lR,uR]).openapi({ref:"ElementTarget"});function Sc(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function xm(r){return _a.safeParse(r).success}import{v4 as se}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as yR}from"zod-openapi";import{z as X}from"zod";import{extendZodWithOpenApi as dR}from"zod-openapi";import{z as Kn}from"zod";var yc=Kn.object({result:Kn.boolean(),traceId:Kn.string()}).array(),Ec=Kn.object({type:Kn.literal("GCS_TRACES"),traces:yc}),bc=Kn.object({memory:Ec.optional()});dR(X);var _m=X.object({plan:X.string().optional(),evidence:X.string().optional(),thoughts:X.string(),result:X.boolean(),relevantElements:X.array(X.number()).optional(),updatedMemory:yc.optional()}),Dr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Dr||{});var pR=X.object({type:X.literal("ELEMENT_NAME"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementNameAssertion"}),mR=X.object({type:X.literal("ELEMENT_STYLE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),property:X.string(),value:X.string()}).openapi({ref:"ElementStyleAssertion"}),gR=X.object({type:X.literal("ELEMENT_CONTENT"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementContentAssertion"}),hR=X.object({type:X.literal("ELEMENT_ATTRIBUTE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),attr:X.string(),value:X.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Yn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Yn||{}),fR=X.object({type:X.literal("ELEMENT_EXISTENCE"),negated:X.boolean().optional(),condition:X.nativeEnum(Yn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Mm=X.discriminatedUnion("type",[gR,hR,fR,pR,mR]).openapi({ref:"ManualElementAssertion"});var SR=X.object({type:X.literal("CONTENT"),negated:X.boolean().optional(),value:X.string()}).openapi({ref:"PageContentAssertion"}),Im=X.discriminatedUnion("type",[SR]).openapi({ref:"ManualPageAssertion"});import pt from"zod";var Tc=pt.discriminatedUnion("type",[pt.object({type:pt.literal("SUBSTRING"),url:pt.string()}),pt.object({type:pt.literal("GLOB"),glob:pt.string()}),pt.object({type:pt.literal("REGEX"),regex:pt.string()}),pt.object({type:pt.literal("DOMAIN"),domain:pt.string()})]),ei=pt.object({urlMatcher:Tc,method:pt.string().optional()});import{z as ae}from"zod";var Ia=ae.object({url:ae.string(),method:ae.union([ae.literal("GET"),ae.literal("POST"),ae.literal("PUT"),ae.literal("DELETE"),ae.literal("PATCH")]),headers:ae.record(ae.string(),ae.string()).optional(),params:ae.record(ae.string(),ae.string()).optional(),body:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Pm=ae.object({url:ae.string(),headers:ae.record(ae.string(),ae.string()).optional(),query:ae.string(),variables:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Pa=ae.object({code:ae.string(),fragment:ae.boolean().optional(),environment:ae.union([ae.literal("NODE"),ae.literal("BROWSER")]).optional().describe("default NODE"),timeout:ae.number().int().max(60).optional().describe("Max seconds for the code to complete")});var rt=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.MOCK_ROUTE="MOCK_ROUTE",H.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(rt||{});yR(y);var G=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),It=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Pt=y.object({target:Lr}).optional().openapi({ref:"SingleTargetCache"});function Lm(r){return Pt.safeParse(r).success}var La=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),ER=G.merge(La).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),Na=It.merge(y.object({cache:Pt})),Xn=G.merge(Na.merge(y.object({target:it.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Jn=G.merge(Na.merge(y.object({target:it.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Qn=G.merge(Na.merge(y.object({target:it.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Zn=G.merge(Na.merge(y.object({target:it.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),lF=y.discriminatedUnion("type",[Xn,Jn,Qn,Zn]).openapi({ref:"AllScrollCommands"}),bR=G.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),TR=G.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),vR=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),AR=G.extend({type:y.literal("WAIT_FOR_URL"),matcher:Tc}).merge(vR).openapi({ref:"WaitUrlCommand"}),RR=G.merge(La).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),wR=G.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),CR=G.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),xR=G.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),_R=G.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),vc=G.merge(It).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),MR=G.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),IR=G.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),PR=G.merge(Pa).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ti=G.merge(It).extend({type:y.literal("CLICK"),target:it,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Pt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),Nm=y.object({fromTarget:Lr.optional(),toTarget:Lr.optional()}),ri=G.merge(It).merge(y.object({type:y.literal("DRAG"),fromTarget:it,toTarget:it,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:Nm.optional()})).openapi({ref:"DragCommand"}),ni=G.merge(It).merge(y.object({type:y.literal("MOUSE_DRAG"),target:it.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Pt})).openapi({ref:"MouseDragCommand"}),oi=G.merge(It).merge(y.object({type:y.literal("HOVER"),target:it,cache:Pt})).openapi({ref:"HoverCommand"}),ii=G.merge(It).merge(y.object({type:y.literal("FOCUS"),target:it,cache:Pt})).openapi({ref:"FocusCommand"}),ai=G.merge(It).extend({type:y.literal("BLUR"),target:it.optional(),cache:Pt}).openapi({ref:"BlurCommand"}),OR=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),LR=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),NR=G.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[OR,LR]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),DR=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),si=G.merge(It).extend({type:y.literal("SELECT_OPTION"),target:it,cache:Pt,choice:DR.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Ac=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Da=G.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:Ac.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:bc.optional()})).openapi({ref:"AIAssertionCommand"}),kr=5,Rc=600,li=G.merge(It).extend({type:y.literal("ELEMENT_CHECK"),target:it,assertion:Mm,cache:Pt.or(bc).optional(),timeout:y.number().int().min(0).max(Rc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),kR=G.extend({type:y.literal("PAGE_CHECK"),assertion:Im,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(Rc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),UR=G.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),FR=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional()}),Dm=25,ci=G.merge(It).merge(FR).extend({type:y.literal("TYPE"),target:it.optional(),value:y.string(),cache:Pt}).openapi({ref:"TypeCommand"}),BR=G.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),zR=G.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),GR=G.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),HR=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),VR=y.object({type:y.literal("REGEX"),pattern:y.string()}),jR=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),WR=y.discriminatedUnion("type",[HR,VR,jR]),$R=G.merge(La).merge(y.object({type:y.literal("TAB"),action:WR})).openapi({ref:"TabCommand"}),qR=G.merge(La).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),KR=G.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),YR=G.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),XR=G.extend({type:y.literal("REQUEST")}).merge(Ia).openapi({ref:"RequestCommand"}),JR=G.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Pm).openapi({ref:"GraphQLRequestCommand"}),QR=G.merge(y.object({type:y.literal("SUCCESS"),condition:Da.optional()})).openapi({ref:"SuccessCommand"}),ZR=G.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ew=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),ui=G.merge(It).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:it.optional(),screenshot:ew.optional(),cache:Pt})).openapi({ref:"VisualDiffCommand"}),tw=G.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:ei,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),rw=G.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),nw=G.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:ei,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),ow=G.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),iw=G.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:ei.optional()})).openapi({ref:"SetHeaderCommand"}),aw=G.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:ei,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:y.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),sw=G.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),lw=G.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),km=y.discriminatedUnion("type",[ti,ci,BR,zR,GR,si,ER,Jn,Xn,Da,oi,TR,QR]),cw=y.discriminatedUnion("type",[UR,_R,xR,vc,KR,MR,bR,ri,li,NR,wR,CR,PR,YR,ni,qR,kR,IR,RR,XR,JR,Qn,Zn,$R,ui,ii,ai,AR,tw,rw,nw,ow,iw,aw,sw,lw]),eo=y.discriminatedUnion("type",[...km.options,...cw.options]).openapi({ref:"Command"}),ka=y.discriminatedUnion("type",[...km.options,ZR]);function Ar(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:se(),type:r};break;case"AUTH_LOAD":{e={id:se(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:se(),type:r,goal:""};break;case"DIALOG":e={id:se(),type:r,action:"DISMISS"};break;case"DRAG":e={id:se(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:se(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:se(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:se(),type:r,delay:1};break;case"BLUR":e={id:se(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:se(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:se(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:se(),type:r,value:""};break;case"SELECT_OPTION":e={id:se(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:se(),type:r,url:""};case"TAB":e={id:se(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:se(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:se(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:se(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:se(),type:r,code:""};break;case"AI_ASSERTION":e={id:se(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:se(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:se(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:se(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:se(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:se(),type:r,key:""};break}case"SET_HEADER":{e={id:se(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:se(),type:r};break}case"OFFLINE_MODE":{e={id:se(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Um(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as uw}from"zod";var mF=uw.discriminatedUnion("type",[ai,vc,ti,ri,ii,oi,ni,Xn,Jn,Qn,Zn,si,ci,ui,li]);import{z as dw}from"zod";import{z as Ur}from"zod";function di(r){return Ur.object({key:Ur.string(),testId:Ur.string().optional(),moduleId:Ur.string().optional(),organizationId:Ur.string(),value:r})}function pi(r){return di(r).extend({uniqueKey:Ur.string()})}function Ua(r){return Ur.record(Ur.string(),pi(r))}var mt={type:!0,cache:!0},to=dw.discriminatedUnion("type",[Da.pick(mt),ai.pick(mt),ti.pick(mt),ri.pick(mt),li.pick(mt),ii.pick(mt),oi.pick(mt),ni.pick(mt),Xn.pick(mt),Jn.pick(mt),Qn.pick(mt),Zn.pick(mt),si.pick(mt),ci.pick(mt),ui.pick(mt)]),wc=Object.values(rt).filter(r=>to.options.some(e=>e.shape.type.safeParse(r).success));eo.options.forEach(r=>{if("target"in r.shape&&!wc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Fm(r){return wc.includes(r.type)}var Bm=di(to),zm=pi(to),TF=Ua(to);import{z as Cc}from"zod";import{extendZodWithOpenApi as gw}from"zod-openapi";import{z as Gm}from"zod";import{extendZodWithOpenApi as pw}from"zod-openapi";import{z as sn}from"zod";var Ot=sn.object({index:sn.number().optional().describe("global index within a test (in-order traversal)"),id:sn.string(),skipped:sn.boolean().optional(),envKey:sn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:sn.boolean().optional(),retries:sn.number().optional()});pw(Gm);var mw=Ot.extend({type:Gm.literal("PRESET_ACTION")}),Lt=mw.extend({command:eo}).openapi({ref:"PresetAction"});gw(Cc);var ln=Ot.extend({type:Cc.literal("AI_ACTION"),text:Cc.string(),steps:Lt.array().optional()}).openapi({ref:"AIAction"});import{z as gt}from"zod";import{z as Fa}from"zod";import{extendZodWithOpenApi as hw}from"zod-openapi";hw(Fa);var ro=Ot.extend({type:Fa.literal("AI_ACTION_DYNAMIC"),text:Fa.string(),retries:Fa.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Hm}from"zod";var xc=Ot.extend({type:Hm.literal("CONDITIONAL"),skipped:Hm.boolean().optional()});import{z as ne}from"zod";var fw=ne.object({cacheKey:ne.string(),cacheExpiryMs:ne.number()}),_c=Ot.extend({id:ne.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ne.record(ne.string()).optional(),cacheConfig:fw.optional()}),Rr=_c.extend({type:ne.literal("MODULE"),moduleId:ne.string().uuid()}),Sw=ne.union([Rr.pick({type:!0,moduleId:!0}),ne.record(ne.unknown())]),yw=ne.object({type:ne.literal("URL_REGEX"),regex:ne.string()}),Ew=ne.object({type:ne.literal("PAGE_CHECK"),substring:ne.string()}),Mc=ne.object({cacheInvalidation:ne.discriminatedUnion("type",[Ew,yw]).optional()}),Nt=ne.object({moduleId:ne.string().uuid(),name:ne.string(),description:ne.string().nullish(),enabled:ne.boolean().nullish(),parameters:ne.string().array().nullish(),defaultParameters:ne.record(ne.string(),ne.string()).nullish(),parameterEnums:ne.record(ne.string(),ne.string().array()).nullish(),defaultCacheKey:ne.string().nullish(),defaultCacheTtl:ne.number().nullish(),defaultCacheAllInvocations:ne.boolean().nullish(),autoAuth:ne.boolean().nullish(),advanced:Mc.nullish()});import{z as Dt}from"zod";var Vm=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Vm||{});var bw=Dt.discriminatedUnion("type",[Dt.object({type:Dt.literal("NAVIGATE_URL"),url:Dt.string().url()}),Dt.object({type:Dt.literal("GO_TO_SECTION_START")})]),Tw=Dt.object({trigger:Dt.nativeEnum(Vm).optional(),attempts:Dt.number().int().optional(),restartBehavior:bw}),mi=Ot.extend({type:Dt.literal("SECTION"),description:Dt.string().describe("user provided goal of what the section should accomplish"),plan:Dt.string().array().optional(),autohealingConfig:Tw.optional()});var jm=Nt.merge(_c).extend({type:gt.literal("RESOLVED_MODULE"),steps:gt.lazy(()=>Ke.array())}),gi=Nt.extend({steps:gt.lazy(()=>Ke.array())}),Ic=mi.extend({steps:gt.lazy(()=>ht.array())}),vw=mi.extend({steps:gt.lazy(()=>Ke.array())}),no=xc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>ht.array())}).array(),elseSteps:gt.lazy(()=>ht.array().optional())}),Aw=xc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>Ke.array())}).array(),elseSteps:gt.lazy(()=>Ke.array().optional())}),ht=gt.discriminatedUnion("type",[Lt,ln,ro,Rr,no,Ic]),Ke=gt.discriminatedUnion("type",[Lt,ln,ro,jm,Aw,vw]);import{z as kt}from"zod";var Rw=kt.object({steps:ht.array(),beforeSteps:ht.array().nullish(),afterSteps:ht.array().nullish()}),oo=kt.object({steps:Ke.array(),beforeSteps:Ke.array().nullish(),afterSteps:Ke.array().nullish()}),cn=kt.object({steps:kt.record(kt.string(),kt.unknown()).array(),beforeSteps:kt.record(kt.string(),kt.unknown()).array().nullish(),afterSteps:kt.record(kt.string(),kt.unknown()).array().nullish()});var un="1.0.21",Pc="0.0.1";var Wm=I.object({phrase:I.string()}),Oc=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),az=I.object({text:I.string()}),$m=I.object({attributes:I.array(I.string()).optional(),text:I.boolean().optional(),boundingBox:I.boolean().optional()}),ww=I.object({id:I.number().int(),requirements:$m}),Cw=ww.array(),qm=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:fc.optional(),requirements:$m.optional(),additionalElements:Cw.optional()});var Lc=(g=>(g.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",g.FEW_WORDS="FEW_WORDS",g.STYLE_TAG="STYLE_TAG",g.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",g.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",g.NONE="NONE",g.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",g.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",g.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",g.PREFER_ASSERTION="PREFER_ASSERTION",g.HTML_ELEMENTS="HTML_ELEMENTS",g.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",g.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",g))(Lc||{}),Km=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(Km||{});var Ym=I.object({thoughts:I.string(),category:I.nativeEnum(Lc)}),Xm=I.object({thoughts:I.string(),category:I.nativeEnum(Km)}),xw=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),sz=I.object({thoughts:I.string(),patches:xw.array()}),_w=[I.literal("add"),I.literal("replace"),I.literal("remove")],Mw=I.object({op:I.union(_w),path:I.string(),value:Ke.optional()}),Jm=I.object({patches:Mw.array(),thoughts:I.string()}),Qm=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Qm||{}),Zm=I.object({thoughts:I.string(),scenario:I.nativeEnum(Qm),instructions:I.string().nullish()}),eg=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),lz=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),cz=I.object({observations:I.string(),reasoning:I.string(),command:ka});var Nc=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),Iw=I.object({startId:I.number().int(),endId:I.number().int()}),tg=I.object({categoryThoughts:I.string(),category:I.string(),relevantSections:Iw.array()});import{z as _}from"zod";import*as J from"zod";var hz=J.object({thoughts:J.string().optional().describe("only provided if a description was provided"),target:Lr.optional().describe("only provided if a description was provided"),pageState:J.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:J.object({label:J.string(),value:J.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:J.object({data:J.string(),height:J.number().int(),width:J.number().int()}).optional().describe("only provided if returnScreenshot is true")}),rg=J.union([J.literal("ELEMENT_CHECK"),J.literal("NEGATED_CHECK"),J.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),J.literal("SELECT_OPTION"),J.literal("TYPE")]);function hi(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var fi=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(fi||{}),io=J.object({matched:J.boolean(),reason:J.string().optional().describe("Human understandable description"),logs:J.string().array().optional().describe("Logs for debugging")}),Pw=io.extend({type:J.literal("USER_SELECTOR")}),Ow=io.extend({type:J.literal("CSS_SELECTOR"),selectors:J.string().array()}),Lw=io.extend({type:J.literal("HYBRID_SELECTOR")}),Nw=io.extend({type:J.literal("HTML_DISTANCE"),distance:J.number().optional(),closestElement:J.string().optional(),savedElement:J.string().optional()}),Dw=io.extend({type:J.literal("TEMPLATE_MATCHING"),elementImageUrl:J.string().url()}),kw=io.extend({type:J.literal("AUTO_FRAME"),logs:J.string().array().optional()}),ng=J.discriminatedUnion("type",[Pw,Ow,Lw,Nw,Dw,kw]);import{z as bi}from"zod";import{z as qw}from"zod";import*as z from"zod";import{extendZodWithOpenApi as Bw}from"zod-openapi";import{cloneDeep as Cz}from"lodash-es";import _z from"truncate-json";import*as mn from"zod";import{extendZodWithOpenApi as Uw}from"zod-openapi";import{z as at}from"zod";import{z as fe}from"zod";var Dc=fe.object({autoFollowNewTabs:fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:fe.union([fe.boolean(),fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:fe.boolean().optional(),disableSecondaryCacheResolution:fe.boolean().optional(),hybridSelectorMode:fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:fe.boolean().optional(),visualActions:fe.boolean().optional(),autoExpandIframes:fe.boolean().optional(),disableHtmlSnapshots:fe.boolean().optional(),importantAttributes:fe.string().array().optional(),importantClasses:fe.string().array().optional(),importantStyles:fe.string().array().optional()});var og=1e4,ig=6e4,dn=Dc.extend({pageLoadTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=ig&&r>=-1,{message:`Page load timeout must be between 0 and ${ig/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=og&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${og/1e3} seconds`}),localChromeExtensionPaths:fe.string().array().optional(),extraHeaders:fe.record(fe.string(),fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:fe.string().optional(),disableGpu:fe.boolean().optional(),bustCacheOnBoundingBoxChange:fe.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var kc="BASE_URL";var pn="ENV_NAME",ao="TEST_NAME",Tz={[kc]:"https://www.google.com"},ag=at.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),sg=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.string().describe("variable value"))}),lg=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value")),browser:dn.optional()});var vz=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value"))});Uw(mn);var Uc=mn.object({env:mn.record(mn.unknown())}).openapi({ref:"TestContextSnapshot"});var Ye=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ye||{}),Fc=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Fc||{});import{z as or}from"zod";import{extendZodWithOpenApi as Fw}from"zod-openapi";Fw(or);var ge=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(ge||{});var Bc=or.object({reason:or.nativeEnum(ge),previousStepsDescription:or.array(or.string()).optional(),summary:or.string(),rootCause:or.string().optional()}).openapi({ref:"TestResultClassification"}),Ba=or.object({errorMessage:or.string(),errorStack:or.string().optional(),classification:Bc.optional()}).openapi({ref:"TestFailureDetails"});Bw(z);var zc=z.object({beforeUrl:z.string().optional(),afterUrl:z.string().optional(),message:z.string().optional(),beforeSnapshot:z.string().optional(),afterSnapshot:z.string().optional(),startedAt:z.coerce.date(),finishedAt:z.coerce.date()}),zw=zc.extend({viewport:z.object({height:z.number(),width:z.number()}).nullish(),status:z.nativeEnum(Fc),message:z.string().optional(),elementInteracted:z.string().optional()}),gn=zc.extend({status:z.nativeEnum(Ye),message:z.string().optional(),data:z.unknown().optional(),beforeTestContext:Uc.optional(),afterTestContext:Uc.optional(),failureReason:z.nativeEnum(ge).optional(),details:z.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),cg=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(cg||{}),za=gn.merge(Lt).extend({results:zw.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:z.lazy(()=>Qe.array()).optional(),failureRecoveryStatus:z.object({type:z.nativeEnum(cg),message:z.string()}).optional()}),Gw=gn.merge(ln).extend({results:z.lazy(()=>za.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Hw=gn.merge(ro).extend({results:z.lazy(()=>za.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Vw=gn.merge(Rr).extend({moduleName:z.string().optional(),results:z.lazy(()=>Qe.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),jw=gn.merge(no).extend({assertion:za.optional(),results:z.lazy(()=>Qe.array()).describe("results for the block actually executed"),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Ww=gn.merge(mi).extend({results:z.lazy(()=>Qe.array()),healingAttempts:z.lazy(()=>Qe.array().array()).optional(),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Qe=z.discriminatedUnion("type",[Gw,Hw,za,Vw,jw,Ww]),qz=gn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),$w=zc.extend({index:z.number().optional(),description:z.string(),pageState:z.string().optional(),elementInteracted:z.string().optional(),startedAt:z.coerce.date().or(z.string()).optional().catch(void 0),finishedAt:z.coerce.date().or(z.string()).optional().catch(void 0)}),Ga=$w.extend({beforeScreenshot:z.string().optional(),afterScreenshot:z.string().optional()});var Gc=qw.object({results:Qe.array().describe("main results"),beforeResults:Qe.array().optional(),afterResults:Qe.array().optional()}),Si=Gc.partial();import{z as U}from"zod";import{extendZodWithOpenApi as eC}from"zod-openapi";var so=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(so||{});import{isValidCron as Kw}from"cron-validator";import{z as Q}from"zod";import{z as Hc}from"zod";var Fr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Fr||{});var Ha=Hc.object({width:Hc.number().min(200).max(1e4),height:Hc.number().min(200).max(1e4)}),ug={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},e1=Object.keys(ug);var Br=ug["Desktop Large"],dg="en-us",pg="America/Los_Angeles";var mg={latitude:37.7749,longitude:-122.4194};var gg=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var hg=2e3,Yw=dn.extend({browserType:Q.nativeEnum(Fr).optional(),slowMoMs:Q.number().optional().refine(r=>r===void 0||r<=hg&&r>=-1,{message:`Slow motion must be between 0 and ${hg} milliseconds`}),basicAuthorization:Q.object({username:Q.string().optional(),password:Q.string().optional()}).optional(),geolocation:Q.object({latitude:Q.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Q.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Q.boolean().optional(),locale:Q.string().optional(),timezone:Q.enum(gg).optional(),colorScheme:Q.enum(["light","dark"]).optional()});var Vc=Q.object({useMemory:Q.boolean().optional(),failureRecovery:Q.boolean().optional().describe("undefined means inherit org settings")}),Xw=Vc.extend({disableAICaching:Q.boolean().optional(),failureRecoveryInstructions:Q.string().optional()}),Jw=Q.object({viewport:Ha.optional()}),yi=Jw.merge(Xw).merge(Yw),lo=Q.object({cron:Q.string().refine(r=>Kw(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Q.boolean().default(!1),env:Q.string().optional(),timeZone:Q.string().default("America/Los_Angeles"),jobKey:Q.string().optional()}),co=Q.object({onSuccess:Q.boolean().default(!1),failureMessage:Q.string().optional(),onFailure:Q.boolean().default(!0),successMessage:Q.string().optional()}),Qw=Q.object({name:Q.string(),required:Q.boolean().optional(),defaultValue:Q.string().describe("this is not optional because we need a value when the editor is first loaded")}),Va=Qw.array(),Zw=Q.object({name:Q.string(),value:Q.string()}),fg=Zw.array(),ja=Q.object({name:Q.string(),default:Q.boolean().optional(),fixtures:ag.array().optional()});eC(U);var Ut={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},me=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(me||{}),Wa=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Wa||{});var ze=U.string().pipe(U.coerce.date()).or(U.date()),Ei=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(so).optional().default("WEB"),createdAt:ze,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:ze.or(U.null()),startedAt:ze.or(U.null()),updatedAt:ze.nullish(),finishedAt:ze.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(Wa).nullish(),status:U.nativeEnum(me),trigger:U.nativeEnum(Ut),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(me),startedAt:ze.or(U.null()),finishedAt:ze.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(ge).nullish(),failureDetails:Ba.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),tC={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},$a=Ei.pick({...tC,test:!0}),Sg=Ei.omit({failureReason:!0,failureDetails:!0,test:!0}),jc=Ei.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:yi.nullish()}).nullish()}).merge(Gc);var rC=bi.object({id:bi.string().uuid(),startedAt:ze.or(bi.null()),finishedAt:ze.or(bi.null()),status:bi.nativeEnum(me)}).merge(Si),v1=rC.array();import{z as Ge}from"zod";var nC=Ge.object({id:Ge.string(),status:Ge.nativeEnum(me),trigger:Ge.nativeEnum(Ut),createdAt:ze,startedAt:ze.nullish(),finishedAt:ze.nullish(),gitCommitSha:Ge.string().nullish(),gitCommitShaShort:Ge.string().nullish(),gitCommitTimestamp:ze.nullish(),gitBranchName:Ge.string().nullish(),gitOriginUrl:Ge.string().nullish(),gitCommitMessage:Ge.string().nullish(),gitCommitAuthorName:Ge.string().nullish(),githubRepository:Ge.string().nullish(),gitlabProjectPath:Ge.string().nullish(),pipelineId:Ge.string().nullish(),cliVersion:Ge.string().nullish(),labels:Ge.string().array().optional(),suite:Ge.object({id:Ge.string(),name:Ge.string()}).nullish(),runs:Ge.object({status:Ge.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),yg=nC.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:$a.array()});import{z as Ze}from"zod";var oC=Ze.object({type:Ze.literal("TARGETING"),name:Ze.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:ng.array(),pageState:Ze.string().optional(),targetSource:Ze.nativeEnum(Or).optional(),targetUpdateTime:Ze.string().optional()}),iC=Ze.object({type:Ze.literal("AI_LOCATION"),matched:Ze.boolean(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional(),thoughts:Ze.string().optional()}),aC=Ze.object({type:Ze.literal("ASSERTION"),relevantElementsSerialized:Ze.string().array().optional(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional()}),sC=Ze.discriminatedUnion("type",[oC,iC,aC]);import{z as Ue}from"zod";var lC=Ue.object({id:Ue.string(),name:Ue.string()}),k1=lC.merge(Ue.object({createdAt:ze,createdBy:Ue.string(),schedule:lo,notification:co,environment:Ue.object({name:Ue.string()}).nullish(),beforeTests:Ue.object({id:Ue.string()}).array().nullish(),afterTests:Ue.object({id:Ue.string()}).array().nullish()})),Eg=Ue.object({id:Ue.string().uuid(),orgId:Ue.string(),createdAt:ze,startedAt:ze.or(Ue.null()),finishedAt:ze.or(Ue.null()),status:Ue.nativeEnum(me),trigger:Ue.nativeEnum(Ut),suite:Ue.object({id:Ue.string(),name:Ue.string()}).nullish(),runs:Ei.array()}),U1=Eg.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),bg=Eg.extend({runs:$a.array()});import{z as Ft}from"zod";import{cloneDeep as z1}from"lodash-es";import{z as le}from"zod";var $1=le.object({thoughts:le.string(),subGoals:le.object({instruction:le.string()}).array()}),q1=le.object({thoughts:le.string(),newPlanMarkdown:le.string()}),K1=le.object({thoughts:le.string(),correct:le.boolean(),failedActionIndex:le.number().optional()}),cC=le.object({type:le.literal("PLANNING"),beforePlan:le.string(),goalDecision:le.string(),thoughts:le.string()}),uC=le.object({type:le.literal("RUNNING"),stepDisplayName:le.string(),status:le.nativeEnum(Ye),results:Qe.array()}),dC=le.object({type:le.literal("REVISING"),beforePlan:le.string(),afterPlan:le.string(),errString:le.string(),diffs:le.string(),thoughts:le.string()}),pC=le.object({type:le.literal("SYSTEM"),message:le.string()}),mC=le.discriminatedUnion("type",[cC,uC,dC,pC]),Tg=mC.array();var Z1=Ft.object({id:Ft.string(),scheduledAt:Ft.coerce.date().nullable(),startedAt:Ft.coerce.date().nullable(),finishedAt:Ft.coerce.date().nullable(),status:Ft.nativeEnum(me),history:Tg.nullable(),testPlan:Ft.object({id:Ft.string(),name:Ft.string()}).nullable(),test:Ft.object({id:Ft.string(),name:Ft.string()}).nullable()});import{z as ft}from"zod";var Wc=ft.object({content:ft.string(),ids:ft.string().array(),tokenLength:ft.number()}),gC=ft.object({chunks:Wc.array()}),fG=ft.object({ids:ft.string().array(),score:ft.number(),tokenLength:ft.number()}),SG=gC.extend({description:ft.string().describe("Input to pass to RAG engine"),tokenLimit:ft.number()}),vg=ft.object({ids:ft.number().array()}),Ag=ft.object({indices:ft.number().array()});var st=_.object({disableCache:_.boolean().optional(),useMemory:_.boolean().optional(),loggerTags:_.record(_.string(),_.string()).optional(),langfuseSessionId:_.string().optional(),agentConfigVersion:_.string().optional()}),wG=st.extend({chunks:Wc.array(),description:_.string().describe("Input to pass to AI"),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),softTokenLimit:_.number(),hardTokenLimit:_.number()}),hC=_.object({screenshotBase64AfterCommand:_.string(),urlAfterCommand:_.string(),serializedCommand:_.string(),elementInteracted:_.string().optional(),thoughts:_.string().optional()}),Rg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),source:rg.optional().catch(void 0),memory:_.discriminatedUnion("type",[_a,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional()}),wg=_.object({target:_.string().or(_.number()),browserState:_.string().optional(),screenshot:_.string().optional(),boundingBox:_.object({x:_.number(),y:_.number(),height:_.number(),width:_.number()}).optional()}),Cg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string().optional(),returnSchema:_.string().optional()}),fC=_.literal("NEGATED_CHECK"),xg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),url:_.string(),contextChoice:Ac.optional(),memory:_.discriminatedUnion("type",[Ec,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional(),source:fC.optional()}),_g=_.object({command:eo}),Mg=_.object({message:_.string()}),$c=_.object({goal:_.string(),browserState:_.string(),startingScreenshot:_.string().optional(),screenshot:_.string(),url:_.string(),history:hC.array(),actionHint:_.string().optional(),lastError:_.string().optional()}),Ig=_.object({results:Ga.array(),errorMessage:_.string(),errorStack:_.string().optional()}),Pg=_.object({results:Ga.array(),goal:_.string(),errorMessage:_.string()}),Og=_.object({failedResults:Ga.array(),nextStepsSerialized:_.string().array(),currentUrl:_.string(),currentPageState:_.string(),currentScreenshot:_.string(),customInstructions:_.string().optional(),testDescription:_.string().optional()}),CG=_.object({description:_.string(),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),excerpt:_.string()}),Lg=_.object({type:_.string(),browserContext:_.string(),currentStep:_.string(),screenshot:_.string()});import{z as Ti}from"zod";var MG=Ti.object({goal:Ti.string()}),Ng=Ti.object({keywords:Ti.array(Ti.string())});import{z as qc}from"zod";var qa=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(qa||{}),OG=qc.nativeEnum(qa),SC=qc.enum(["v1","v2"]),LG=SC.or(qc.string().describe("for people with special configurations"));import{z as Pe}from"zod";var Dg=Pe.object({attributesRequired:Pe.array(Pe.string()).optional(),textRequired:Pe.boolean().optional(),boundsRequired:Pe.boolean().optional()}),kg=Pe.object({id:Pe.number(),thoughts:Pe.string(),requirements:Dg.optional(),additionalElements:Pe.object({id:Pe.number(),requirements:Dg}).array().optional()}),Ug=Pe.object({description:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),Fg=Pe.object({assertion:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),Bg=Pe.object({thoughts:Pe.string(),result:Pe.boolean(),relevantElements:Pe.array(Pe.number()).optional()});import{z as hn}from"zod";var zg=hn.object({id:hn.string().uuid(),skipped:hn.boolean().optional(),envKey:hn.string().optional().describe("key in the environment to save the result of this step to")}),Kc=zg.merge(Ia).extend({type:hn.literal("REQUEST")}),Yc=zg.merge(Pa).extend({type:hn.literal("JAVASCRIPT")}),Xc=hn.discriminatedUnion("type",[Yc,Kc]);import{z as Bt}from"zod";import{z as fn}from"zod";var yC=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,zr=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Ka=fn.string().min(1).max(255).superRefine((r,e)=>{try{Jc(r)}catch(t){return e.addIssue({code:fn.ZodIssueCode.custom,message:t.message,fatal:!0}),fn.NEVER}});function Jc(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(yC))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ya=fn.preprocess(r=>r===null?"":r,fn.union([fn.string().url(),fn.literal("")])).optional();var Gg=Bt.object({id:Bt.string(),name:Ka,description:Bt.string().optional().nullish(),baseUrl:Ya.nullish(),schemaVersion:Bt.string(),advanced:Bt.unknown().optional(),retries:Bt.number(),envs:Bt.array(ja).nullish(),parameters:Va.nullish()}),EC=Bt.object({createdAt:Bt.coerce.date(),updatedAt:Bt.coerce.date(),schedule:lo.nullish(),notification:co.nullish(),createdBy:Bt.string(),organizationId:Bt.string()}),bC=Gg.merge(EC),iH=bC.extend({steps:Xc.array()}),aH=Gg.extend({steps:Xc.array()});import{z as vt}from"zod";var Hg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date(),status:vt.nativeEnum(Ye),message:vt.string().optional(),data:vt.unknown().optional()}),TC=Hg.merge(Yc).extend({type:vt.literal("JAVASCRIPT")}),vC=Hg.merge(Kc).extend({type:vt.literal("REQUEST")}),AC=vt.discriminatedUnion("type",[TC,vC]),Vg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date().nullish(),status:vt.nativeEnum(me),results:AC.array(),failureReason:vt.string().nullish(),failureDetails:Ba.nullish()});import{z as At}from"zod";var RC=At.object({id:At.string(),organizationId:At.string(),createdAt:At.coerce.date(),updatedAt:At.coerce.date(),createdBy:At.string(),scheduledAt:At.coerce.date().nullish(),startedAt:At.coerce.date().nullish(),finishedAt:At.coerce.date().nullish(),status:At.nativeEnum(me),trigger:At.nativeEnum(Ut),results:Vg.array().nullish(),apiTestName:At.string().nullish(),apiTestPath:At.string().nullish(),apiTestId:At.string().nullish()}),fH=RC.pick({status:!0,startedAt:!0,finishedAt:!0});var vi=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(vi||{}),jg=3;function wC(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Qc(r){if(!wC(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Zc(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return jg;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Xa=class{trackStepExecution(){}async flush(){}};import{parseString as CC,splitCookiesString as xC}from"set-cookie-parser";import{z as pe}from"zod";var eu=pe.object({name:pe.string(),value:pe.string(),url:pe.string().optional(),domain:pe.string().optional(),path:pe.string().optional(),expires:pe.number().default(Date.now()/1e3+60*60*24*365),httpOnly:pe.boolean().optional(),secure:pe.boolean().default(!0),sameSite:pe.union([pe.literal("Strict"),pe.literal("Lax"),pe.literal("None")]).default("None")});function Ja(r,e){let t=[],n=xC(r);for(let o of n){let i=CC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=eu.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var _C=pe.object({origin:pe.string(),localStorage:pe.array(pe.object({name:pe.string(),value:pe.string()}))}),MC=pe.object({entries:pe.record(pe.string(),pe.array(pe.tuple([pe.unknown(),pe.unknown()]))),version:pe.number().optional()}),Wg=pe.object({cookies:eu.array().optional(),origins:_C.array().optional(),idb:pe.record(pe.string(),MC).optional().describe("key is db name")});function $g(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=eu.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import GC from"zod";import{v4 as BH}from"uuid";import{z as ee}from"zod";import*as Se from"zod";var qg=Se.object({requiredText:Se.string().optional(),requiredAttributes:Se.record(Se.string(),Se.string()).optional(),requiredBounds:Se.boolean().optional()}),IC=Se.object({xPath:Se.string(),requirements:qg.optional()}),PC=Se.object({type:Se.literal("NATIVE"),bounds:Se.number().array(),resolvedDescription:Se.string(),xPath:Se.string(),elementOnlySerializedXml:Se.string(),requirements:qg.optional(),requiredRelatedElements:IC.array().optional()}),OC=Se.object({type:Se.literal("WEBVIEW"),resolvedDescription:Se.string(),xPath:Se.string(),browserCache:Lr.optional()}),Kg=Se.discriminatedUnion("type",[PC,OC]);var Sn=(u=>(u.AI_CHECK="AI_CHECK",u.TAP="TAP",u.TYPE="TYPE",u.PRESS="PRESS",u.PRESS_KEYBOARD="PRESS_KEYBOARD",u.OPEN_APP="OPEN_APP",u.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",u.JAVASCRIPT="JAVASCRIPT",u.ADB="ADB",u.STATE="STATE",u))(Sn||{}),tu=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(tu||{}),ru=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(ru||{}),Yg=ee.discriminatedUnion("type",[ee.object({type:ee.literal("description"),description:ee.string()}),ee.object({type:ee.literal("coordinates"),xPercent:ee.number(),yPercent:ee.number()})]),ir=ee.object({id:ee.string().uuid(),disableCache:ee.boolean().optional()}),LC=ir.extend({type:ee.literal("STATE")}),Xg=ee.object({target:Kg}),nu=ir.extend({type:ee.literal("TAP"),target:Yg,cache:Xg.optional(),longPress:ee.boolean().optional(),longPressDurationMs:ee.number().optional()}),ou=ir.extend({type:ee.literal("TYPE"),target:Yg.optional(),cache:Xg.optional(),keyPressDelayMs:ee.number().optional(),text:ee.string(),clearContent:ee.boolean().optional()}),NC=ir.extend({type:ee.literal("OPEN_NOTIFICATION_DRAWER")}),DC=ir.extend({type:ee.literal("PRESS"),key:ee.nativeEnum(tu),longPress:ee.boolean().optional()}),kC=ir.extend({type:ee.literal("PRESS_KEYBOARD"),key:ee.nativeEnum(ru)}),UC=ir.extend({type:ee.literal("OPEN_APP"),packageName:ee.string(),activityName:ee.string().optional()}),FC=ir.extend({type:ee.literal("AI_CHECK"),assertion:ee.string(),timeoutSecs:ee.number().optional()}),BC=ir.extend({type:ee.literal("JAVASCRIPT"),code:ee.string(),timeout:ee.number().int().max(60).optional().describe("Max seconds for the code to complete")}),zC=ir.extend({type:ee.literal("ADB"),command:ee.string()}),Jg=ee.discriminatedUnion("type",[nu,ou,DC,UC,NC,FC,BC,kC,zC,LC]);var iu=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var Qg={type:!0,cache:!0},Gr=GC.discriminatedUnion("type",[nu.pick(Qg),ou.pick(Qg)]),HC=Object.values(Sn).filter(r=>Gr.options.some(e=>e.shape.type.safeParse(r).success));function Qa(r){return HC.includes(r.type)}var Zg=di(Gr),eh=pi(Gr),qH=Ua(Gr);import{cloneDeep as Ai}from"lodash-es";import th from"truncate-json";var VC="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",jC=[pn,ao],rh=[pn,ao],uo=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[pn],o=e.env[ao],i={};for(let[l,c]of Object.entries(e.env))rh.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Ai(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){jC.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[pn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Ai(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>rh.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,VC]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=th(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=th(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=Ai(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(pn,e.envName),e.testName&&this.setMomenticSystemVariable(ao,e.testName)}getDynamicVariablesCopy(){return Ai(this.env)}getVariablesFromEnvironmentCopy(){return Ai(this.varsFromMomenticEnvironment)}};var Ri=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Ri||{});import He from"zod";import{z as qt}from"zod";import{z as xe}from"zod";var $t=xe.object({id:xe.string(),name:Ka,baseUrl:Ya,description:xe.string().optional().nullish(),schemaVersion:xe.string(),advanced:yi,retries:xe.number(),envs:xe.array(ja).nullish(),parameters:Va.nullish(),disabled:xe.boolean().optional(),labels:xe.array(xe.string()).optional().catch([])}),oV=xe.enum(["INHERIT","ENABLED","DISABLED"]);var WC=yi.extend({failureRecovery:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var iV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:WC}),aV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),$C=xe.object({labels:xe.array(xe.string()).optional(),outputs:fg.nullish()}),po=$t.merge($C),qC=xe.object({createdAt:xe.coerce.date(),updatedAt:xe.coerce.date(),updatedBy:xe.string().nullable(),schedule:lo,notification:co,createdBy:xe.string(),organizationId:xe.string(),folderId:xe.string().nullable().optional()}),KC=$t.merge(qC),sV=KC.merge(oo),Za=$t.merge(oo),lV=$t.merge(cn);var YC="test",XC="module",JC="mobile-test",QC="mobile-module";var ye=(o=>(o.TEST=`momentic/${YC}`,o.MODULE=`momentic/${XC}`,o.MOBILE_TEST=`momentic/${JC}`,o.MOBILE_MODULE=`momentic/${QC}`,o))(ye||{}),hV=$t.merge(cn),nh=Nt.extend({steps:qt.array(qt.record(qt.string(),qt.unknown())),schemaVersion:qt.string()}),fV=nh.extend({fileType:qt.literal(ye.MODULE)}),SV=qt.object({test:qt.string().describe("YAML for the test, including metadata and steps"),modules:qt.record(qt.string(),qt.string()).describe("Map of module name to YAML for the module")});var au=He.object({parameterNames:He.string().array(),defaultParameters:He.record(He.string(),He.string()).optional(),parameterEnums:He.record(He.string(),He.string().array()).optional()}),ZC=He.object({moduleId:He.string().uuid(),name:He.string(),description:He.string().nullish(),parameters:au.optional(),enabled:He.boolean().nullish(),schemaVersion:He.string()}),wi=ZC.omit({name:!0}),es=wi.extend({steps:He.array(He.record(He.string(),He.unknown()))}),ex=He.object({fileType:He.literal(ye.MOBILE_MODULE)}).merge(es);import Rt from"zod";var Kt=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(Kt||{}),ts=Rt.object({id:Rt.string().uuid(),envKey:Rt.string().optional(),skipped:Rt.boolean().optional()}),Ci=ts.extend({type:Rt.literal("MOBILE_PRESET_STEP"),command:Jg,keyPressDelayMs:Rt.number().optional()}),mo=Rt.object({moduleId:Rt.string(),inputs:Rt.record(Rt.string(),Rt.string()).optional(),parameters:au.optional()}),xi=ts.merge(mo.extend({type:Rt.literal("MOBILE_MODULE_STEP")})),wV=mo.extend({steps:Rt.lazy(()=>Yt.array())}),Yt=Rt.discriminatedUnion("type",[Ci,xi]);import Ve from"zod";import rs from"zod";var wr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(wr||{}),tx=mo.extend({steps:rs.lazy(()=>_i.array()),name:rs.string().describe("name of the module")}),rx=ts.merge(tx).extend({type:rs.literal("RESOLVED_MOBILE_MODULE")}),_i=rs.discriminatedUnion("type",[rx,Ci]);function oh(r){return Object.values(wr).includes(r)||Object.values(Kt).includes(r)}var nx=Ve.object({disableDefaultWebviewAccessibilityTree:Ve.boolean().optional(),autoGrantPermissions:Ve.boolean().optional()}),su=nx.extend({region:Ve.nativeEnum(Ri).optional()}),Mi=Ve.object({retries:Ve.number().optional().describe("number of retries to run"),defaultChannel:Ve.string().optional().describe("default channel to use"),defaultTag:Ve.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ve.string().optional(),emulator:su.optional()}),ar=Ve.object({id:Ve.string().uuid(),description:Ve.string(),schemaVersion:Ve.string(),settings:Mi.optional()}),ox=ar.merge(Ve.object({steps:Ve.array(Yt)})),ns=Ve.object({fileType:Ve.literal(ye.MOBILE_TEST)}).merge(ox),BV=Ve.object({name:Ve.string(),steps:Ve.array(Yt).optional(),settings:Mi.optional()}),ix=ar.extend({steps:_i.array()});import Oe from"zod";var go=Oe.object({startTime:Oe.number(),endTime:Oe.number().optional(),error:Oe.string().optional()});var ax=go.extend({type:Oe.literal("SECTION"),name:Oe.string(),subSpans:Oe.lazy(()=>px.array())}),sx=go.extend({type:Oe.literal("AI_LOCATOR_CALL"),result:Oe.object({serializedElement:Oe.string(),id:Oe.number(),thoughts:Oe.string()}).optional()}),lx=go.extend({type:Oe.literal("AI_ASSERTION_CALL"),result:Oe.object({thoughts:Oe.string(),result:Oe.boolean()}).optional()}),cx=go.extend({type:Oe.literal("WAIT_FOR_STABILITY"),reason:Oe.string().optional()}),ux=go.extend({type:Oe.literal("RESOLVE_TARGET_CACHE"),result:Oe.object({serializedElement:Oe.string()}).optional()}),dx=go.extend({type:Oe.literal("GET_EMULATOR_STATE")}),px=Oe.discriminatedUnion("type",[ax,sx,lx,cx,ux,dx]);import Xt from"zod";var ih=Xt.object({message:Xt.string().optional(),startTime:Xt.number(),endTime:Xt.number(),status:Xt.nativeEnum(Ye),trace:Xt.unknown(),beforeSnapshot:Xt.string().optional(),afterSnapshot:Xt.string().optional(),data:Xt.unknown().optional().describe("output data from the step")}),mx=ih.merge(Ci),gx=ih.merge(xi).extend({steps:Xt.lazy(()=>yn.array())}),yn=Xt.discriminatedUnion("type",[mx,gx]);var pj=new Set(Object.values(rt));var hx={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},mj={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},gj={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},hj={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state",RESOLVED_MOBILE_MODULE:"Module"},fj={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests."};import fx from"semver";import{z as Sx}from"zod";var bj=Sx.string().refine(r=>fx.valid(r),{message:"must be a valid semver string"});import{Faker as Aj,en as Rj}from"@faker-js/faker";import{z as O}from"zod";var Cj=O.object({body:O.string(),to:O.string(),from:O.string()}),xj=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),_j=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),Mj=O.object({inbox:O.string().transform(r=>r.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),Ij=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var os=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(os||{}),ah=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),yx=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Ex=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),sh=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),Pj=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:yx,response:Ex,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(os).optional()}),Hr=15e3;import*as lt from"zod";import{extendZodWithOpenApi as bx}from"zod-openapi";bx(lt);var Tx=lt.object({url:lt.string(),lineNumber:lt.number(),columnNumber:lt.number()}).openapi({ref:"CodeLocation"}),is=lt.object({timestamp:lt.number(),text:lt.string(),type:lt.string(),tabIndex:lt.number(),args:lt.unknown().array().optional(),url:lt.string().optional(),location:Tx.optional()}).openapi({ref:"ConsoleLog"}),lh=is.array(),vx=lh.array();import*as lu from"zod";import{extendZodWithOpenApi as Hx}from"zod-openapi";import{z as C}from"zod";var Ax=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),Rx=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),wx=C.object({onContentLoad:C.number().optional(),onLoad:C.number().optional(),comment:C.string().optional()}),uh=C.object({startedDateTime:C.string(),id:C.string(),title:C.string().optional(),pageTimings:wx,comment:C.string().optional()}),Cx=C.array(uh),xx=C.object({name:C.string(),value:C.string(),path:C.string().optional(),domain:C.string().optional(),expires:C.string().optional(),httpOnly:C.boolean().optional(),secure:C.boolean().optional(),comment:C.string().optional()}),dh=C.array(xx),_x=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),ph=C.array(_x),Mx=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),Ix=C.array(Mx),Px=C.object({name:C.string(),value:C.string().optional(),fileName:C.string().optional(),contentType:C.string().optional(),comment:C.string().optional()}),Ox=C.array(Px),Lx=C.object({mimeType:C.string(),params:Ox,text:C.string(),comment:C.string().optional()}),Nx=C.object({method:C.string(),url:C.string(),httpVersion:C.string().optional(),cookies:dh,headers:ph,queryString:Ix,postData:Lx.optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional()}),Dx=C.object({size:C.number().optional(),compression:C.number().optional(),mimeType:C.string().optional(),text:C.string().optional(),encoding:C.string().optional(),comment:C.string().optional()}),kx=C.object({status:C.number(),statusText:C.string(),httpVersion:C.string().optional(),cookies:dh,headers:ph,content:Dx,redirectURL:C.string().optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional(),_mocked:C.boolean().optional()}),ch=C.object({expires:C.string().optional(),lastAccess:C.string(),eTag:C.string(),hitCount:C.number(),comment:C.string().optional()}),Ux=C.object({beforeRequest:ch.optional(),afterRequest:ch.optional(),comment:C.string().optional()}),Fx=C.object({blocked:C.number().optional(),dns:C.number().optional(),connect:C.number().optional(),send:C.number(),wait:C.number(),receive:C.number(),ssl:C.number().optional(),comment:C.string().optional()}),mh=C.object({pageref:C.string().optional(),startedDateTime:C.string(),time:C.number().optional(),request:Nx,response:kx.optional(),cache:Ux.optional(),timings:Fx,serverIPAddress:C.string().optional(),connection:C.string().optional(),comment:C.string().optional(),_resourceType:C.string().optional()}),Bx=C.array(mh),zx=C.object({version:C.string().default("1.1"),creator:Ax.optional(),browser:Rx.optional(),pages:Cx.optional(),entries:Bx,comment:C.string().optional()}),Gx=C.object({log:zx}),gh=C.record(C.string(),uh),hh=C.record(C.string(),mh);Hx(lu);var Vx=lu.object({logsPerPage:is.array().array(),harPages:gh.optional(),harEntries:hh.optional()}).openapi({ref:"DebugData"});var R=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(ge))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},ho=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Vr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
2
+ var WA=Object.defineProperty;var Ie=(r,e)=>()=>(r&&(e=r(r=0)),e);var $A=(r,e)=>{for(var t in e)WA(r,t,{get:e[t],enumerable:!0})};var wS,CS=Ie(()=>{"use strict";wS=typeof globalThis=="object"?globalThis:global});var xS=Ie(()=>{"use strict";CS()});var _S=Ie(()=>{"use strict";xS()});var Cr,Nu=Ie(()=>{"use strict";Cr="1.9.0"});function wM(r){var e=new Set([r]),t=new Set,n=r.match(MS);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(MS);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var MS,IS,PS=Ie(()=>{"use strict";Nu();MS=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;IS=wM(Cr)});function Eo(r,e,t,n){var o;n===void 0&&(n=!1);var i=Di[Ni]=(o=Di[Ni])!==null&&o!==void 0?o:{version:Cr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Cr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Cr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Cr+"."),!0}function xr(r){var e,t,n=(e=Di[Ni])===null||e===void 0?void 0:e.version;if(!(!n||!IS(n)))return(t=Di[Ni])===null||t===void 0?void 0:t[r]}function bo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Cr+".");var t=Di[Ni];t&&delete t[r]}var CM,Ni,Di,ki=Ie(()=>{"use strict";_S();Nu();PS();CM=Cr.split(".")[0],Ni=Symbol.for("opentelemetry.js.api."+CM),Di=wS});function Ui(r,e,t){var n=xr("diag");if(n)return t.unshift(e),n[r].apply(n,_M([],xM(t),!1))}var xM,_M,OS,LS=Ie(()=>{"use strict";ki();xM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_M=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))},OS=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("verbose",this._namespace,e)},r}()});var we,Is=Ie(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(we||(we={}))});function NS(r,e){r<we.NONE?r=we.NONE:r>we.ALL&&(r=we.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var DS=Ie(()=>{"use strict";Is()});var MM,IM,PM,dr,Fi=Ie(()=>{"use strict";LS();DS();Is();ki();MM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},IM=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))},PM="diag",dr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=xr("diag");if(l)return l[o].apply(l,IM([],MM(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:we.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=xr("diag"),d=NS((l=i.logLevel)!==null&&l!==void 0?l:we.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return Eo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){bo(PM,t)},t.createComponentLogger=function(o){return new OS(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var kS,US=Ie(()=>{"use strict";kS=Symbol("BaggageEntryMetadata")});function Du(r){return typeof r!="string"&&(OM.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:kS,toString:function(){return r}}}var OM,FS=Ie(()=>{"use strict";Fi();US();OM=dr.instance()});function ku(r){return Symbol.for(r)}var LM,Uu,Fu=Ie(()=>{"use strict";LM=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Uu=new LM});function Gu(){return zu}var xn,NM,Ps,DM,kM,UM,FM,Bu,BM,zM,GM,zu,HM,VM,jM,WM,$M,qM,KM,Hu=Ie(()=>{"use strict";xn=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)}}(),NM=function(){function r(){}return r.prototype.createGauge=function(e,t){return VM},r.prototype.createHistogram=function(e,t){return jM},r.prototype.createCounter=function(e,t){return HM},r.prototype.createUpDownCounter=function(e,t){return WM},r.prototype.createObservableGauge=function(e,t){return qM},r.prototype.createObservableCounter=function(e,t){return $M},r.prototype.createObservableUpDownCounter=function(e,t){return KM},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Ps=function(){function r(){}return r}(),DM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ps),kM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ps),UM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ps),FM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ps),Bu=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),BM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),zM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),GM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),zu=new NM,HM=new DM,VM=new UM,jM=new FM,WM=new kM,$M=new BM,qM=new zM,KM=new GM});var _t,BS=Ie(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(_t||(_t={}))});var YM,XM,zS,GS=Ie(()=>{"use strict";Fu();YM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},XM=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))},zS=function(){function r(){}return r.prototype.active=function(){return Uu},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,XM([n],YM(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var JM,QM,Vu,ZM,HS,VS=Ie(()=>{"use strict";GS();ki();Fi();JM=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QM=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))},Vu="context",ZM=new zS,HS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Eo(Vu,e,dr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,QM([e,t,n],JM(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return xr(Vu)||ZM},r.prototype.disable=function(){this._getContextManager().disable(),bo(Vu,dr.instance())},r}()});var To,jS=Ie(()=>{"use strict";VS();To=HS.getInstance()});var F,WS=Ie(()=>{"use strict";Fi();F=dr.instance()});var eI,$S,qS=Ie(()=>{"use strict";Hu();eI=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return zu},r}(),$S=new eI});var ju,KS,YS=Ie(()=>{"use strict";qS();ki();Fi();ju="metrics",KS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Eo(ju,e,dr.instance())},r.prototype.getMeterProvider=function(){return xr(ju)||$S},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){bo(ju,dr.instance())},r}()});var Os,XS=Ie(()=>{"use strict";YS();Os=KS.getInstance()});var he=Ie(()=>{"use strict";FS();Fu();Is();Hu();BS();jS();WS();XS()});import{Argument as ym,Command as iU,Option as aU}from"@commander-js/extra-typings";import JA from"appium";import{tmpdir as QA}from"os";import{remote as ZA}from"webdriverio";import{createInstanceClient as qA}from"@limrun/api";import{execSync as KA}from"child_process";import{hostname as YA}from"os";import XA from"path";async function Em(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:l,adbUrl:c,name:s,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:YA()}),p;try{KA("adb --version"),p="adb"}catch{if(process.env.ANDROID_HOME)p=XA.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("adb not found in PATH and ANDROID_HOME not set")}t.info({emulatorName:s,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let m=await qA({adbUrl:c,endpointUrl:l,token:a,logLevel:i,adbPath:p}),g=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];u&&g.push(u);let h=n.apkToInstall?.channel,f=n.apkToInstall?.tag;o(`Installing APK${h?` with channel ${h}`:""}${f?` and tag ${f}`:""}`),await Promise.all(g.map(b=>m.sendAsset(b))),o("Starting tunnel");let E=await m.startAdbTunnel();return{port:E.address.port,close:E.close,token:a,webRtcUrl:l,emulatorName:s}}async function wa({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,logLevel:o,appiumPort:i,socket:a}){let l=Date.now(),{close:c,port:s,limbarToken:u,limbarUrl:d,emulatorName:p}=await rR({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),m=[()=>t.deleteAndroidEmulator(p),c],g=async()=>{for(let f=m.length-1;f>=0;f-=1)try{await m[f]()}catch(E){if(E instanceof Error&&E.message.includes("ECONNREFUSED"))return;n.warn({err:E},"Error running cleanup task")}},h=async()=>{if(a&&!a.connected)throw await g(),new Error("Client disconnected before Appium driver could be started")};await h();try{let f=await eR({logger:n,logLevel:o,appiumPort:i,port:s,limbarStart:l,emulatorName:p,apiClient:t,onStatusUpdate:r,creationOpts:e});return m.push(f.appiumClose),m.push(async()=>f.driver.deleteSession()),await h(),{...f,emulatorName:p,limbarToken:u,limbarUrl:d,adbTunnelPort:s,cleanup:g,appiumPort:i}}catch(f){throw await g(),new Error(`Failed to start Appium driver: ${f}`)}}async function eR({logger:r,logLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:l,logFile:c}=await tR({logger:r,logLevel:e,appiumPort:i}),s={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":300,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0},u={hostname:"localhost",port:i,logLevel:e,capabilities:s,connectionRetryTimeout:3e4,connectionRetryCount:2},d=Date.now(),p=await ZA(u);await p.updateSettings({enableMultiWindows:!0});let m=new Map;return p.on("command",g=>{m.set(g.command,Date.now())}),p.on("result",g=>{let h=m.get(g.command);if(!h)return;let f=Date.now()-h;g.result instanceof Error?r.warn({err:g.result,command:g.command,args:g.body,durationMs:f},"Appium cmd failed"):f>1e4&&r.warn({command:g.command,args:g.body,durationMs:f},"Appium cmd took very long"),m.delete(g.command)}),r.info({timings:{limbarDuration:a-n,appiumDuration:d-a,wdioDuration:Date.now()-d},capabilities:s,emulatorName:o},"Started Appium driver"),{driver:p,appiumClose:l,appiumPort:i,appiumLogFile:c}}async function tR({logger:r,logLevel:e,appiumPort:t}){let n=`${QA()}/appium-port-${Date.now()}.log`,o=await JA.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}async function rR({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:l,emulatorName:c}=await Em({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:l,emulatorName:c}}import bm from"crypto";import nR from"fs";async function Ca({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await nR.promises.readFile(t),a=bm.createHash("md5").update(i).digest("base64"),l=bm.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===l)){o.info({channel:e,tag:r,md5:a,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let s=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(s.status!==200)throw new Error(`Got error response from emulator platform: ${s.status} ${await s.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(s){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:s},"Failed to upload asset"),s}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as wf}from"child_process";import{existsSync as D_}from"fs";import{platform as Cf}from"os";import{dirname as k_,join as U_,resolve as F_}from"path";import{z as Tm}from"zod";var IU=Tm.object({input:Tm.string()});import{z as $e}from"zod";var LU=$e.object({srcs:$e.array($e.string()),urls:$e.array($e.string()),desiredSrc:$e.string().optional(),desiredUrl:$e.string().optional()}),vm=$e.object({srcRegex:$e.string().optional(),urlRegex:$e.string().optional()}),Am=$e.object({x:$e.number(),y:$e.number(),correlation:$e.number()}),NU=$e.object({searchImageBase64String:$e.string(),pageImageBase64String:$e.string(),id:$e.string().uuid(),timeoutMs:$e.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as oR}from"zod-openapi";oR(L);var Or=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Or||{}),iR=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),gc=L.object({result:L.number(),traceId:L.string()}).array(),xa=L.object({type:L.literal("GCS_TRACES"),traces:gc}),Rm=L.object({text:L.string().optional(),attributes:L.record(L.string(),L.string()).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),aR=L.object({selectors:L.string().array(),requirements:Rm.optional()}),Lr=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Rm.optional(),additionalElements:aR.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:iR.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Or).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:xa.optional()}).openapi({ref:"ElementTargetCache"});function _a(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function hc(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var sR=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),lR=L.object({x:L.number(),y:L.number()}),cR=L.object({type:L.literal("coordinates"),pixels:lR}).openapi({ref:"CoordinatesTarget"});function Nr(r){return r.type==="description"}function nr(r){return r.type==="coordinates"}var it=L.discriminatedUnion("type",[sR,cR]).openapi({ref:"ElementTarget"});function fc(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function wm(r){return xa.safeParse(r).success}import{v4 as se}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as SR}from"zod-openapi";import{z as X}from"zod";import{extendZodWithOpenApi as uR}from"zod-openapi";import{z as qn}from"zod";var Sc=qn.object({result:qn.boolean(),traceId:qn.string()}).array(),yc=qn.object({type:qn.literal("GCS_TRACES"),traces:Sc}),Ec=qn.object({memory:yc.optional()});uR(X);var Cm=X.object({plan:X.string().optional(),evidence:X.string().optional(),thoughts:X.string(),result:X.boolean(),relevantElements:X.array(X.number()).optional(),updatedMemory:Sc.optional()}),Dr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Dr||{});var dR=X.object({type:X.literal("ELEMENT_NAME"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementNameAssertion"}),pR=X.object({type:X.literal("ELEMENT_STYLE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),property:X.string(),value:X.string()}).openapi({ref:"ElementStyleAssertion"}),mR=X.object({type:X.literal("ELEMENT_CONTENT"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementContentAssertion"}),gR=X.object({type:X.literal("ELEMENT_ATTRIBUTE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),attr:X.string(),value:X.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Kn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Kn||{}),hR=X.object({type:X.literal("ELEMENT_EXISTENCE"),negated:X.boolean().optional(),condition:X.nativeEnum(Kn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),xm=X.discriminatedUnion("type",[mR,gR,hR,dR,pR]).openapi({ref:"ManualElementAssertion"});var fR=X.object({type:X.literal("CONTENT"),negated:X.boolean().optional(),value:X.string()}).openapi({ref:"PageContentAssertion"}),_m=X.discriminatedUnion("type",[fR]).openapi({ref:"ManualPageAssertion"});import pt from"zod";var bc=pt.discriminatedUnion("type",[pt.object({type:pt.literal("SUBSTRING"),url:pt.string()}),pt.object({type:pt.literal("GLOB"),glob:pt.string()}),pt.object({type:pt.literal("REGEX"),regex:pt.string()}),pt.object({type:pt.literal("DOMAIN"),domain:pt.string()})]),Zo=pt.object({urlMatcher:bc,method:pt.string().optional()});import{z as ae}from"zod";var Ma=ae.object({url:ae.string(),method:ae.union([ae.literal("GET"),ae.literal("POST"),ae.literal("PUT"),ae.literal("DELETE"),ae.literal("PATCH")]),headers:ae.record(ae.string(),ae.string()).optional(),params:ae.record(ae.string(),ae.string()).optional(),body:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Mm=ae.object({url:ae.string(),headers:ae.record(ae.string(),ae.string()).optional(),query:ae.string(),variables:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ia=ae.object({code:ae.string(),fragment:ae.boolean().optional(),environment:ae.union([ae.literal("NODE"),ae.literal("BROWSER")]).optional().describe("default NODE"),timeout:ae.number().int().max(60).optional().describe("Max seconds for the code to complete")});var rt=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.MOCK_ROUTE="MOCK_ROUTE",H.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(rt||{});SR(y);var G=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),It=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Pt=y.object({target:Lr}).optional().openapi({ref:"SingleTargetCache"});function Pm(r){return Pt.safeParse(r).success}var Oa=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),yR=G.merge(Oa).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),La=It.merge(y.object({cache:Pt})),Yn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Xn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Jn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Qn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),iF=y.discriminatedUnion("type",[Yn,Xn,Jn,Qn]).openapi({ref:"AllScrollCommands"}),ER=G.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),bR=G.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),TR=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),vR=G.extend({type:y.literal("WAIT_FOR_URL"),matcher:bc}).merge(TR).openapi({ref:"WaitUrlCommand"}),AR=G.merge(Oa).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),RR=G.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),wR=G.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),CR=G.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),xR=G.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Tc=G.merge(It).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),_R=G.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),MR=G.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),IR=G.merge(Ia).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ei=G.merge(It).extend({type:y.literal("CLICK"),target:it,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Pt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),Om=y.object({fromTarget:Lr.optional(),toTarget:Lr.optional()}),ti=G.merge(It).merge(y.object({type:y.literal("DRAG"),fromTarget:it,toTarget:it,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:Om.optional()})).openapi({ref:"DragCommand"}),ri=G.merge(It).merge(y.object({type:y.literal("MOUSE_DRAG"),target:it.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Pt})).openapi({ref:"MouseDragCommand"}),ni=G.merge(It).merge(y.object({type:y.literal("HOVER"),target:it,cache:Pt})).openapi({ref:"HoverCommand"}),oi=G.merge(It).merge(y.object({type:y.literal("FOCUS"),target:it,cache:Pt})).openapi({ref:"FocusCommand"}),ii=G.merge(It).extend({type:y.literal("BLUR"),target:it.optional(),cache:Pt}).openapi({ref:"BlurCommand"}),PR=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),OR=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),LR=G.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[PR,OR]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),NR=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),ai=G.merge(It).extend({type:y.literal("SELECT_OPTION"),target:it,cache:Pt,choice:NR.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),vc=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Na=G.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:vc.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Ec.optional()})).openapi({ref:"AIAssertionCommand"}),kr=5,Ac=600,si=G.merge(It).extend({type:y.literal("ELEMENT_CHECK"),target:it,assertion:xm,cache:Pt.or(Ec).optional(),timeout:y.number().int().min(0).max(Ac).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),DR=G.extend({type:y.literal("PAGE_CHECK"),assertion:_m,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(Ac).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),kR=G.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),UR=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional()}),Lm=25,li=G.merge(It).merge(UR).extend({type:y.literal("TYPE"),target:it.optional(),value:y.string(),cache:Pt}).openapi({ref:"TypeCommand"}),FR=G.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),BR=G.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),zR=G.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),GR=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),HR=y.object({type:y.literal("REGEX"),pattern:y.string()}),VR=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),jR=y.discriminatedUnion("type",[GR,HR,VR]),WR=G.merge(Oa).merge(y.object({type:y.literal("TAB"),action:jR})).openapi({ref:"TabCommand"}),$R=G.merge(Oa).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),qR=G.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),KR=G.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),YR=G.extend({type:y.literal("REQUEST")}).merge(Ma).openapi({ref:"RequestCommand"}),XR=G.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Mm).openapi({ref:"GraphQLRequestCommand"}),JR=G.merge(y.object({type:y.literal("SUCCESS"),condition:Na.optional()})).openapi({ref:"SuccessCommand"}),QR=G.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ZR=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),ci=G.merge(It).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:it.optional(),screenshot:ZR.optional(),cache:Pt})).openapi({ref:"VisualDiffCommand"}),ew=G.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Zo,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),tw=G.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),rw=G.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Zo,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),nw=G.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),ow=G.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Zo.optional()})).openapi({ref:"SetHeaderCommand"}),iw=G.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Zo,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:y.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),aw=G.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),sw=G.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),Nm=y.discriminatedUnion("type",[ei,li,FR,BR,zR,ai,yR,Xn,Yn,Na,ni,bR,JR]),lw=y.discriminatedUnion("type",[kR,xR,CR,Tc,qR,_R,ER,ti,si,LR,RR,wR,IR,KR,ri,$R,DR,MR,AR,YR,XR,Jn,Qn,WR,ci,oi,ii,vR,ew,tw,rw,nw,ow,iw,aw,sw]),Zn=y.discriminatedUnion("type",[...Nm.options,...lw.options]).openapi({ref:"Command"}),Da=y.discriminatedUnion("type",[...Nm.options,QR]);function Ar(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:se(),type:r};break;case"AUTH_LOAD":{e={id:se(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:se(),type:r,goal:""};break;case"DIALOG":e={id:se(),type:r,action:"DISMISS"};break;case"DRAG":e={id:se(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:se(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:se(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:se(),type:r,delay:1};break;case"BLUR":e={id:se(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:se(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:se(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:se(),type:r,value:""};break;case"SELECT_OPTION":e={id:se(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:se(),type:r,url:""};case"TAB":e={id:se(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:se(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:se(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:se(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:se(),type:r,code:""};break;case"AI_ASSERTION":e={id:se(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:se(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:se(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:se(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:se(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:se(),type:r,key:""};break}case"SET_HEADER":{e={id:se(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:se(),type:r};break}case"OFFLINE_MODE":{e={id:se(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Dm(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as cw}from"zod";var uF=cw.discriminatedUnion("type",[ii,Tc,ei,ti,oi,ni,ri,Yn,Xn,Jn,Qn,ai,li,ci,si]);import{z as uw}from"zod";import{z as Ur}from"zod";function ui(r){return Ur.object({key:Ur.string(),testId:Ur.string().optional(),moduleId:Ur.string().optional(),organizationId:Ur.string(),value:r})}function di(r){return ui(r).extend({uniqueKey:Ur.string()})}function ka(r){return Ur.record(Ur.string(),di(r))}var mt={type:!0,cache:!0},eo=uw.discriminatedUnion("type",[Na.pick(mt),ii.pick(mt),ei.pick(mt),ti.pick(mt),si.pick(mt),oi.pick(mt),ni.pick(mt),ri.pick(mt),Yn.pick(mt),Xn.pick(mt),Jn.pick(mt),Qn.pick(mt),ai.pick(mt),li.pick(mt),ci.pick(mt)]),Rc=Object.values(rt).filter(r=>eo.options.some(e=>e.shape.type.safeParse(r).success));Zn.options.forEach(r=>{if("target"in r.shape&&!Rc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function km(r){return Rc.includes(r.type)}var Um=ui(eo),Fm=di(eo),yF=ka(eo);import{z as wc}from"zod";import{extendZodWithOpenApi as mw}from"zod-openapi";import{z as Bm}from"zod";import{extendZodWithOpenApi as dw}from"zod-openapi";import{z as sn}from"zod";var Ot=sn.object({index:sn.number().optional().describe("global index within a test (in-order traversal)"),id:sn.string(),skipped:sn.boolean().optional(),envKey:sn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:sn.boolean().optional(),retries:sn.number().optional()});dw(Bm);var pw=Ot.extend({type:Bm.literal("PRESET_ACTION")}),Lt=pw.extend({command:Zn}).openapi({ref:"PresetAction"});mw(wc);var ln=Ot.extend({type:wc.literal("AI_ACTION"),text:wc.string(),steps:Lt.array().optional()}).openapi({ref:"AIAction"});import{z as gt}from"zod";import{z as Ua}from"zod";import{extendZodWithOpenApi as gw}from"zod-openapi";gw(Ua);var to=Ot.extend({type:Ua.literal("AI_ACTION_DYNAMIC"),text:Ua.string(),retries:Ua.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as zm}from"zod";var Cc=Ot.extend({type:zm.literal("CONDITIONAL"),skipped:zm.boolean().optional()});import{z as ne}from"zod";var hw=ne.object({cacheKey:ne.string(),cacheExpiryMs:ne.number()}),xc=Ot.extend({id:ne.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ne.record(ne.string()).optional(),cacheConfig:hw.optional()}),Rr=xc.extend({type:ne.literal("MODULE"),moduleId:ne.string().uuid()}),fw=ne.union([Rr.pick({type:!0,moduleId:!0}),ne.record(ne.unknown())]),Sw=ne.object({type:ne.literal("URL_REGEX"),regex:ne.string()}),yw=ne.object({type:ne.literal("PAGE_CHECK"),substring:ne.string()}),_c=ne.object({cacheInvalidation:ne.discriminatedUnion("type",[yw,Sw]).optional()}),Nt=ne.object({moduleId:ne.string().uuid(),name:ne.string(),description:ne.string().nullish(),enabled:ne.boolean().nullish(),parameters:ne.string().array().nullish(),defaultParameters:ne.record(ne.string(),ne.string()).nullish(),parameterEnums:ne.record(ne.string(),ne.string().array()).nullish(),defaultCacheKey:ne.string().nullish(),defaultCacheTtl:ne.number().nullish(),defaultCacheAllInvocations:ne.boolean().nullish(),autoAuth:ne.boolean().nullish(),advanced:_c.nullish()});import{z as Dt}from"zod";var Gm=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Gm||{});var Ew=Dt.discriminatedUnion("type",[Dt.object({type:Dt.literal("NAVIGATE_URL"),url:Dt.string().url()}),Dt.object({type:Dt.literal("GO_TO_SECTION_START")})]),bw=Dt.object({trigger:Dt.nativeEnum(Gm).optional(),attempts:Dt.number().int().optional(),restartBehavior:Ew}),pi=Ot.extend({type:Dt.literal("SECTION"),description:Dt.string().describe("user provided goal of what the section should accomplish"),plan:Dt.string().array().optional(),autohealingConfig:bw.optional()});var Hm=Nt.merge(xc).extend({type:gt.literal("RESOLVED_MODULE"),steps:gt.lazy(()=>Ke.array())}),mi=Nt.extend({steps:gt.lazy(()=>Ke.array())}),Mc=pi.extend({steps:gt.lazy(()=>ht.array())}),Tw=pi.extend({steps:gt.lazy(()=>Ke.array())}),ro=Cc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>ht.array())}).array(),elseSteps:gt.lazy(()=>ht.array().optional())}),vw=Cc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>Ke.array())}).array(),elseSteps:gt.lazy(()=>Ke.array().optional())}),ht=gt.discriminatedUnion("type",[Lt,ln,to,Rr,ro,Mc]),Ke=gt.discriminatedUnion("type",[Lt,ln,to,Hm,vw,Tw]);import{z as kt}from"zod";var Aw=kt.object({steps:ht.array(),beforeSteps:ht.array().nullish(),afterSteps:ht.array().nullish()}),no=kt.object({steps:Ke.array(),beforeSteps:Ke.array().nullish(),afterSteps:Ke.array().nullish()}),cn=kt.object({steps:kt.record(kt.string(),kt.unknown()).array(),beforeSteps:kt.record(kt.string(),kt.unknown()).array().nullish(),afterSteps:kt.record(kt.string(),kt.unknown()).array().nullish()});var un="1.0.21",Ic="0.0.1";var Vm=I.object({phrase:I.string()}),Pc=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),nz=I.object({text:I.string()}),jm=I.object({attributes:I.array(I.string()).optional(),text:I.boolean().optional(),boundingBox:I.boolean().optional()}),Rw=I.object({id:I.number().int(),requirements:jm}),ww=Rw.array(),Wm=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:gc.optional(),requirements:jm.optional(),additionalElements:ww.optional()});var Oc=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(Oc||{}),$m=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))($m||{});var qm=I.object({thoughts:I.string(),category:I.nativeEnum(Oc)}),Km=I.object({thoughts:I.string(),category:I.nativeEnum($m)}),Cw=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),oz=I.object({thoughts:I.string(),patches:Cw.array()}),xw=[I.literal("add"),I.literal("replace"),I.literal("remove")],_w=I.object({op:I.union(xw),path:I.string(),value:Ke.optional()}),Ym=I.object({patches:_w.array(),thoughts:I.string()}),Xm=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Xm||{}),Jm=I.object({thoughts:I.string(),scenario:I.nativeEnum(Xm),instructions:I.string().nullish()}),Qm=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),iz=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),az=I.object({observations:I.string(),reasoning:I.string(),command:Da});var Lc=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),Mw=I.object({startId:I.number().int(),endId:I.number().int()}),Zm=I.object({categoryThoughts:I.string(),category:I.string(),relevantSections:Mw.array()});import{z as _}from"zod";import*as J from"zod";var pz=J.object({thoughts:J.string().optional().describe("only provided if a description was provided"),target:Lr.optional().describe("only provided if a description was provided"),pageState:J.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:J.object({label:J.string(),value:J.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:J.object({data:J.string(),height:J.number().int(),width:J.number().int()}).optional().describe("only provided if returnScreenshot is true")}),eg=J.union([J.literal("ELEMENT_CHECK"),J.literal("NEGATED_CHECK"),J.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),J.literal("SELECT_OPTION"),J.literal("TYPE")]);function gi(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var hi=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(hi||{}),oo=J.object({matched:J.boolean(),reason:J.string().optional().describe("Human understandable description"),logs:J.string().array().optional().describe("Logs for debugging")}),Iw=oo.extend({type:J.literal("USER_SELECTOR")}),Pw=oo.extend({type:J.literal("CSS_SELECTOR"),selectors:J.string().array()}),Ow=oo.extend({type:J.literal("HYBRID_SELECTOR")}),Lw=oo.extend({type:J.literal("HTML_DISTANCE"),distance:J.number().optional(),closestElement:J.string().optional(),savedElement:J.string().optional()}),Nw=oo.extend({type:J.literal("TEMPLATE_MATCHING"),elementImageUrl:J.string().url()}),Dw=oo.extend({type:J.literal("AUTO_FRAME"),logs:J.string().array().optional()}),tg=J.discriminatedUnion("type",[Iw,Pw,Ow,Lw,Nw,Dw]);import{z as Ei}from"zod";import{z as $w}from"zod";import*as z from"zod";import{extendZodWithOpenApi as Fw}from"zod-openapi";import{cloneDeep as Az}from"lodash-es";import wz from"truncate-json";import*as mn from"zod";import{extendZodWithOpenApi as kw}from"zod-openapi";import{z as at}from"zod";import{z as fe}from"zod";var Nc=fe.object({autoFollowNewTabs:fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:fe.union([fe.boolean(),fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:fe.boolean().optional(),disableSecondaryCacheResolution:fe.boolean().optional(),hybridSelectorMode:fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:fe.boolean().optional(),visualActions:fe.boolean().optional(),autoExpandIframes:fe.boolean().optional(),disableHtmlSnapshots:fe.boolean().optional(),importantAttributes:fe.string().array().optional(),importantClasses:fe.string().array().optional(),importantStyles:fe.string().array().optional()});var rg=1e4,ng=6e4,dn=Nc.extend({pageLoadTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=ng&&r>=-1,{message:`Page load timeout must be between 0 and ${ng/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=rg&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${rg/1e3} seconds`}),localChromeExtensionPaths:fe.string().array().optional(),extraHeaders:fe.record(fe.string(),fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:fe.string().optional(),disableGpu:fe.boolean().optional(),bustCacheOnBoundingBoxChange:fe.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var Dc="BASE_URL";var pn="ENV_NAME",io="TEST_NAME",yz={[Dc]:"https://www.google.com"},og=at.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),ig=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.string().describe("variable value"))}),ag=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value")),browser:dn.optional()});var Ez=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value"))});kw(mn);var kc=mn.object({env:mn.record(mn.unknown())}).openapi({ref:"TestContextSnapshot"});var Ye=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ye||{}),Uc=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Uc||{});import{z as or}from"zod";import{extendZodWithOpenApi as Uw}from"zod-openapi";Uw(or);var ge=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(ge||{});var Fc=or.object({reason:or.nativeEnum(ge),previousStepsDescription:or.array(or.string()).optional(),summary:or.string(),rootCause:or.string().optional()}).openapi({ref:"TestResultClassification"}),Fa=or.object({errorMessage:or.string(),errorStack:or.string().optional(),classification:Fc.optional()}).openapi({ref:"TestFailureDetails"});Fw(z);var Bc=z.object({beforeUrl:z.string().optional(),afterUrl:z.string().optional(),message:z.string().optional(),beforeSnapshot:z.string().optional(),afterSnapshot:z.string().optional(),startedAt:z.coerce.date(),finishedAt:z.coerce.date()}),Bw=Bc.extend({viewport:z.object({height:z.number(),width:z.number()}).nullish(),status:z.nativeEnum(Uc),message:z.string().optional(),elementInteracted:z.string().optional()}),gn=Bc.extend({status:z.nativeEnum(Ye),message:z.string().optional(),data:z.unknown().optional(),beforeTestContext:kc.optional(),afterTestContext:kc.optional(),failureReason:z.nativeEnum(ge).optional(),details:z.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),sg=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(sg||{}),Ba=gn.merge(Lt).extend({results:Bw.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:z.lazy(()=>Qe.array()).optional(),failureRecoveryStatus:z.object({type:z.nativeEnum(sg),message:z.string()}).optional()}),zw=gn.merge(ln).extend({results:z.lazy(()=>Ba.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Gw=gn.merge(to).extend({results:z.lazy(()=>Ba.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Hw=gn.merge(Rr).extend({moduleName:z.string().optional(),results:z.lazy(()=>Qe.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Vw=gn.merge(ro).extend({assertion:Ba.optional(),results:z.lazy(()=>Qe.array()).describe("results for the block actually executed"),previousAttempts:z.lazy(()=>Qe.array()).optional()}),jw=gn.merge(pi).extend({results:z.lazy(()=>Qe.array()),healingAttempts:z.lazy(()=>Qe.array().array()).optional(),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Qe=z.discriminatedUnion("type",[zw,Gw,Ba,Hw,Vw,jw]),jz=gn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Ww=Bc.extend({index:z.number().optional(),description:z.string(),pageState:z.string().optional(),elementInteracted:z.string().optional(),startedAt:z.coerce.date().or(z.string()).optional().catch(void 0),finishedAt:z.coerce.date().or(z.string()).optional().catch(void 0)}),za=Ww.extend({beforeScreenshot:z.string().optional(),afterScreenshot:z.string().optional()});var zc=$w.object({results:Qe.array().describe("main results"),beforeResults:Qe.array().optional(),afterResults:Qe.array().optional()}),fi=zc.partial();import{z as k}from"zod";import{extendZodWithOpenApi as Zw}from"zod-openapi";var ao=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(ao||{});import{isValidCron as qw}from"cron-validator";import{z as Q}from"zod";import{z as Gc}from"zod";var Fr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Fr||{});var Ga=Gc.object({width:Gc.number().min(200).max(1e4),height:Gc.number().min(200).max(1e4)}),lg={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},Jz=Object.keys(lg);var Br=lg["Desktop Large"],cg="en-us",ug="America/Los_Angeles";var dg={latitude:37.7749,longitude:-122.4194};var pg=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var mg=2e3,Kw=dn.extend({browserType:Q.nativeEnum(Fr).optional(),slowMoMs:Q.number().optional().refine(r=>r===void 0||r<=mg&&r>=-1,{message:`Slow motion must be between 0 and ${mg} milliseconds`}),basicAuthorization:Q.object({username:Q.string().optional(),password:Q.string().optional()}).optional(),geolocation:Q.object({latitude:Q.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Q.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Q.boolean().optional(),locale:Q.string().optional(),timezone:Q.enum(pg).optional(),colorScheme:Q.enum(["light","dark"]).optional()});var Hc=Q.object({useMemory:Q.boolean().optional(),failureRecovery:Q.boolean().optional().describe("undefined means inherit org settings")}),Yw=Hc.extend({disableAICaching:Q.boolean().optional(),failureRecoveryInstructions:Q.string().optional()}),Xw=Q.object({viewport:Ga.optional()}),Si=Xw.merge(Yw).merge(Kw),so=Q.object({cron:Q.string().refine(r=>qw(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Q.boolean().default(!1),env:Q.string().optional(),timeZone:Q.string().default("America/Los_Angeles"),jobKey:Q.string().optional()}),lo=Q.object({onSuccess:Q.boolean().default(!1),failureMessage:Q.string().optional(),onFailure:Q.boolean().default(!0),successMessage:Q.string().optional()}),Jw=Q.object({name:Q.string(),required:Q.boolean().optional(),defaultValue:Q.string().describe("this is not optional because we need a value when the editor is first loaded")}),Ha=Jw.array(),Qw=Q.object({name:Q.string(),value:Q.string()}),gg=Qw.array(),Va=Q.object({name:Q.string(),default:Q.boolean().optional(),fixtures:og.array().optional()});Zw(k);var Ut={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},me=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(me||{}),ja=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(ja||{});var ze=k.string().pipe(k.coerce.date()).or(k.date()),yi=k.object({id:k.string(),runKey:k.string(),organizationId:k.string(),executionType:k.nativeEnum(ao).optional().default("WEB"),createdAt:ze,createdBy:k.string(),flake:k.boolean().nullish(),scheduledAt:ze.or(k.null()),startedAt:ze.or(k.null()),updatedAt:ze.nullish(),finishedAt:ze.or(k.null()),resolvedBaseUrl:k.string().nullish(),environmentName:k.string().nullish(),gitBranchName:k.string().nullish(),githubRepository:k.string().nullish(),gitlabProjectPath:k.string().nullish(),labels:k.array(k.string()).optional(),gitOriginUrl:k.string().nullish(),gitCommitSha:k.string().nullish(),gitCommitShaShort:k.string().nullish(),gitCommitAuthorName:k.string().nullish(),cliVersion:k.string().nullish(),section:k.nativeEnum(ja).nullish(),status:k.nativeEnum(me),trigger:k.nativeEnum(Ut),attempts:k.number(),runAttempts:k.array(k.object({id:k.string(),status:k.nativeEnum(me),startedAt:ze.or(k.null()),finishedAt:ze.or(k.null())})).optional(),videos:k.array(k.string()).optional(),failureReason:k.nativeEnum(ge).nullish(),failureDetails:Fa.nullish(),failureRecoveryDetails:k.record(k.string(),k.unknown()).nullish(),pipelineId:k.string().nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),quarantined:k.boolean().nullish().default(!1),quarantinedReason:k.string().nullish(),localTestId:k.string().nullish(),testId:k.string().nullish(),testName:k.string().nullish(),description:k.string().nullish(),test:k.object({name:k.string(),id:k.string()}).nullish().default(null),suiteId:k.string().nullish()}).openapi({ref:"RunMetadata"}),eC={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Wa=yi.pick({...eC,test:!0}),hg=yi.omit({failureReason:!0,failureDetails:!0,test:!0}),Vc=yi.extend({stepsSnapshot:k.array(k.record(k.unknown())).nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),test:k.object({name:k.string(),id:k.string(),description:k.string().nullish(),baseUrl:k.string().nullish(),advanced:Si.nullish()}).nullish()}).merge(zc);var tC=Ei.object({id:Ei.string().uuid(),startedAt:ze.or(Ei.null()),finishedAt:ze.or(Ei.null()),status:Ei.nativeEnum(me)}).merge(fi),E1=tC.array();import{z as Ge}from"zod";var rC=Ge.object({id:Ge.string(),status:Ge.nativeEnum(me),trigger:Ge.nativeEnum(Ut),createdAt:ze,startedAt:ze.nullish(),finishedAt:ze.nullish(),gitCommitSha:Ge.string().nullish(),gitCommitShaShort:Ge.string().nullish(),gitCommitTimestamp:ze.nullish(),gitBranchName:Ge.string().nullish(),gitOriginUrl:Ge.string().nullish(),gitCommitMessage:Ge.string().nullish(),gitCommitAuthorName:Ge.string().nullish(),githubRepository:Ge.string().nullish(),gitlabProjectPath:Ge.string().nullish(),pipelineId:Ge.string().nullish(),cliVersion:Ge.string().nullish(),labels:Ge.string().array().optional(),suite:Ge.object({id:Ge.string(),name:Ge.string()}).nullish(),runs:Ge.object({status:Ge.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),fg=rC.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Wa.array()});import{z as Ze}from"zod";var nC=Ze.object({type:Ze.literal("TARGETING"),name:Ze.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:tg.array(),pageState:Ze.string().optional(),targetSource:Ze.nativeEnum(Or).optional(),targetUpdateTime:Ze.string().optional()}),oC=Ze.object({type:Ze.literal("AI_LOCATION"),matched:Ze.boolean(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional(),thoughts:Ze.string().optional()}),iC=Ze.object({type:Ze.literal("ASSERTION"),relevantElementsSerialized:Ze.string().array().optional(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional()}),aC=Ze.discriminatedUnion("type",[nC,oC,iC]);import{z as Ue}from"zod";var sC=Ue.object({id:Ue.string(),name:Ue.string()}),L1=sC.merge(Ue.object({createdAt:ze,createdBy:Ue.string(),schedule:so,notification:lo,environment:Ue.object({name:Ue.string()}).nullish(),beforeTests:Ue.object({id:Ue.string()}).array().nullish(),afterTests:Ue.object({id:Ue.string()}).array().nullish()})),Sg=Ue.object({id:Ue.string().uuid(),orgId:Ue.string(),createdAt:ze,startedAt:ze.or(Ue.null()),finishedAt:ze.or(Ue.null()),status:Ue.nativeEnum(me),trigger:Ue.nativeEnum(Ut),suite:Ue.object({id:Ue.string(),name:Ue.string()}).nullish(),runs:yi.array()}),N1=Sg.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),yg=Sg.extend({runs:Wa.array()});import{z as Ft}from"zod";import{cloneDeep as U1}from"lodash-es";import{z as le}from"zod";var V1=le.object({thoughts:le.string(),subGoals:le.object({instruction:le.string()}).array()}),j1=le.object({thoughts:le.string(),newPlanMarkdown:le.string()}),W1=le.object({thoughts:le.string(),correct:le.boolean(),failedActionIndex:le.number().optional()}),lC=le.object({type:le.literal("PLANNING"),beforePlan:le.string(),goalDecision:le.string(),thoughts:le.string()}),cC=le.object({type:le.literal("RUNNING"),stepDisplayName:le.string(),status:le.nativeEnum(Ye),results:Qe.array()}),uC=le.object({type:le.literal("REVISING"),beforePlan:le.string(),afterPlan:le.string(),errString:le.string(),diffs:le.string(),thoughts:le.string()}),dC=le.object({type:le.literal("SYSTEM"),message:le.string()}),pC=le.discriminatedUnion("type",[lC,cC,uC,dC]),Eg=pC.array();var X1=Ft.object({id:Ft.string(),scheduledAt:Ft.coerce.date().nullable(),startedAt:Ft.coerce.date().nullable(),finishedAt:Ft.coerce.date().nullable(),status:Ft.nativeEnum(me),history:Eg.nullable(),testPlan:Ft.object({id:Ft.string(),name:Ft.string()}).nullable(),test:Ft.object({id:Ft.string(),name:Ft.string()}).nullable()});import{z as ft}from"zod";var jc=ft.object({content:ft.string(),ids:ft.string().array(),tokenLength:ft.number()}),mC=ft.object({chunks:jc.array()}),mG=ft.object({ids:ft.string().array(),score:ft.number(),tokenLength:ft.number()}),gG=mC.extend({description:ft.string().describe("Input to pass to RAG engine"),tokenLimit:ft.number()}),bg=ft.object({ids:ft.number().array()}),Tg=ft.object({indices:ft.number().array()});var st=_.object({disableCache:_.boolean().optional(),useMemory:_.boolean().optional(),loggerTags:_.record(_.string(),_.string()).optional(),langfuseSessionId:_.string().optional(),agentConfigVersion:_.string().optional()}),vG=st.extend({chunks:jc.array(),description:_.string().describe("Input to pass to AI"),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),softTokenLimit:_.number(),hardTokenLimit:_.number()}),gC=_.object({screenshotBase64AfterCommand:_.string(),urlAfterCommand:_.string(),serializedCommand:_.string(),elementInteracted:_.string().optional(),thoughts:_.string().optional()}),vg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),source:eg.optional().catch(void 0),memory:_.discriminatedUnion("type",[xa,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional()}),Ag=_.object({target:_.string().or(_.number()),browserState:_.string().optional(),screenshot:_.string().optional(),boundingBox:_.object({x:_.number(),y:_.number(),height:_.number(),width:_.number()}).optional()}),Rg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string().optional(),returnSchema:_.string().optional()}),hC=_.literal("NEGATED_CHECK"),wg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),url:_.string(),contextChoice:vc.optional(),memory:_.discriminatedUnion("type",[yc,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional(),source:hC.optional()}),Cg=_.object({command:Zn}),xg=_.object({message:_.string()}),Wc=_.object({goal:_.string(),browserState:_.string(),startingScreenshot:_.string().optional(),screenshot:_.string(),url:_.string(),history:gC.array(),actionHint:_.string().optional(),lastError:_.string().optional()}),_g=_.object({results:za.array(),errorMessage:_.string(),errorStack:_.string().optional()}),Mg=_.object({results:za.array(),goal:_.string(),errorMessage:_.string()}),Ig=_.object({failedResults:za.array(),nextStepsSerialized:_.string().array(),currentUrl:_.string(),currentPageState:_.string(),currentScreenshot:_.string(),customInstructions:_.string().optional(),testDescription:_.string().optional()}),AG=_.object({description:_.string(),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),excerpt:_.string()}),Pg=_.object({type:_.string(),browserContext:_.string(),currentStep:_.string(),screenshot:_.string()});import{z as bi}from"zod";var CG=bi.object({goal:bi.string()}),Og=bi.object({keywords:bi.array(bi.string())});import{z as $c}from"zod";var $a=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))($a||{}),MG=$c.nativeEnum($a),fC=$c.enum(["v1","v2"]),IG=fC.or($c.string().describe("for people with special configurations"));import{z as Pe}from"zod";var Lg=Pe.object({attributesRequired:Pe.array(Pe.string()).optional(),textRequired:Pe.boolean().optional(),boundsRequired:Pe.boolean().optional()}),Ng=Pe.object({id:Pe.number(),thoughts:Pe.string(),requirements:Lg.optional(),additionalElements:Pe.object({id:Pe.number(),requirements:Lg}).array().optional()}),Dg=Pe.object({description:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),kg=Pe.object({assertion:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),Ug=Pe.object({thoughts:Pe.string(),result:Pe.boolean(),relevantElements:Pe.array(Pe.number()).optional()});import{z as hn}from"zod";var Fg=hn.object({id:hn.string().uuid(),skipped:hn.boolean().optional(),envKey:hn.string().optional().describe("key in the environment to save the result of this step to")}),qc=Fg.merge(Ma).extend({type:hn.literal("REQUEST")}),Kc=Fg.merge(Ia).extend({type:hn.literal("JAVASCRIPT")}),Yc=hn.discriminatedUnion("type",[Kc,qc]);import{z as Bt}from"zod";import{z as fn}from"zod";var SC=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,zr=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var qa=fn.string().min(1).max(255).superRefine((r,e)=>{try{Xc(r)}catch(t){return e.addIssue({code:fn.ZodIssueCode.custom,message:t.message,fatal:!0}),fn.NEVER}});function Xc(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(SC))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ka=fn.preprocess(r=>r===null?"":r,fn.union([fn.string().url(),fn.literal("")])).optional();var Bg=Bt.object({id:Bt.string(),name:qa,description:Bt.string().optional().nullish(),baseUrl:Ka.nullish(),schemaVersion:Bt.string(),advanced:Bt.unknown().optional(),retries:Bt.number(),envs:Bt.array(Va).nullish(),parameters:Ha.nullish()}),yC=Bt.object({createdAt:Bt.coerce.date(),updatedAt:Bt.coerce.date(),schedule:so.nullish(),notification:lo.nullish(),createdBy:Bt.string(),organizationId:Bt.string()}),EC=Bg.merge(yC),rH=EC.extend({steps:Yc.array()}),nH=Bg.extend({steps:Yc.array()});import{z as vt}from"zod";var zg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date(),status:vt.nativeEnum(Ye),message:vt.string().optional(),data:vt.unknown().optional()}),bC=zg.merge(Kc).extend({type:vt.literal("JAVASCRIPT")}),TC=zg.merge(qc).extend({type:vt.literal("REQUEST")}),vC=vt.discriminatedUnion("type",[bC,TC]),Gg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date().nullish(),status:vt.nativeEnum(me),results:vC.array(),failureReason:vt.string().nullish(),failureDetails:Fa.nullish()});import{z as At}from"zod";var AC=At.object({id:At.string(),organizationId:At.string(),createdAt:At.coerce.date(),updatedAt:At.coerce.date(),createdBy:At.string(),scheduledAt:At.coerce.date().nullish(),startedAt:At.coerce.date().nullish(),finishedAt:At.coerce.date().nullish(),status:At.nativeEnum(me),trigger:At.nativeEnum(Ut),results:Gg.array().nullish(),apiTestName:At.string().nullish(),apiTestPath:At.string().nullish(),apiTestId:At.string().nullish()}),mH=AC.pick({status:!0,startedAt:!0,finishedAt:!0});var Ti=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Ti||{}),Hg=3;function RC(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Jc(r){if(!RC(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Qc(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return Hg;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Ya=class{trackStepExecution(){}async flush(){}};import{parseString as wC,splitCookiesString as CC}from"set-cookie-parser";import{z as de}from"zod";var Zc=de.object({name:de.string(),value:de.string(),url:de.string().optional(),domain:de.string().optional(),path:de.string().optional(),expires:de.number().default(Date.now()/1e3+60*60*24*365),httpOnly:de.boolean().optional(),secure:de.boolean().default(!0),sameSite:de.union([de.literal("Strict"),de.literal("Lax"),de.literal("None")]).default("None")});function Xa(r,e){let t=[],n=CC(r);for(let o of n){let i=wC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=Zc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var xC=de.object({origin:de.string(),localStorage:de.array(de.object({name:de.string(),value:de.string()}))}),_C=de.object({entries:de.record(de.string(),de.array(de.tuple([de.unknown(),de.unknown()]))),version:de.number().optional()}),Vg=de.object({cookies:Zc.array().optional(),origins:xC.array().optional(),idb:de.record(de.string(),_C).optional().describe("key is db name")});function jg(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Zc.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import GC from"zod";import{v4 as kH}from"uuid";import{z as Z}from"zod";import*as Se from"zod";var Wg=Se.object({requiredText:Se.string().optional(),requiredAttributes:Se.record(Se.string(),Se.string()).optional(),requiredBounds:Se.boolean().optional()}),MC=Se.object({xPath:Se.string(),requirements:Wg.optional()}),IC=Se.object({type:Se.literal("NATIVE"),bounds:Se.number().array(),resolvedDescription:Se.string(),xPath:Se.string(),elementOnlySerializedXml:Se.string(),requirements:Wg.optional(),requiredRelatedElements:MC.array().optional()}),PC=Se.object({type:Se.literal("WEBVIEW"),resolvedDescription:Se.string(),xPath:Se.string(),browserCache:Lr.optional()}),$g=Se.discriminatedUnion("type",[IC,PC]);var Sn=(u=>(u.AI_CHECK="AI_CHECK",u.TAP="TAP",u.TYPE="TYPE",u.PRESS="PRESS",u.PRESS_KEYBOARD="PRESS_KEYBOARD",u.OPEN_APP="OPEN_APP",u.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",u.JAVASCRIPT="JAVASCRIPT",u.ADB="ADB",u.STATE="STATE",u))(Sn||{}),eu=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(eu||{}),tu=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(tu||{}),qg=Z.discriminatedUnion("type",[Z.object({type:Z.literal("description"),description:Z.string()}),Z.object({type:Z.literal("coordinates"),xPercent:Z.number(),yPercent:Z.number()})]),OC=Z.object({updatedAt:Z.coerce.date().optional()}),ir=Z.object({id:Z.string().uuid(),disableCache:Z.boolean().optional()}),LC=ir.extend({type:Z.literal("STATE")}),Kg=OC.extend({target:$g}),ru=ir.extend({type:Z.literal("TAP"),target:qg,cache:Kg.optional(),longPress:Z.boolean().optional(),longPressDurationMs:Z.number().optional()}),nu=ir.extend({type:Z.literal("TYPE"),target:qg.optional(),cache:Kg.optional(),keyPressDelayMs:Z.number().optional(),text:Z.string(),clearContent:Z.boolean().optional()}),NC=ir.extend({type:Z.literal("OPEN_NOTIFICATION_DRAWER")}),DC=ir.extend({type:Z.literal("PRESS"),key:Z.nativeEnum(eu),longPress:Z.boolean().optional()}),kC=ir.extend({type:Z.literal("PRESS_KEYBOARD"),key:Z.nativeEnum(tu)}),UC=ir.extend({type:Z.literal("OPEN_APP"),packageName:Z.string(),activityName:Z.string().optional()}),FC=ir.extend({type:Z.literal("AI_CHECK"),assertion:Z.string(),timeoutSecs:Z.number().optional()}),BC=ir.extend({type:Z.literal("JAVASCRIPT"),code:Z.string(),timeout:Z.number().int().max(60).optional().describe("Max seconds for the code to complete")}),zC=ir.extend({type:Z.literal("ADB"),command:Z.string()}),Yg=Z.discriminatedUnion("type",[ru,nu,DC,UC,NC,FC,BC,kC,zC,LC]);var ou=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var Xg={type:!0,cache:!0},Gr=GC.discriminatedUnion("type",[ru.pick(Xg),nu.pick(Xg)]),HC=Object.values(Sn).filter(r=>Gr.options.some(e=>e.shape.type.safeParse(r).success));function Ja(r){return HC.includes(r.type)}var Jg=ui(Gr),Qg=di(Gr),jH=ka(Gr);import{cloneDeep as vi}from"lodash-es";import Zg from"truncate-json";var VC="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",jC=[pn,io],eh=[pn,io],co=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[pn],o=e.env[io],i={};for(let[l,c]of Object.entries(e.env))eh.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=vi(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){jC.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[pn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return vi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>eh.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,VC]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Zg(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Zg(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=vi(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(pn,e.envName),e.testName&&this.setMomenticSystemVariable(io,e.testName)}getDynamicVariablesCopy(){return vi(this.env)}getVariablesFromEnvironmentCopy(){return vi(this.varsFromMomenticEnvironment)}};var Ai=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Ai||{});import He from"zod";import{z as qt}from"zod";import{z as xe}from"zod";var $t=xe.object({id:xe.string(),name:qa,baseUrl:Ka,description:xe.string().optional().nullish(),schemaVersion:xe.string(),advanced:Si,retries:xe.number(),envs:xe.array(Va).nullish(),parameters:Ha.nullish(),disabled:xe.boolean().optional(),labels:xe.array(xe.string()).optional().catch([])}),tV=xe.enum(["INHERIT","ENABLED","DISABLED"]);var WC=Si.extend({failureRecovery:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var rV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:WC}),nV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),$C=xe.object({labels:xe.array(xe.string()).optional(),outputs:gg.nullish()}),uo=$t.merge($C),qC=xe.object({createdAt:xe.coerce.date(),updatedAt:xe.coerce.date(),updatedBy:xe.string().nullable(),schedule:so,notification:lo,createdBy:xe.string(),organizationId:xe.string(),folderId:xe.string().nullable().optional()}),KC=$t.merge(qC),oV=KC.merge(no),Qa=$t.merge(no),iV=$t.merge(cn);var YC="test",XC="module",JC="mobile-test",QC="mobile-module";var ye=(o=>(o.TEST=`momentic/${YC}`,o.MODULE=`momentic/${XC}`,o.MOBILE_TEST=`momentic/${JC}`,o.MOBILE_MODULE=`momentic/${QC}`,o))(ye||{}),pV=$t.merge(cn),th=Nt.extend({steps:qt.array(qt.record(qt.string(),qt.unknown())),schemaVersion:qt.string()}),mV=th.extend({fileType:qt.literal(ye.MODULE)}),gV=qt.object({test:qt.string().describe("YAML for the test, including metadata and steps"),modules:qt.record(qt.string(),qt.string()).describe("Map of module name to YAML for the module")});var iu=He.object({parameterNames:He.string().array(),defaultParameters:He.record(He.string(),He.string()).optional(),parameterEnums:He.record(He.string(),He.string().array()).optional()}),ZC=He.object({moduleId:He.string().uuid(),name:He.string(),description:He.string().nullish(),parameters:iu.optional(),enabled:He.boolean().nullish(),schemaVersion:He.string()}),Ri=ZC.omit({name:!0}),Za=Ri.extend({steps:He.array(He.record(He.string(),He.unknown()))}),ex=He.object({fileType:He.literal(ye.MOBILE_MODULE)}).merge(Za);import Rt from"zod";var Kt=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(Kt||{}),es=Rt.object({id:Rt.string().uuid(),envKey:Rt.string().optional(),skipped:Rt.boolean().optional()}),wi=es.extend({type:Rt.literal("MOBILE_PRESET_STEP"),command:Yg,keyPressDelayMs:Rt.number().optional()}),po=Rt.object({moduleId:Rt.string(),inputs:Rt.record(Rt.string(),Rt.string()).optional(),parameters:iu.optional()}),Ci=es.merge(po.extend({type:Rt.literal("MOBILE_MODULE_STEP")})),vV=po.extend({steps:Rt.lazy(()=>Yt.array())}),Yt=Rt.discriminatedUnion("type",[wi,Ci]);import Ve from"zod";import ts from"zod";var wr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(wr||{}),tx=po.extend({steps:ts.lazy(()=>xi.array()),name:ts.string().describe("name of the module")}),rx=es.merge(tx).extend({type:ts.literal("RESOLVED_MOBILE_MODULE")}),xi=ts.discriminatedUnion("type",[rx,wi]);function rh(r){return Object.values(wr).includes(r)||Object.values(Kt).includes(r)}var nx=Ve.object({disableDefaultWebviewAccessibilityTree:Ve.boolean().optional(),autoGrantPermissions:Ve.boolean().optional()}),au=nx.extend({region:Ve.nativeEnum(Ai).optional()}),_i=Ve.object({retries:Ve.number().optional().describe("number of retries to run"),defaultChannel:Ve.string().optional().describe("default channel to use"),defaultTag:Ve.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ve.string().optional(),emulator:au.optional()}),ar=Ve.object({id:Ve.string().uuid(),description:Ve.string(),schemaVersion:Ve.string(),settings:_i.optional()}),ox=ar.merge(Ve.object({steps:Ve.array(Yt)})),rs=Ve.object({fileType:Ve.literal(ye.MOBILE_TEST)}).merge(ox),kV=Ve.object({name:Ve.string(),steps:Ve.array(Yt).optional(),settings:_i.optional()}),ix=ar.extend({steps:xi.array()});import Oe from"zod";var mo=Oe.object({startTime:Oe.number(),endTime:Oe.number().optional(),error:Oe.string().optional()});var ax=mo.extend({type:Oe.literal("SECTION"),name:Oe.string(),subSpans:Oe.lazy(()=>px.array())}),sx=mo.extend({type:Oe.literal("AI_LOCATOR_CALL"),result:Oe.object({serializedElement:Oe.string(),id:Oe.number(),thoughts:Oe.string()}).optional()}),lx=mo.extend({type:Oe.literal("AI_ASSERTION_CALL"),result:Oe.object({thoughts:Oe.string(),result:Oe.boolean()}).optional()}),cx=mo.extend({type:Oe.literal("WAIT_FOR_STABILITY"),reason:Oe.string().optional()}),ux=mo.extend({type:Oe.literal("RESOLVE_TARGET_CACHE"),result:Oe.object({serializedElement:Oe.string()}).optional()}),dx=mo.extend({type:Oe.literal("GET_EMULATOR_STATE")}),px=Oe.discriminatedUnion("type",[ax,sx,lx,cx,ux,dx]);import Xt from"zod";var nh=Xt.object({message:Xt.string().optional(),startTime:Xt.number(),endTime:Xt.number(),status:Xt.nativeEnum(Ye),trace:Xt.unknown(),beforeSnapshot:Xt.string().optional(),afterSnapshot:Xt.string().optional(),data:Xt.unknown().optional().describe("output data from the step")}),mx=nh.merge(wi),gx=nh.merge(Ci).extend({steps:Xt.lazy(()=>yn.array())}),yn=Xt.discriminatedUnion("type",[mx,gx]);var cj=new Set(Object.values(rt));var hx={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},uj={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},dj={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},pj={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state",RESOLVED_MOBILE_MODULE:"Module"},mj={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests."};import fx from"semver";import{z as Sx}from"zod";var Sj=Sx.string().refine(r=>fx.valid(r),{message:"must be a valid semver string"});import{Faker as bj,en as Tj}from"@faker-js/faker";import{z as O}from"zod";var Aj=O.object({body:O.string(),to:O.string(),from:O.string()}),Rj=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),wj=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),Cj=O.object({inbox:O.string().transform(r=>r.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),xj=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var ns=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(ns||{}),oh=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),yx=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Ex=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),ih=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),_j=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:yx,response:Ex,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(ns).optional()}),Hr=15e3;import*as lt from"zod";import{extendZodWithOpenApi as bx}from"zod-openapi";bx(lt);var Tx=lt.object({url:lt.string(),lineNumber:lt.number(),columnNumber:lt.number()}).openapi({ref:"CodeLocation"}),os=lt.object({timestamp:lt.number(),text:lt.string(),type:lt.string(),tabIndex:lt.number(),args:lt.unknown().array().optional(),url:lt.string().optional(),location:Tx.optional()}).openapi({ref:"ConsoleLog"}),ah=os.array(),vx=ah.array();import*as su from"zod";import{extendZodWithOpenApi as Hx}from"zod-openapi";import{z as C}from"zod";var Ax=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),Rx=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),wx=C.object({onContentLoad:C.number().optional(),onLoad:C.number().optional(),comment:C.string().optional()}),lh=C.object({startedDateTime:C.string(),id:C.string(),title:C.string().optional(),pageTimings:wx,comment:C.string().optional()}),Cx=C.array(lh),xx=C.object({name:C.string(),value:C.string(),path:C.string().optional(),domain:C.string().optional(),expires:C.string().optional(),httpOnly:C.boolean().optional(),secure:C.boolean().optional(),comment:C.string().optional()}),ch=C.array(xx),_x=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),uh=C.array(_x),Mx=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),Ix=C.array(Mx),Px=C.object({name:C.string(),value:C.string().optional(),fileName:C.string().optional(),contentType:C.string().optional(),comment:C.string().optional()}),Ox=C.array(Px),Lx=C.object({mimeType:C.string(),params:Ox,text:C.string(),comment:C.string().optional()}),Nx=C.object({method:C.string(),url:C.string(),httpVersion:C.string().optional(),cookies:ch,headers:uh,queryString:Ix,postData:Lx.optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional()}),Dx=C.object({size:C.number().optional(),compression:C.number().optional(),mimeType:C.string().optional(),text:C.string().optional(),encoding:C.string().optional(),comment:C.string().optional()}),kx=C.object({status:C.number(),statusText:C.string(),httpVersion:C.string().optional(),cookies:ch,headers:uh,content:Dx,redirectURL:C.string().optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional(),_mocked:C.boolean().optional()}),sh=C.object({expires:C.string().optional(),lastAccess:C.string(),eTag:C.string(),hitCount:C.number(),comment:C.string().optional()}),Ux=C.object({beforeRequest:sh.optional(),afterRequest:sh.optional(),comment:C.string().optional()}),Fx=C.object({blocked:C.number().optional(),dns:C.number().optional(),connect:C.number().optional(),send:C.number(),wait:C.number(),receive:C.number(),ssl:C.number().optional(),comment:C.string().optional()}),dh=C.object({pageref:C.string().optional(),startedDateTime:C.string(),time:C.number().optional(),request:Nx,response:kx.optional(),cache:Ux.optional(),timings:Fx,serverIPAddress:C.string().optional(),connection:C.string().optional(),comment:C.string().optional(),_resourceType:C.string().optional()}),Bx=C.array(dh),zx=C.object({version:C.string().default("1.1"),creator:Ax.optional(),browser:Rx.optional(),pages:Cx.optional(),entries:Bx,comment:C.string().optional()}),Gx=C.object({log:zx}),ph=C.record(C.string(),lh),mh=C.record(C.string(),dh);Hx(su);var Vx=su.object({logsPerPage:os.array().array(),harPages:ph.optional(),harEntries:mh.optional()}).openapi({ref:"DebugData"});var w=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(ge))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},go=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Vr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
3
3
  Decisions:
4
4
  ${this.decisions.map(e=>e.toString()).join(`
5
- `)}`}};function fh(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function cu(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var sr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},as=class extends sr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},ss=class extends sr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function uu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function du(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function pu(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var Ii=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as jx}from"lodash-es";import{z as lr}from"zod";var cs=(m=>(m.DisableClickhouseCaches="disable_clickhouse_caches",m.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",m.IconKnowledgeBase="icon_knowledge_base",m.MiniModelInitialAssertion="mini_model_initial_assertion",m.MiniModelInitialLocator="mini_model_initial_locator",m.ShowTestPlans="show_test_plans",m.AiPageSummary="ai_page_summary",m.ShowZeroOpacityElements="show_zero_opacity_elements",m.VisualActions="visual_actions",m.RagV2="rag_v2",m.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",m.GlobalLocatorRedirect="global_locator_redirect",m.FakerConstantSeed="faker_constant_seed",m.AutoExpandIframes="auto_expand_iframes",m))(cs||{});var Sh=lr.union([lr.string(),lr.number(),lr.boolean(),lr.null(),lr.record(lr.string(),lr.lazy(()=>Sh)),lr.array(lr.lazy(()=>Sh))]),ls=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=jx(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(cs).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},mu=new ls({},{});var gu={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},yh=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],AW=Object.keys(gu);import*as Eh from"zod";var wW=Eh.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as jr}from"zod";var _W=jr.object({id:jr.string(),name:jr.string(),createdAt:jr.coerce.date(),createdBy:jr.string(),updatedAt:jr.coerce.date(),updatedBy:jr.string().nullable(),organizationId:jr.string()});import{z as P}from"zod";import Wr from"zod";var fo=Wr.object({platformSep:Wr.string(),fullPathSegments:Wr.string().array(),relativePathSegments:Wr.string().array(),relativePath:Wr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Wr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Wr.coerce.date(),createdAt:Wr.coerce.date()});var Wx=P.array(fo.extend({id:P.string(),name:P.string(),description:P.string().optional(),labels:P.string().array().optional()})),$x=P.array(fo.extend({id:P.string(),name:P.string(),description:P.string().optional(),content:gi})),GW=P.object({tests:Wx,modules:$x,labels:P.string().array()}),HW=Za.merge(po),VW=P.object({schemaVersion:P.string(),stepLists:oo}),jW=po.partial().merge($t.pick({id:!0})),qx={name:P.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:P.string().optional(),baseUrl:P.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:P.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:P.nativeEnum(Fr).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ha.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:P.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},WW=P.object(qx),$W=Za.merge(P.object({relativeFilePath:P.string().describe("relative to project root")})),qW=P.object({name:P.string()}),KW=P.object({relativeFilePath:P.string()}),YW=P.object({name:P.string()}),XW=P.object({relativeFilePath:P.string()}),JW=P.object({name:P.string(),description:P.string(),enabled:P.boolean(),steps:P.lazy(()=>Ke.array()),testFilePath:P.string().describe("relative to the project root"),folderPath:P.string().optional().describe("user selected folder path")}),QW=P.object({name:P.string(),description:P.string(),enabled:P.boolean()}).partial();var ZW=P.array(lg),e$=P.object({defaultEnv:P.string().optional().describe("name of the default env, or undefined to unset")}),t$=P.object({configFilePath:P.string().describe("full path on disk")}),r$=P.string().array(),n$=P.object({message:P.string(),newRelativeTestPath:P.string().optional()}),hu=P.object({name:P.string(),absolutePath:P.string(),relativePath:P.string(),pathSegments:P.array(P.string()),isDirectory:P.boolean(),size:P.number(),createdAt:P.coerce.date(),modifiedAt:P.coerce.date(),accessedAt:P.coerce.date()}),bh=P.object({pathSegments:P.array(P.string())}),o$=P.object({absolutePath:P.string(),pathSegments:P.array(P.string()),contents:P.array(hu)}),Th=P.object({pathSegments:P.array(P.string())}),vh=P.object({pathSegments:P.array(P.string()),newPathSegments:P.array(P.string())}),Ah=P.object({pathSegments:P.array(P.string()),recursive:P.boolean().optional()}),i$=P.object({success:P.boolean(),message:P.string(),pathSegments:P.array(P.string()).optional()});var us=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],ds=us.map(r=>`**/${r}/**`),Rh=!0,En=!1;import cr from"chalk";import Kx from"safe-stable-stringify";import Yx from"truncate-json";import Xx from"zod";var $r=Kx.configure({deterministic:!1});function wh(r){let e=$r(r),{jsonString:t}=Yx(e,1e4);return t}var Jx=["app","version","env","namespace","host"];function ce(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!Jx.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var ms=Xx.enum(["debug","info","warn","error"]);var Pi={debug:20,info:30,warn:40,error:50},gs={20:"debug",30:"info",40:"warn",50:"error"},fu=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Pi[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=$r(c,void 0,2),s=s.split(`
5
+ `)}`}};function gh(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function lu(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var sr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},is=class extends sr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},as=class extends sr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function cu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function uu(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function du(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var Mi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as jx}from"lodash-es";import{z as lr}from"zod";var fh=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(fh||{});var hh=lr.union([lr.string(),lr.number(),lr.boolean(),lr.null(),lr.record(lr.string(),lr.lazy(()=>hh)),lr.array(lr.lazy(()=>hh))]),ss=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=jx(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(fh).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},EW=new ss({},{});var pu={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Sh=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],TW=Object.keys(pu);import*as yh from"zod";var AW=yh.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as jr}from"zod";var CW=jr.object({id:jr.string(),name:jr.string(),createdAt:jr.coerce.date(),createdBy:jr.string(),updatedAt:jr.coerce.date(),updatedBy:jr.string().nullable(),organizationId:jr.string()});import{z as P}from"zod";import Wr from"zod";var ho=Wr.object({platformSep:Wr.string(),fullPathSegments:Wr.string().array(),relativePathSegments:Wr.string().array(),relativePath:Wr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Wr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Wr.coerce.date(),createdAt:Wr.coerce.date()});var Wx=P.array(ho.extend({id:P.string(),name:P.string(),description:P.string().optional(),labels:P.string().array().optional()})),$x=P.array(ho.extend({id:P.string(),name:P.string(),description:P.string().optional(),content:mi})),BW=P.object({tests:Wx,modules:$x,labels:P.string().array()}),zW=Qa.merge(uo),GW=P.object({schemaVersion:P.string(),stepLists:no}),HW=uo.partial().merge($t.pick({id:!0})),qx={name:P.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:P.string().optional(),baseUrl:P.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:P.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:P.nativeEnum(Fr).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ga.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:P.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},VW=P.object(qx),jW=Qa.merge(P.object({relativeFilePath:P.string().describe("relative to project root")})),WW=P.object({name:P.string()}),$W=P.object({relativeFilePath:P.string()}),qW=P.object({name:P.string()}),KW=P.object({relativeFilePath:P.string()}),YW=P.object({name:P.string(),description:P.string(),enabled:P.boolean(),steps:P.lazy(()=>Ke.array()),testFilePath:P.string().describe("relative to the project root"),folderPath:P.string().optional().describe("user selected folder path")}),XW=P.object({name:P.string(),description:P.string(),enabled:P.boolean()}).partial();var JW=P.array(ag),QW=P.object({defaultEnv:P.string().optional().describe("name of the default env, or undefined to unset")}),ZW=P.object({configFilePath:P.string().describe("full path on disk")}),e$=P.string().array(),t$=P.object({message:P.string(),newRelativeTestPath:P.string().optional()}),mu=P.object({name:P.string(),absolutePath:P.string(),relativePath:P.string(),pathSegments:P.array(P.string()),isDirectory:P.boolean(),size:P.number(),createdAt:P.coerce.date(),modifiedAt:P.coerce.date(),accessedAt:P.coerce.date()}),Eh=P.object({pathSegments:P.array(P.string())}),r$=P.object({absolutePath:P.string(),pathSegments:P.array(P.string()),contents:P.array(mu)}),bh=P.object({pathSegments:P.array(P.string())}),Th=P.object({pathSegments:P.array(P.string()),newPathSegments:P.array(P.string())}),vh=P.object({pathSegments:P.array(P.string()),recursive:P.boolean().optional()}),n$=P.object({success:P.boolean(),message:P.string(),pathSegments:P.array(P.string()).optional()});var ls=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],cs=ls.map(r=>`**/${r}/**`),Ah=!0,En=!1;import cr from"chalk";import Kx from"safe-stable-stringify";import Yx from"truncate-json";import Xx from"zod";var $r=Kx.configure({deterministic:!1});function Rh(r){let e=$r(r),{jsonString:t}=Yx(e,1e4);return t}var Jx=["app","version","env","namespace","host"];function pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!Jx.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var ds=Xx.enum(["debug","info","warn","error"]);var Ii={debug:20,info:30,warn:40,error:50},ps={20:"debug",30:"info",40:"warn",50:"error"},gu=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Ii[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=$r(c,void 0,2),s=s.split(`
6
6
  `).map((u,d)=>d>0?` ${u}`:u).join(`
7
7
  `),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=$r(a,void 0,2),l=l.split(`
8
8
  `).map((c,s)=>s>0?` ${c}`:c).join(`
9
- `)),console.log(" ",t(l))}}getLevel(){return gs[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Pi[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,cr.reset,...e)}info(...e){this.logWithLevel(30,cr.white,...e)}debug(...e){this.logWithLevel(20,cr.dim,...e)}warn(...e){this.logWithLevel(40,cr.yellow,...e)}error(...e){this.logWithLevel(50,cr.red,...e)}success(...e){this.logWithLevel(1/0,cr.green,...e)}dimmed(...e){this.logWithLevel(30,cr.dim,...e)}underline(...e){this.logWithLevel(40,cr.underline,...e)}bold(...e){this.logWithLevel(40,cr.bold,...e)}grey(...e){this.logWithLevel(20,cr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Su=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},m$=new Su,Qx=typeof window>"u"&&typeof process<"u"&&ms.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?ms.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,A=new fu(Qx,{}),bn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>bn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},ps={},hs=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=ps[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},ps[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=ps[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete ps[e]},n)};import{z as ue}from"zod";var Zx=ue.array(fo.extend({id:ue.string(),name:ue.string(),description:ue.string().optional(),labels:ue.string().array().optional()})),e_=ue.array(fo.extend({id:ue.string(),name:ue.string(),description:ue.string().optional(),content:gi})),Ch=ue.object({name:ue.string(),description:ue.string().optional(),settings:Mi.optional(),pathSegments:ue.string().array()}),E$=ue.object({id:ue.string(),fileName:ue.string(),fullPath:ue.string(),relativeFilePath:ue.string().describe("relative to project root")});var xh=ue.object({steps:_i.array().optional(),settings:Mi.optional()}),b$=ue.object({message:ue.literal("ok")}),_h=ue.object({tag:ue.string(),channel:ue.string(),filePath:ue.string()}),T$=ue.object({tests:Zx,modules:e_,labels:ue.string().array()}),Mh=ue.object({name:ue.string(),description:ue.string(),enabled:ue.boolean()}).partial();import{z as Fe}from"zod";var Ih=Fe.object({id:Fe.string(),createdAt:Fe.coerce.date(),createdBy:Fe.string(),organizationId:Fe.string(),name:Fe.string(),description:Fe.string().nullish(),enabled:Fe.boolean(),schemaVersion:Fe.string().describe("Schema version for steps"),parameters:Fe.string().array().nullish().describe("Parameter list"),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).nullish(),defaultParameters:Fe.record(Fe.string(),Fe.string()).nullish(),defaultCacheKey:Fe.string().nullish(),defaultCacheTtl:Fe.number().nullish(),defaultCacheAllInvocations:Fe.boolean().nullish(),autoAuth:Fe.boolean().nullish(),advanced:Mc.nullish()}),I$=Ih.extend({steps:Fe.lazy(()=>ht.array())}),P$=5*60*1e3,t_=Nt.merge(Ih.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as N$}from"date-fns-tz";import{z as Ee}from"zod";var yu=Vc.extend({aiAction:Ee.boolean().optional(),stepLintSuggestions:Ee.boolean().optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional(),aiFailureAnalysis:Ee.boolean().optional(),aiPageFiltering:Ee.boolean().optional().describe("rag v2 feature flag")}),Eu=Ee.object({fakerConstantSeed:Ee.boolean().optional()}),z$=Ee.object({ai:yu.optional(),githubAppInstallationId:Ee.number().nullish(),githubAppSummaryMessageEnabled:Ee.boolean().nullish(),githubReleaseAppInstallationId:Ee.number().nullish(),gitlabAppAccessToken:Ee.string().nullish(),gitlabAppBaseUrl:Ee.string().nullish(),qaseAccessToken:Ee.string().nullish(),testSuggestionsEnabled:Ee.boolean().nullish(),browser:Dc.optional(),advanced:Eu.optional()}),G$=Ee.object({globalOverrides:Ee.record(Ee.string()).optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional()}),H$=Ee.record(Ee.string(),Ee.string()).nullish();import*as S from"zod";import{z as Ne}from"zod";var bu=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(bu||{});var r_=Ne.object({type:Ne.literal("DESCRIPTION_UPDATE"),thoughts:Ne.string()}),fs=Ne.discriminatedUnion("type",[r_]),n_=Ne.object({testId:Ne.string(),name:Ne.string(),orgId:Ne.string(),runId:Ne.string(),steps:Ke.array(),purpose:Ne.nativeEnum(bu),details:fs.or(fs.array()).optional()});var $$=n_.pick({name:!0,orgId:!0}),o_=Ne.object({id:Ne.string(),name:Ne.string().nullish(),createdAt:Ne.string().pipe(Ne.coerce.date()).or(Ne.date()),organizationId:Ne.string(),schemaVersion:Ne.string(),runId:Ne.string().nullish(),purpose:Ne.nativeEnum(bu),details:fs.or(fs.array()).optional(),applied:Ne.boolean().nullish(),appliedAt:Ne.coerce.date().nullish()}),Ph=o_.extend({steps:Ke.array()});var Oh="x-momentic-cli-version",Lh="x-momentic-cli-type",i_="x-momentic-main-branch-name",a_="x-momentic-branch-name",s_="x-momentic-commit-timestamp",l_="x-momentic-last-commit-on-main",c_="x-momentic-last-commit-on-main-timestamp",u_="x-momentic-merged-branch-name";var cq=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),uq=st.merge($c),Nh=ka,dq=st.merge($c);var pq=st.merge(xg).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Tu=_m,mq=st.merge(Mg),Dh=Xm,gq=st.merge(_g),kh=Ym,hq=st.merge(Rg),Uh=qm,fq=st.merge(wg),Fh=Wm,Sq=st.merge(Cg);var yq=st.merge(Lg),Eq=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),Bh=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var bq=S.string().array(),Tq=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),zh=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),d_=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),vq=d_.array(),Aq=S.object({testId:S.string(),schemaVersion:S.string()}).merge(cn);function vu(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[i_]=encodeURIComponent(e)),t&&(a[a_]=encodeURIComponent(t)),n&&(a[s_]=n.toISOString()),o&&(a[l_]=encodeURIComponent(o)),i&&(a[c_]=i.toISOString()),r.mergedGitBranchName&&(a[u_]=encodeURIComponent(r.mergedGitBranchName)),a}var Rq=S.object({entries:S.array(Bm),testId:S.string()}),wq=S.object({entries:S.array(Zg),testId:S.string()}),Cq=S.object({testId:S.string()});function Gh(r){return S.record(S.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var Hh=Gh(zm),Vh=Gh(eh),jh=S.object({trigger:S.nativeEnum(Ut),status:S.nativeEnum(me),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),xq=S.object({id:S.string()}),Wh=S.object({status:S.nativeEnum(me),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),$h=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(Ut),schemaVersion:S.string().optional(),section:S.nativeEnum(Wa).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),_q=S.object({id:S.string()}),p_=jc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),qh=p_.array(),Kh=jc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Mq=S.object({id:S.string()}),Yh=S.object({status:S.nativeEnum(me),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),Iq=S.object({screenshot:S.string()}),Xh=S.object({key:S.string()}),Jh=S.object({orgId:S.string(),userId:S.string()}),Qh=S.array(sg),Pq=S.record(S.string(),S.union([S.string(),S.boolean()])),Oq=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Zh=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),Lq=S.object({suiteRunIds:S.string().array()}),Nq=bg.array(),Dq=S.object({runGroupIds:S.string().array()}),m_=S.object({uploadUrl:S.string()}),kq=st.merge(Ig),Uq=st.merge(Og),Fq=st.merge(Pg),g_=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),h_=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(vi),properties:g_}),Bq=h_.array(),ef=Ph.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),zq=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),tf=Sg.array(),Gq=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),rf=m_.extend({id:S.string()}),Hq=S.object({runGroupId:S.string().uuid().optional()}),nf=S.object({runGroupId:S.string().uuid()}),of=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),Vq=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),jq=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Wq=st.merge(Ug),$q=st.merge(Fg),qq=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(Ri).optional()}),af=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),Kq=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),sf=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),lf=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as W}from"zod";var f_=3,Jq=W.object({localTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()}).or(W.object({cloudTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()})),cf=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(cf||{});var Au=W.object({name:W.string(),description:W.string().nullish(),effect:W.nativeEnum(cf),labels:W.array(W.string()),githubRepository:W.string().nullish(),gitlabProjectPath:W.string().nullish(),gitBranchName:W.string().nullish()}),S_=W.object({type:W.literal("LAST_N_RUNS"),lastN:W.number().min(f_).max(10)}),y_=W.object({type:W.literal("LAST_N_HOURS"),lastN:W.number().min(1).max(24)}),E_=W.object({type:W.literal("LAST_N_DAYS"),lastN:W.number().min(1).max(7)}),Ru=W.discriminatedUnion("type",[S_,y_,E_]),b_=W.object({flakeRateThreshold:W.number().min(1).max(100),evaluationWindow:Ru}),T_=Au.extend({type:W.literal("FLAKE_RATE"),config:b_}),v_=W.object({passRateThreshold:W.number().min(1).max(100),evaluationWindow:Ru}),A_=Au.extend({type:W.literal("PASS_RATE"),config:v_}),R_=W.object({failureCountThreshold:W.number().min(0),evaluationWindow:Ru}),w_=Au.extend({type:W.literal("FAILURE_COUNT"),config:R_}),Qq=W.discriminatedUnion("type",[T_,A_,w_]);import{z as Be}from"zod";var tK=Be.object({repositoriesIndexed:Be.boolean(),indexingInProgress:Be.boolean(),indexesOutdated:Be.boolean()}),uf=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(uf||{}),df=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(df||{}),rK=Be.object({name:Be.string(),status:Be.nativeEnum(uf),conclusion:Be.nativeEnum(df).nullable()}),Oi=Be.object({sha:Be.string(),message:Be.string(),author:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()}),committer:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()})}),wu=Be.object({mergedBranch:Be.string().optional()});import{z as _e}from"zod";var pf=_e.object({orgId:_e.string(),cacheKeys:_e.string().array()}),iK=_e.object({keyParams:pf,clientMetadata:_e.string(),lockAcquisitionTimeoutMs:_e.number().optional()}),mf=_e.object({acquired:_e.boolean(),acquiredByMetadata:_e.string(),keyPrefix:_e.string()}),aK=_e.object({keyPrefix:_e.string(),result:_e.string(),ttlMs:_e.number()}),sK=_e.union([_e.object({keyPrefix:_e.string()}),pf]),C_=_e.object({remainingTtlMs:_e.number(),value:_e.string().nullish()}),lK=_e.object({results:_e.record(_e.string(),C_),activeLocks:_e.string().array()});var cK=5*60*1e3;var mK=90*24*60*60*1e3,gK=7*24*60*60*1e3;import{z as gf}from"zod";var SK=gf.object({quarantineNotifications:gf.string().nullish()});import{z as nt}from"zod";var x_=nt.object({version:nt.string(),json:nt.record(nt.unknown()),hash:nt.string()}),hf=nt.record(nt.unknown()),TK=nt.object({newSvgs:nt.array(x_),metadata:hf.optional()}),__=nt.object({version:nt.string(),json:nt.record(nt.unknown()).nullish(),hash:nt.string(),description:nt.string().nullish(),metadata:hf.nullish()}),ff=nt.record(nt.string().describe("icon hash"),__);import{z as Le}from"zod";var Cu=Le.object({assertion:Le.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),M_=Le.object({instruction:Le.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:Cu.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),Sf=M_.extend({subSteps:Le.lazy(()=>Sf.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),yf=Le.object({name:Le.string().describe("Short name describing the test plan"),description:Le.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Ef=yf.extend({id:Le.string(),createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string(),createdBy:Le.string(),test:Le.object({id:Le.string(),name:Le.string()}).nullish().transform(r=>r??void 0)}),wK=Ef.extend({testGenRuns:Le.tuple([]).or(Le.tuple([Le.object({id:Le.string(),startedAt:Le.coerce.date(),status:Le.nativeEnum(me)})]))}),bf=Le.object({preConditions:Cu.array().nullish().transform(r=>r??[]),postConditions:Cu.array().nullish().transform(r=>r??[]),steps:Sf.array().nullish().transform(r=>r??[])}),CK=Ef.extend({plan:bf.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),I_=yf.extend({plan:bf.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),xK=I_.array().nullish().transform(r=>r??[]);import{validator as P_}from"@exodus/schemasafe";function Tf(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{P_(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var vf=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Ss=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as jK}from"zod";var ys=class{async resolveEntries(){}async saveEntries(){}};var So=class r{spans;parentSection;name;finished=!1;startTime;endTime;constructor(e,t){this.startTime=t?.startTime??Date.now(),this.spans=t?.subSpans??[],this.parentSection=t,this.name=e}startSection(e){let t={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[]};return new r(e,t)}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime);this.parentSection&&(this.parentSection.endTime=this.endTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}async startAsyncSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=await t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:this.name,startTime:this.startTime,endTime:this.endTime,subSpans:this.spans}}};import{z as j}from"zod";var O_=j.object({step:Ke,status:j.nativeEnum(Ye),startedAt:j.coerce.date(),finishedAt:j.coerce.date().optional(),healMetadata:j.object({healType:j.nativeEnum(fi).or(j.literal("AI")),healedAt:j.coerce.date()}).optional(),beforeSnapshotId:j.string().uuid().optional(),afterSnapshotId:j.string().uuid().optional(),message:j.string().optional()}),s2=O_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),Af="1.0.0",_u=Yh.extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),runAttemptSchemaVersion:j.string().optional(),schemaVersion:j.string().optional().default("1.0.19"),results:j.record(j.string(),j.unknown()).array().optional(),beforeResults:j.record(j.string(),j.unknown()).array().optional(),afterResults:j.record(j.string(),j.unknown()).array().optional()}),Rf=_u.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),l2=_u.merge(Si),c2=Rf.merge(Si),wf=j.object({results:j.array(yn),beforeResults:j.array(yn).optional(),afterResults:j.array(yn).optional()}),u2=_u.merge(wf),d2=Rf.merge(wf),L_=Kh.merge($h).extend({executionType:j.nativeEnum(so).optional().default("WEB"),testId:j.string().uuid(),testDescription:j.string().optional(),runGroupId:j.string().uuid(),status:j.nativeEnum(me),startedAt:j.coerce.date(),attempts:j.number(),failureRecoveryDetails:j.record(j.unknown()).optional()}),p2=L_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),N_=jh.merge(Wh).extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),cliVersion:j.string(),labels:j.string().array().optional().default([])}),Li=N_.extend({updatedAt:j.coerce.date().optional().transform(r=>r??new Date),finishedAt:j.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as B_}from"url";var _f,z_=B_(import.meta.url),G_=k_(z_);_f=F_(G_,"..");var Ni=_f;A.info(`Setting APPIUM_HOME to ${Ni}`);process.env.APPIUM_HOME=Ni;var H_="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",V_="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",j_="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Mf="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",If="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function W_(){if(!process.env.JAVA_HOME)A.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&A.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>U_(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");D_(e)||A.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{Cf("java --version",{stdio:"pipe",encoding:"utf-8"})||(A.error(`Could not find a Java installation. ${H_}`),process.exit(1))}catch(r){A.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function $_(){process.env.ANDROID_HOME||(A.error(`The ANDROID_HOME environment variable is not set. ${j_} ${xf()==="darwin"?Mf:If}`),process.exit(1))}function q_(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{Cf(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(A.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${V_} Finally, ensure that the 'adb' command is available in your shell. ${xf()==="darwin"?Mf:If}`),process.exit(1))}catch(e){A.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function Pf(){W_(),$_(),q_()}import{Server as JD}from"socket.io";import{randomUUID as oM}from"crypto";import{faker as K_}from"@faker-js/faker";import Y_ from"assert";import X_ from"axios";import*as J_ from"child_process";import Q_ from"moment";import*as Z_ from"otpauth";import eM from"pg";var qr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Of=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 B(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(Of(d));l=()=>s(Of(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new qr(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}async function Lf(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Ja(n,e);t.push(...o)}),t}function tM(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function rM(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var nM=Object.getPrototypeOf(async function(){}).constructor;async function Nf(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(v,w)=>{o[v]=w,s[v]=w},d={},p=(v,w)=>{o[v]=w,d[v]=w},g;n.includes("Octokit")&&(g=(await import("@octokit/rest")).Octokit);let m;n.includes("createAppAuth")&&(m=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new nM("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(X_,Q_,c.fakerInstance??K_,Y_,eM,g,m,Z_,J_,Lf,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,w=>c.sms.send(w),w=>c.sms.fetchLatest(w),c.email,c.sms,c.ai,tM(a,l),...Object.values(i??{}))),f=!0,E,b;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await rM(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof qr?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=v instanceof Error?v.message:`${v}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:b}}async function Df({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Hr,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oM(),p=await Nf(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return A.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iM,randomUUID as aM}from"crypto";import sM from"fetch-retry";var lM=sM(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),kf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Uf=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Ff({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Hr,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!kf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,g,m=0;if(!Uf)throw new Error("Missing lambda auth secret.");let h=iM("sha256",Uf).update(r).digest("hex");for(;m<=i;){m++,a?.throwIfAborted();let E={id:aM(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await B(lM(kf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);g=void 0;break}catch(b){g=b}}if(g)throw l.error({err:g},"Failed to evaluate code remotely"),g;if(!p)throw new Error(`An unexpected code evaluation error occurred${g?`: ${g}`:""}`);let f;try{f=sh.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function ur(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Ff(r);else if(r.localTools)e=await Df({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
9
+ `)),console.log(" ",t(l))}}getLevel(){return ps[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Ii[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,cr.reset,...e)}info(...e){this.logWithLevel(30,cr.white,...e)}debug(...e){this.logWithLevel(20,cr.dim,...e)}warn(...e){this.logWithLevel(40,cr.yellow,...e)}error(...e){this.logWithLevel(50,cr.red,...e)}success(...e){this.logWithLevel(1/0,cr.green,...e)}dimmed(...e){this.logWithLevel(30,cr.dim,...e)}underline(...e){this.logWithLevel(40,cr.underline,...e)}bold(...e){this.logWithLevel(40,cr.bold,...e)}grey(...e){this.logWithLevel(20,cr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},hu=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},d$=new hu,Qx=typeof window>"u"&&typeof process<"u"&&ds.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?ds.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,R=new gu(Qx,{}),bn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>bn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},us={},ms=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=us[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},us[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=us[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete us[e]},n)};import{z as ce}from"zod";var Zx=ce.array(ho.extend({id:ce.string(),name:ce.string(),description:ce.string().optional(),labels:ce.string().array().optional()})),e_=ce.array(ho.extend({id:ce.string(),name:ce.string(),description:ce.string().optional(),content:mi})),wh=ce.object({name:ce.string(),description:ce.string().optional(),settings:_i.optional(),pathSegments:ce.string().array()}),S$=ce.object({id:ce.string(),fileName:ce.string(),fullPath:ce.string(),relativeFilePath:ce.string().describe("relative to project root")});var Ch=ce.object({steps:xi.array().optional(),settings:_i.optional()}),y$=ce.object({message:ce.literal("ok")}),xh=ce.object({tag:ce.string(),channel:ce.string(),filePath:ce.string()}),E$=ce.object({tests:Zx,modules:e_,labels:ce.string().array()}),_h=ce.object({name:ce.string(),description:ce.string(),enabled:ce.boolean()}).partial();import{z as Fe}from"zod";var Mh=Fe.object({id:Fe.string(),createdAt:Fe.coerce.date(),createdBy:Fe.string(),organizationId:Fe.string(),name:Fe.string(),description:Fe.string().nullish(),enabled:Fe.boolean(),schemaVersion:Fe.string().describe("Schema version for steps"),parameters:Fe.string().array().nullish().describe("Parameter list"),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).nullish(),defaultParameters:Fe.record(Fe.string(),Fe.string()).nullish(),defaultCacheKey:Fe.string().nullish(),defaultCacheTtl:Fe.number().nullish(),defaultCacheAllInvocations:Fe.boolean().nullish(),autoAuth:Fe.boolean().nullish(),advanced:_c.nullish()}),_$=Mh.extend({steps:Fe.lazy(()=>ht.array())}),M$=5*60*1e3,t_=Nt.merge(Mh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as O$}from"date-fns-tz";import{z as Ee}from"zod";var fu=Hc.extend({aiAction:Ee.boolean().optional(),stepLintSuggestions:Ee.boolean().optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional(),aiFailureAnalysis:Ee.boolean().optional(),aiPageFiltering:Ee.boolean().optional().describe("rag v2 feature flag")}),Su=Ee.object({fakerConstantSeed:Ee.boolean().optional()}),F$=Ee.object({ai:fu.optional(),githubAppInstallationId:Ee.number().nullish(),githubAppSummaryMessageEnabled:Ee.boolean().nullish(),githubReleaseAppInstallationId:Ee.number().nullish(),gitlabAppAccessToken:Ee.string().nullish(),gitlabAppBaseUrl:Ee.string().nullish(),qaseAccessToken:Ee.string().nullish(),testSuggestionsEnabled:Ee.boolean().nullish(),browser:Nc.optional(),advanced:Su.optional()}),B$=Ee.object({globalOverrides:Ee.record(Ee.string()).optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional()}),z$=Ee.record(Ee.string(),Ee.string()).nullish();import*as S from"zod";import{z as Ne}from"zod";var yu=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(yu||{});var r_=Ne.object({type:Ne.literal("DESCRIPTION_UPDATE"),thoughts:Ne.string()}),gs=Ne.discriminatedUnion("type",[r_]),n_=Ne.object({testId:Ne.string(),name:Ne.string(),orgId:Ne.string(),runId:Ne.string(),steps:Ke.array(),purpose:Ne.nativeEnum(yu),details:gs.or(gs.array()).optional()});var j$=n_.pick({name:!0,orgId:!0}),o_=Ne.object({id:Ne.string(),name:Ne.string().nullish(),createdAt:Ne.string().pipe(Ne.coerce.date()).or(Ne.date()),organizationId:Ne.string(),schemaVersion:Ne.string(),runId:Ne.string().nullish(),purpose:Ne.nativeEnum(yu),details:gs.or(gs.array()).optional(),applied:Ne.boolean().nullish(),appliedAt:Ne.coerce.date().nullish()}),Ih=o_.extend({steps:Ke.array()});var Ph="x-momentic-cli-version",Oh="x-momentic-cli-type",i_="x-momentic-main-branch-name",a_="x-momentic-branch-name",s_="x-momentic-commit-timestamp",l_="x-momentic-last-commit-on-main",c_="x-momentic-last-commit-on-main-timestamp",u_="x-momentic-merged-branch-name";var sq=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),lq=st.merge(Wc),Lh=Da,cq=st.merge(Wc);var uq=st.merge(wg).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Eu=Cm,dq=st.merge(xg),Nh=Km,pq=st.merge(Cg),Dh=qm,mq=st.merge(vg),kh=Wm,gq=st.merge(Ag),Uh=Vm,hq=st.merge(Rg);var fq=st.merge(Pg),Sq=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),Fh=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var yq=S.string().array(),Eq=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),Bh=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),d_=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),bq=d_.array(),Tq=S.object({testId:S.string(),schemaVersion:S.string()}).merge(cn);function bu(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[i_]=encodeURIComponent(e)),t&&(a[a_]=encodeURIComponent(t)),n&&(a[s_]=n.toISOString()),o&&(a[l_]=encodeURIComponent(o)),i&&(a[c_]=i.toISOString()),r.mergedGitBranchName&&(a[u_]=encodeURIComponent(r.mergedGitBranchName)),a}var vq=S.object({entries:S.array(Um),testId:S.string()}),Aq=S.object({entries:S.array(Jg),testId:S.string()}),Rq=S.object({testId:S.string()});function zh(r){return S.record(S.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var Gh=zh(Fm),Hh=zh(Qg),Vh=S.object({trigger:S.nativeEnum(Ut),status:S.nativeEnum(me),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),wq=S.object({id:S.string()}),jh=S.object({status:S.nativeEnum(me),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),Wh=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(Ut),schemaVersion:S.string().optional(),section:S.nativeEnum(ja).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),Cq=S.object({id:S.string()}),p_=Vc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),$h=p_.array(),qh=Vc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),xq=S.object({id:S.string()}),Kh=S.object({status:S.nativeEnum(me),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),_q=S.object({screenshot:S.string()}),Yh=S.object({key:S.string()}),Xh=S.object({orgId:S.string(),userId:S.string()}),Jh=S.array(ig),Mq=S.record(S.string(),S.union([S.string(),S.boolean()])),Iq=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Qh=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),Pq=S.object({suiteRunIds:S.string().array()}),Oq=yg.array(),Lq=S.object({runGroupIds:S.string().array()}),m_=S.object({uploadUrl:S.string()}),Nq=st.merge(_g),Dq=st.merge(Ig),kq=st.merge(Mg),g_=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),h_=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(Ti),properties:g_}),Uq=h_.array(),Zh=Ih.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),Fq=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),ef=hg.array(),Bq=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),tf=m_.extend({id:S.string()}),zq=S.object({runGroupId:S.string().uuid().optional()}),rf=S.object({runGroupId:S.string().uuid()}),nf=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),Gq=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Hq=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Vq=st.merge(Dg),jq=st.merge(kg),Wq=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(Ai).optional()}),of=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),$q=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),af=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),sf=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as W}from"zod";var f_=3,Yq=W.object({localTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()}).or(W.object({cloudTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()})),lf=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(lf||{});var Tu=W.object({name:W.string(),description:W.string().nullish(),effect:W.nativeEnum(lf),labels:W.array(W.string()),githubRepository:W.string().nullish(),gitlabProjectPath:W.string().nullish(),gitBranchName:W.string().nullish()}),S_=W.object({type:W.literal("LAST_N_RUNS"),lastN:W.number().min(f_).max(10)}),y_=W.object({type:W.literal("LAST_N_HOURS"),lastN:W.number().min(1).max(24)}),E_=W.object({type:W.literal("LAST_N_DAYS"),lastN:W.number().min(1).max(7)}),vu=W.discriminatedUnion("type",[S_,y_,E_]),b_=W.object({flakeRateThreshold:W.number().min(1).max(100),evaluationWindow:vu}),T_=Tu.extend({type:W.literal("FLAKE_RATE"),config:b_}),v_=W.object({passRateThreshold:W.number().min(1).max(100),evaluationWindow:vu}),A_=Tu.extend({type:W.literal("PASS_RATE"),config:v_}),R_=W.object({failureCountThreshold:W.number().min(0),evaluationWindow:vu}),w_=Tu.extend({type:W.literal("FAILURE_COUNT"),config:R_}),Xq=W.discriminatedUnion("type",[T_,A_,w_]);import{z as Be}from"zod";var Zq=Be.object({repositoriesIndexed:Be.boolean(),indexingInProgress:Be.boolean(),indexesOutdated:Be.boolean()}),cf=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(cf||{}),uf=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(uf||{}),e2=Be.object({name:Be.string(),status:Be.nativeEnum(cf),conclusion:Be.nativeEnum(uf).nullable()}),Pi=Be.object({sha:Be.string(),message:Be.string(),author:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()}),committer:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()})}),Au=Be.object({mergedBranch:Be.string().optional()});import{z as _e}from"zod";var df=_e.object({orgId:_e.string(),cacheKeys:_e.string().array()}),n2=_e.object({keyParams:df,clientMetadata:_e.string(),lockAcquisitionTimeoutMs:_e.number().optional()}),pf=_e.object({acquired:_e.boolean(),acquiredByMetadata:_e.string(),keyPrefix:_e.string()}),o2=_e.object({keyPrefix:_e.string(),result:_e.string(),ttlMs:_e.number()}),i2=_e.union([_e.object({keyPrefix:_e.string()}),df]),C_=_e.object({remainingTtlMs:_e.number(),value:_e.string().nullish()}),a2=_e.object({results:_e.record(_e.string(),C_),activeLocks:_e.string().array()});var s2=5*60*1e3;var d2=90*24*60*60*1e3,p2=7*24*60*60*1e3;import{z as mf}from"zod";var h2=mf.object({quarantineNotifications:mf.string().nullish()});import{z as nt}from"zod";var x_=nt.object({version:nt.string(),json:nt.record(nt.unknown()),hash:nt.string()}),gf=nt.record(nt.unknown()),E2=nt.object({newSvgs:nt.array(x_),metadata:gf.optional()}),__=nt.object({version:nt.string(),json:nt.record(nt.unknown()).nullish(),hash:nt.string(),description:nt.string().nullish(),metadata:gf.nullish()}),hf=nt.record(nt.string().describe("icon hash"),__);import{z as Le}from"zod";var Ru=Le.object({assertion:Le.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),M_=Le.object({instruction:Le.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:Ru.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),ff=M_.extend({subSteps:Le.lazy(()=>ff.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Sf=Le.object({name:Le.string().describe("Short name describing the test plan"),description:Le.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),yf=Sf.extend({id:Le.string(),createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string(),createdBy:Le.string(),test:Le.object({id:Le.string(),name:Le.string()}).nullish().transform(r=>r??void 0)}),A2=yf.extend({testGenRuns:Le.tuple([]).or(Le.tuple([Le.object({id:Le.string(),startedAt:Le.coerce.date(),status:Le.nativeEnum(me)})]))}),Ef=Le.object({preConditions:Ru.array().nullish().transform(r=>r??[]),postConditions:Ru.array().nullish().transform(r=>r??[]),steps:ff.array().nullish().transform(r=>r??[])}),R2=yf.extend({plan:Ef.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),I_=Sf.extend({plan:Ef.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),w2=I_.array().nullish().transform(r=>r??[]);import{validator as P_}from"@exodus/schemasafe";function bf(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{P_(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Tf=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var hs=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as H2}from"zod";var fs=class{async resolveEntries(){}async saveEntries(){}};var fo=class r{spans;parentSection;name;finished=!1;startTime;endTime;constructor(e,t){this.startTime=t?.startTime??Date.now(),this.spans=t?.subSpans??[],this.parentSection=t,this.name=e}startSection(e){let t={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[]};return new r(e,t)}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime);this.parentSection&&(this.parentSection.endTime=this.endTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}async startAsyncSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=await t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:this.name,startTime:this.startTime,endTime:this.endTime,subSpans:this.spans}}};import{z as j}from"zod";var O_=j.object({step:Ke,status:j.nativeEnum(Ye),startedAt:j.coerce.date(),finishedAt:j.coerce.date().optional(),healMetadata:j.object({healType:j.nativeEnum(hi).or(j.literal("AI")),healedAt:j.coerce.date()}).optional(),beforeSnapshotId:j.string().uuid().optional(),afterSnapshotId:j.string().uuid().optional(),message:j.string().optional()}),iK=O_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),vf="1.0.0",Cu=Kh.extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),runAttemptSchemaVersion:j.string().optional(),schemaVersion:j.string().optional().default("1.0.19"),results:j.record(j.string(),j.unknown()).array().optional(),beforeResults:j.record(j.string(),j.unknown()).array().optional(),afterResults:j.record(j.string(),j.unknown()).array().optional()}),Af=Cu.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),aK=Cu.merge(fi),sK=Af.merge(fi),Rf=j.object({results:j.array(yn),beforeResults:j.array(yn).optional(),afterResults:j.array(yn).optional()}),lK=Cu.merge(Rf),cK=Af.merge(Rf),L_=qh.merge(Wh).extend({executionType:j.nativeEnum(ao).optional().default("WEB"),testId:j.string().uuid(),testDescription:j.string().optional(),runGroupId:j.string().uuid(),status:j.nativeEnum(me),startedAt:j.coerce.date(),attempts:j.number(),failureRecoveryDetails:j.record(j.unknown()).optional()}),uK=L_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),N_=Vh.merge(jh).extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),cliVersion:j.string(),labels:j.string().array().optional().default([])}),Oi=N_.extend({updatedAt:j.coerce.date().optional().transform(r=>r??new Date),finishedAt:j.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as B_}from"url";var xf,z_=B_(import.meta.url),G_=k_(z_);xf=F_(G_,"..");var Li=xf;R.info(`Setting APPIUM_HOME to ${Li}`);process.env.APPIUM_HOME=Li;var H_="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",V_="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",j_="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",_f="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",Mf="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function W_(){if(!process.env.JAVA_HOME)R.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&R.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>U_(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");D_(e)||R.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{wf("java --version",{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find a Java installation. ${H_}`),process.exit(1))}catch(r){R.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function $_(){process.env.ANDROID_HOME||(R.error(`The ANDROID_HOME environment variable is not set. ${j_} ${Cf()==="darwin"?_f:Mf}`),process.exit(1))}function q_(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{wf(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${V_} Finally, ensure that the 'adb' command is available in your shell. ${Cf()==="darwin"?_f:Mf}`),process.exit(1))}catch(e){R.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function If(){W_(),$_(),q_()}import{Server as KD}from"socket.io";import{randomUUID as oM}from"crypto";import{faker as K_}from"@faker-js/faker";import Y_ from"assert";import X_ from"axios";import*as J_ from"child_process";import Q_ from"moment";import*as Z_ from"otpauth";import eM from"pg";var qr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Pf=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 B(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(Pf(d));l=()=>s(Pf(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new qr(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}async function Of(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Xa(n,e);t.push(...o)}),t}function tM(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function rM(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var nM=Object.getPrototypeOf(async function(){}).constructor;async function Lf(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(v,A)=>{o[v]=A,s[v]=A},d={},p=(v,A)=>{o[v]=A,d[v]=A},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new nM("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(X_,Q_,c.fakerInstance??K_,Y_,eM,m,g,Z_,J_,Of,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,tM(a,l),...Object.values(i??{}))),f=!0,E,b;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await rM(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof qr?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=v instanceof Error?v.message:`${v}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:b}}async function Nf({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Hr,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oM(),p=await Lf(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return R.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iM,randomUUID as aM}from"crypto";import sM from"fetch-retry";var lM=sM(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),Df=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,kf=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Uf({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Hr,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!Df)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!kf)throw new Error("Missing lambda auth secret.");let h=iM("sha256",kf).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:aM(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await B(lM(Df,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(b){m=b}}if(m)throw l.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=ih.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function ur(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Uf(r);else if(r.localTools)e=await Nf({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
10
10
  ${e.error}
11
11
  Code received:
12
- ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as cM}from"lodash-es";async function Mu(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Hr,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let g=p[1].trim(),m;try{m=await ur({orgId:e,code:g,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(m===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${g}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof m=="string"?m:`${m}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Es(r){return Bf(r)}async function Bf({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await Mu({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await Bf({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function bs(r,e){for(let{path:t,original:n}of e)cM(r,t,n)}import uM from"fetch-retry";var JX=process.env.MAILINATOR_API_KEY,QX=uM(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{randomUUID as wD}from"crypto";import CD from"path";function Iu({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,g)=>{try{let m=Gr.parse(g.value);if(m.type!==p.type){o.warn({parsedCacheEntry:m,command:p},"Not using step cache due to type mismatch"),l.push(g.key);return}p.cache=m.cache,a.push(g.key),c.push(g.uniqueKey)}catch(m){l.push(g.key),o.error({err:m,cacheEntry:g},"Not using step cache due to parsing error")}},d=(p,g)=>{let m=mM(p.id,g),h=m.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_CHECK")return;l.push(m[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!Qa(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:g,cacheKeysMissed:m,uniqueKeysHit:h}=Iu({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...g),l.push(...m),c.push(...h);break}default:{let g=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function pM(r,e){return e?`${e}:${r}`:r}function mM(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function Pu(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
13
- ${JSON.stringify(t)}`);let n=[];return n.push({key:pM(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Tn({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&Fm(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function Ts(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}function St(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var An={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Rn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},zf={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Gf={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var K5={CONTENT:"The page"};function Hf(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function gM(r){return typeof r=="object"&&r!==null}function vn(r){if(Array.isArray(r))return r.map(vn);if(gM(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=vn(n))}),e}return r}function hM(r){switch(r.type){case"OPEN_APP":return`Open app: ${r.packageName}`;case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${iu(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${iu(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function Vf(r){switch(r.type){case"MOBILE_PRESET_STEP":return hM(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as jf}from"lodash-es";async function Wf(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await vs({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:l}=await vs({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=l}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function vs({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await $f({rawStep:Yt.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function $f({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...jf(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let l;try{l=Yt.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(l.map(u=>$f({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=jf(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as fM}from"lodash-es";import{v4 as Ou}from"uuid";async function wn(r){let e=new Map,t=new Set,n=fM(r.steps),o=await qf({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function qf({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Ou():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Ou():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Pu({id:d.id,orgId:n.orgId,testId:n.testId,value:Gr.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Ou():u.id,p=u.moduleId;a.has(p)?p=a.get(p):l!==void 0&&(p=await l(u),a.set(u.moduleId,p));let{cachesToSave:g,stepsToSave:m,moduleUpdates:h}=await qf({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(h),s.cachesToSave=s.cachesToSave.concat(g),t.has(p)||(t.add(p),s.moduleUpdates.push({...mo.parse(u),steps:Yt.array().parse(m),moduleId:p}));let f=xi.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}default:{let d=u}}return s}function SM(r){let e={parentChain:[]};return Kf(r,e),e}function Kf(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),Kf({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function yM(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return SM({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Yf({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!yM([r],t,i).result}function Xf(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let l=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let l=i}}return{firstMetadata:e,lastMetadata:o}}function Jf({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as j3}from"lodash-es";import $3 from"truncate-json";import{v4 as t4}from"uuid";import{cloneDeep as N3,unset as D3}from"lodash-es";import{cloneDeep as a4}from"lodash-es";import{cloneDeep as MJ}from"lodash-es";import X4 from"diff-lines";import Lu,{gte as Q4}from"semver";var Qf={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var Zf={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var EM=["target","fromTarget","toTarget"];function eS(r){for(let e of EM){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var tS={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return eS(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])eS(n);return e}default:return e}})};import{v4 as bM}from"uuid";var rS={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=bM()),e;default:return e}})};import{v4 as nS}from"uuid";var oS={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??nS(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??nS()}})),delete e.commands),e;default:return e}})};var iS={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as TM}from"uuid";var aS={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=TM()),e))};import{v4 as sS}from"uuid";var lS={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=sS())}return e.id=sS(),e})};var cS={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as vM}from"uuid";var uS={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=vM()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var dS={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var pS={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&mS(t),e})};function mS(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){mS(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var gS={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var hS={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var fS={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var SS={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var yS={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var ES={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var As=new Set(["CLICK","TYPE","SELECT_OPTION"]),bS={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||As.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||As.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||As.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,g=d?.type;(p!==void 0||As.has(g))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var TS={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var vS={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var Rs=[ES,TS,vS,bS,Qf,Zf,tS,rS,oS,iS,aS,lS,cS,uS,dS,pS,gS,hS,fS,SS,yS];if(un!==Rs[Rs.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Rs.forEach((r,e)=>{if(!Lu.valid(r.toVersion)||!Lu.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Lu.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Rs[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as qJ}from"deep-object-diff";import{cloneDeep as YJ}from"lodash-es";import{v4 as u8}from"uuid";import{cloneDeep as g8}from"lodash-es";import{stringify as C8}from"yaml";async function $(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Nu({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function Cn({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await Nu({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function ws(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import AM from"picomatch";var Cs=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||AM(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},xs=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},yo=r=>{try{return new URL(r),!0}catch{return!1}},RS=r=>!r.toLowerCase().startsWith("http"),Eo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function xn(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as wS}from"uuid";function Du(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var _s=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:Du({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(oh(e.type)){this.creditsUsedV2+=1;return}let t=Qc(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Zc(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:wS(),properties:Du({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:wS(),properties:Du({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{mkdirSync as QO}from"fs";import{tmpdir as ZO}from"os";import Db from"path";import{diff as XO}from"deep-object-diff";import{cloneDeep as JO}from"lodash-es";var Ms=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function RM(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 Is(r,e){let t=RM(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var QS="=",Ns=";",qu=",";var ZS=8192;var Ao={};qA(Ao,{getKeyPairs:()=>nI,parseKeyPairsIntoRecord:()=>oI,parsePairKeyValue:()=>ey,serializeKeyPairs:()=>rI});he();var tI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function rI(r){return r.reduce(function(e,t){var n=""+e+(e!==""?qu:"")+t;return n.length>ZS?e:n},"")}function nI(r){return r.getAllEntries().map(function(e){var t=tI(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Ns+o.metadata.toString()),i})}function ey(r){var e=r.split(Ns);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(QS);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Uu(e.join(Ns))),{key:o,value:i,metadata:a}}}}}function oI(r){return typeof r!="string"||r.length===0?{}:r.split(qu).map(function(e){return ey(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}he();var Ds;(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"})(Ds||(Ds={}));var iI=",",aI=["OTEL_SDK_DISABLED"];function sI(r){return aI.indexOf(r)>-1}var lI=["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 cI(r){return lI.indexOf(r)>-1}var uI=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function dI(r){return uI.indexOf(r)>-1}var Ku=1/0,Yu=128,pI=128,mI=128,Xu={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:we.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ku,OTEL_ATTRIBUTE_COUNT_LIMIT:Yu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ku,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Yu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ku,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Yu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:pI,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:mI,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ds.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 gI(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function hI(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 fI(r,e,t,n){n===void 0&&(n=iI);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var SI={ALL:we.ALL,VERBOSE:we.VERBOSE,DEBUG:we.DEBUG,INFO:we.INFO,WARN:we.WARN,ERROR:we.ERROR,NONE:we.NONE};function yI(r,e,t){var n=t[r];if(typeof n=="string"){var o=SI[n.toUpperCase()];o!=null&&(e[r]=o)}}function ty(r){var e={};for(var t in Xu){var n=t;switch(n){case"OTEL_LOG_LEVEL":yI(n,e,r);break;default:if(sI(n))gI(n,e,r);else if(cI(n))hI(n,e,r);else if(dI(n))fI(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ot(){var r=ty(process.env);return Object.assign({},Xu,r)}function ry(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function ks(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=ry(r.charCodeAt(n)),i=ry(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var ny="1.25.1";var EI="deployment.environment";var bI="process.runtime.name";var TI="service.name";var vI="service.instance.id";var AI="telemetry.sdk.name",RI="telemetry.sdk.language",wI="telemetry.sdk.version";var oy=EI;var iy=bI;var Us=TI;var ay=vI;var Gi=AI,Hi=RI,Vi=wI;var CI="nodejs";var sy=CI;var Ro,Fs=(Ro={},Ro[Gi]="opentelemetry",Ro[iy]="node",Ro[Hi]=sy,Ro[Vi]=ny,Ro);var xI=9,_I=6,MI=Math.pow(10,_I),II=Math.pow(10,xI);function ly(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*MI);return[t,n]}function cy(r){return r[0]*II+r[1]}function ji(r){return r[0]*1e6+r[1]/1e3}var Mn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Mn||(Mn={}));var uy=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 PI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},OI=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))},dy=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new uy}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,OI([this._that],PI(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 zt;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(zt||(zt={}));var ct;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(ct||(ct={}));var LI=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 L7=function(r){LI(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function py(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}he();var Gt;(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"})(Gt||(Gt={}));var my=function(){function r(){this.kind=Gt.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 Z;(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"})(Z||(Z={}));var NI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function DI(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 Ju=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=DI(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=py(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 Qu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Gt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Ju(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,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Ju(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Ju(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},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:ct.HISTOGRAM,dataPoints:n.map(function(i){var a=NI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Z.GAUGE||e.type===Z.UP_DOWN_COUNTER||e.type===Z.OBSERVABLE_GAUGE||e.type===Z.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var Zu=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ed=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))},td=function(){function r(e,t,n,o){e===void 0&&(e=new kI),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 l=a%n;l<0&&(l+=n);for(var c=l;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 kI=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,ed([n,this._counts.length-t],Zu(this._counts.slice(t)),!1)),o.splice.apply(o,ed([0,t],Zu(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(ed([],Zu(this._counts),!1))},r}();var gy=52,UI=2146435072,FI=1048575,rd=1023,Bs=-rd+1,zs=rd,Wi=Math.pow(2,-1022);function Gs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&UI)>>20;return n-rd}function Hs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&FI)*Math.pow(2,32);return o+n}function $i(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function fy(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var BI=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)}}(),Kr=function(r){BI(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var yy=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Wi)return this._minNormalLowerBoundaryIndex();var t=Gs(e),n=this._rightShift(Hs(e)-1,gy);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Kr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Kr("overflow: "+e+" is > maximum lower boundary: "+n);return $i(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=Bs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return zs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Ey=function(){function r(e){this._scale=e,this._scaleFactor=$i(Math.LOG2E,e),this._inverseFactor=$i(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Wi)return this._minNormalLowerBoundaryIndex()-1;if(Hs(e)===0){var t=Gs(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 Kr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Wi;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Kr("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 Bs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(zs+1<<this._scale)-1},r}();var by=-10,Ty=20,zI=Array.from({length:31},function(r,e){return e>10?new Ey(e-10):new yy(e-10)});function nd(r){if(r>Ty||r<by)throw new Kr("expected scale >= "+by+" && <= "+Ty+", got: "+r);return zI[r+10]}var GI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vs=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}(),HI=20,VI=160,od=2,jI=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=VI),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new td),u===void 0&&(u=new td),d===void 0&&(d=nd(HI)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<od&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+od),this._maxSize=od)}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,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);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=fy(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},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=nd(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Vs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Vs.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 Vs(0,-1);var o=t-n;return new Vs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var vy=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Gt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jI(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:ct.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=GI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Z.GAUGE||e.type===Z.UP_DOWN_COUNTER||e.type===Z.OBSERVABLE_GAUGE||e.type===Z.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var WI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},id=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=ly(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ay=function(){function r(){this.kind=Gt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new id(e)},r.prototype.merge=function(e,t){var n=ji(t.sampleTime)>=ji(e.sampleTime)?t:e;return new id(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ji(t.sampleTime)>=ji(e.sampleTime)?t:e;return new id(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.GAUGE,dataPoints:n.map(function(i){var a=WI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var $I=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qi=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 ad=function(){function r(e){this.monotonic=e,this.kind=Gt.SUM}return r.prototype.createAccumulation=function(e){return new qi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qi(t.startTime,this.monotonic,o,t.reset):new qi(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 qi(t.startTime,this.monotonic,o,!0):new qi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.SUM,dataPoints:n.map(function(i){var a=$I(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var In=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)}}(),pr=function(){function r(){}return r.Drop=function(){return Py},r.Sum=function(){return Oy},r.LastValue=function(){return Ly},r.Histogram=function(){return Ny},r.ExponentialHistogram=function(){return qI},r.Default=function(){return KI},r}();var Ry=function(r){In(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 my,e}(pr);var wy=function(r){In(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Z.COUNTER:case Z.OBSERVABLE_COUNTER:case Z.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ad(!0),e.NON_MONOTONIC_INSTANCE=new ad(!1),e}(pr);var Cy=function(r){In(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 Ay,e}(pr);var xy=function(r){In(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 Qu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(pr);var _y=function(r){In(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(l,c){return l-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 Qu(this._boundaries,this._recordMinMax)},e}(pr);var My=function(r){In(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 vy(this._maxSize,this._recordMinMax)},e}(pr);var Iy=function(r){In(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Z.COUNTER:case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:return Oy;case Z.GAUGE:case Z.OBSERVABLE_GAUGE:return Ly;case Z.HISTOGRAM:return t.advice.explicitBucketBoundaries?new _y(t.advice.explicitBucketBoundaries):Ny}return F.warn("Unable to recognize instrument type: "+t.type),Py},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(pr);var Py=new Ry,Oy=new wy,Ly=new Cy,Ny=new xy,qI=new My,KI=new Iy;he();function js(){return"unknown_service:"+process.argv0}var Yr=function(){return Yr=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},Yr.apply(this,arguments)},YI=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},XI=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},JI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sd=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 F.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[Us]=js(),e[Hi]=Fs[Hi],e[Gi]=Fs[Gi],e[Vi]=Fs[Vi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.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 YI(this,void 0,void 0,function(){return XI(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=Yr(Yr({},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 l,c=JI(a,2),s=c[0],u=c[1];return Yr(Yr(Yr(Yr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var Pn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Pn||(Pn={}));he();var QI=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ZI=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},ld=function(){return zt.CUMULATIVE},Dy=function(r){switch(r){case Z.COUNTER:case Z.OBSERVABLE_COUNTER:case Z.GAUGE:case Z.HISTOGRAM:case Z.OBSERVABLE_GAUGE:return zt.DELTA;case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:return zt.CUMULATIVE}},ky=function(r){switch(r){case Z.COUNTER:case Z.HISTOGRAM:return zt.DELTA;case Z.GAUGE:case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:case Z.OBSERVABLE_COUNTER:case Z.OBSERVABLE_GAUGE:return zt.CUMULATIVE}};function eP(){var r=ot(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?ld:e==="delta"?Dy:e==="lowmemory"?ky:(F.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."),ld)}function tP(r){return r!=null?r===Pn.DELTA?Dy:r===Pn.LOWMEMORY?ky:ld:eP()}function rP(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return pr.Default()}}var Uy=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=rP(t),this._aggregationTemporalitySelector=tP(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return QI(this,void 0,void 0,function(){return ZI(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}();he();he();var nP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Fy=1e4,By=5,zy=1e3,Gy=5e3,Hy=1.5;function Ki(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=nP(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):F.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function cd(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function ud(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return F.warn("Could not parse export URL: '"+r+"'"),r}}function dd(r){return typeof r=="number"?r<=0?pd(r,Fy):r:oP()}function oP(){var r,e=Number((r=ot().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ot().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?pd(e,Fy):e}function pd(r,e){return F.warn("Timeout must be greater than 0",r),e}function Vy(r){var e=[429,502,503,504];return e.includes(r)}function jy(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 Wy=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 dy(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=dd(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Mn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Mn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Mn.SUCCESS})}).catch(function(n){t({code:Mn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{F.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 F.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();he();import*as md from"url";import*as $s from"http";import*as qs from"https";import*as $y from"zlib";import{Readable as aP}from"stream";var Xr;(function(r){r.NONE="none",r.GZIP="gzip"})(Xr||(Xr={}));var iP=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)}}(),wo=function(r){iP(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 Ws=function(){return Ws=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},Ws.apply(this,arguments)};function gd(r,e,t,n,o){var i=r.timeoutMillis,a=new md.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new wo("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Ws({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?$s.request:qs.request,m=function(h,f){switch(h===void 0&&(h=By),f===void 0&&(f=zy),s=g(p,function(b){var v="";b.on("data",function(w){return v+=w}),b.on("aborted",function(){if(u){var w=new wo("Request Timeout");o(w)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)F.debug("statusCode: "+b.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&Vy(b.statusCode)&&h>0){var w=void 0;f=Hy*f,b.headers["retry-after"]?w=jy(b.headers["retry-after"]):w=Math.round(Math.random()*(Gy-f)+f),c=setTimeout(function(){m(h-1,f)},w)}else{var T=new wo(b.statusMessage,b.statusCode,v);o(T),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(b){if(u){var v=new wo("Request Timeout",b.code);o(v)}else o(b);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var b=new wo("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Xr.GZIP:{s.setHeader("Content-Encoding","gzip");var E=sP(e);E.on("error",o).pipe($y.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};m()}function sP(r){var e=new aP;return e.push(r),e.push(null),e}function hd(r){if(r.httpAgentOptions&&r.keepAlive===!1){F.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new md.URL(r.url),t=e.protocol==="http:"?$s.Agent:qs.Agent;return new t(Ws({keepAlive:!0},r.httpAgentOptions))}catch(n){F.error("collector exporter failed to create http agent. err: "+n.message);return}}function fd(r){if(r)return r;var e=ot().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ot().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Xr.GZIP?Xr.GZIP:Xr.NONE}he();var lP=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)}}(),Ks=function(r){lP(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&&F.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ki(t.headers),Ao.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=hd(t),i.compression=fd(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){F.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;gd(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(Wy);function Ky(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function cP(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Yy(r){var e=Ky(r);return cP(e)}function uP(r){var e=Ky(r);return e.toString()}var dP=typeof BigInt<"u"?uP:cy;function qy(r){return r}function Xy(r){if(r!==void 0)return ks(r)}var pP={encodeHrTime:Yy,encodeSpanContext:ks,encodeOptionalSpanContext:Xy};function Jy(r){var e,t;if(r===void 0)return pP;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Yy:dP,encodeSpanContext:o?qy:ks,encodeOptionalSpanContext:o?qy:Xy}}var mP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Qy(r){return{name:r.name,version:r.version}}function Co(r){return Object.keys(r).map(function(e){return Zy(e,r[e])})}function Zy(r,e){return{key:r,value:eE(e)}}function eE(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(eE)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=mP(t,2),o=n[0],i=n[1];return Zy(o,i)})}}:{}}function tE(r){return{attributes:Co(r.attributes),droppedAttributesCount:0}}he();function nE(r,e){var t=Jy(e);return{resource:tE(r.resource),schemaUrl:void 0,scopeMetrics:gP(r.scopeMetrics,t)}}function gP(r,e){return Array.from(r.map(function(t){return{scope:Qy(t.scope),metrics:t.metrics.map(function(n){return hP(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function hP(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=EP(r.aggregationTemporality);switch(r.dataPointType){case ct.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:rE(r,e)};break;case ct.GAUGE:t.gauge={dataPoints:rE(r,e)};break;case ct.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:SP(r,e)};break;case ct.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:yP(r,e)};break}return t}function fP(r,e,t){var n={attributes:Co(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case _t.INT:n.asInt=r.value;break;case _t.DOUBLE:n.asDouble=r.value;break}return n}function rE(r,e){return r.dataPoints.map(function(t){return fP(t,r.descriptor.valueType,e)})}function SP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Co(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 yP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Co(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 EP(r){switch(r){case zt.DELTA:return 1;case zt.CUMULATIVE:return 2}}function oE(r,e){return{resourceMetrics:r.map(function(t){return nE(t,e)})}}var Sd={serializeRequest:function(r){var e=oE(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 iE="0.52.1";var aE=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)}}(),xo=function(){return xo=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},xo.apply(this,arguments)},sE="v1/metrics",bP="http://localhost:4318/"+sE,TP={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+iE},vP=function(r){aE(e,r);function e(t){var n=r.call(this,t,Sd,"application/json")||this;return n.headers=xo(xo(xo(xo({},n.headers),TP),Ao.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ki(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?ud(ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ot().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?cd(ot().OTEL_EXPORTER_OTLP_ENDPOINT,sE):bP},e}(Ks),lE=function(r){aE(e,r);function e(t){return r.call(this,new vP(t),t)||this}return e}(Uy);var _o;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(_o||(_o={}));var mr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(mr||(mr={}));he();var AP=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)}}(),cE=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},uE=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},RP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wP=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){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 dE(r){return r!=null}function Ys(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function pE(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var yd=function(r){AP(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Jr(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new yd("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function mE(r){return cE(this,void 0,void 0,function(){var e=this;return uE(this,function(t){return[2,Promise.all(r.map(function(n){return cE(e,void 0,void 0,function(){var o,i;return uE(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 gE(r){return r.status==="rejected"}function Ed(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,wP([],RP(e(n)),!1))}),t}function hE(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=CP(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function fE(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 SE(r,e){return r.toLowerCase()===e.toLowerCase()}he();var Ht;(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"})(Ht||(Ht={}));var bd=function(){function r(){this.kind=Ht.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}();he();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));function gr(r,e,t){var n,o,i,a;return _P(r)||F.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:_t.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function yE(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 EE(r,e){return SE(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var xP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function _P(r){return r.match(xP)!=null}var MP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function IP(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 Xs=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=IP(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=fE(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 Js=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Ht.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Xs(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,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Xs(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Xs(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},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:mr.HISTOGRAM,dataPoints:n.map(function(i){var a=MP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var Td=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},vd=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))},Ad=function(){function r(e,t,n,o){e===void 0&&(e=new PP),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 l=a%n;l<0&&(l+=n);for(var c=l;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 PP=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,vd([n,this._counts.length-t],Td(this._counts.slice(t)),!1)),o.splice.apply(o,vd([0,t],Td(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(vd([],Td(this._counts),!1))},r}();var bE=52,OP=2146435072,LP=1048575,Rd=1023,Qs=-Rd+1,Zs=Rd,Yi=Math.pow(2,-1022);function el(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&OP)>>20;return n-Rd}function tl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LP)*Math.pow(2,32);return o+n}function Xi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function vE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NP=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)}}(),Qr=function(r){NP(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var RE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Yi)return this._minNormalLowerBoundaryIndex();var t=el(e),n=this._rightShift(tl(e)-1,bE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Qr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qr("overflow: "+e+" is > maximum lower boundary: "+n);return Xi(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=Qs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Zs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var wE=function(){function r(e){this._scale=e,this._scaleFactor=Xi(Math.LOG2E,e),this._inverseFactor=Xi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Yi)return this._minNormalLowerBoundaryIndex()-1;if(tl(e)===0){var t=el(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 Qr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Yi;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qr("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 Qs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Zs+1<<this._scale)-1},r}();var CE=-10,xE=20,DP=Array.from({length:31},function(r,e){return e>10?new wE(e-10):new RE(e-10)});function wd(r){if(r>xE||r<CE)throw new Qr("expected scale >= "+CE+" && <= "+xE+", got: "+r);return DP[r+10]}var kP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},rl=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}(),UP=20,FP=160,Cd=2,_E=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=FP),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Ad),u===void 0&&(u=new Ad),d===void 0&&(d=wd(UP)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Cd&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Cd),this._maxSize=Cd)}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,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);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=vE(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},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=wd(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=rl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=rl.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 rl(0,-1);var o=t-n;return new rl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var xd=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Ht.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new _E(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:mr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();he();var BP=Fu("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function ME(r){return r.setValue(BP,!0)}he();function IE(){return function(r){F.error(zP(r))}}function zP(r){return typeof r=="string"?r:JSON.stringify(GP(r))}function GP(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 HP=IE();function nl(r){try{HP(r)}catch{}}var PE="1.30.1";var VP="process.runtime.name";var jP="service.name";var WP="telemetry.sdk.name",$P="telemetry.sdk.language",qP="telemetry.sdk.version";var OE=VP;var LE=jP;var Ji=WP,Qi=$P,Zi=qP;var KP="nodejs";var NE=KP;var Mo,On=(Mo={},Mo[Ji]="opentelemetry",Mo[OE]="node",Mo[Qi]=NE,Mo[Zi]=PE,Mo);function ea(r){r.unref()}var tO=9,rO=6,nO=Math.pow(10,rO),Uee=Math.pow(10,tO);function Ln(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*nO);return[t,n]}function Io(r){return r[0]*1e6+r[1]/1e3}var ta;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ta||(ta={}));he();function DE(r,e){return new Promise(function(t){vo.with(ME(vo.active()),function(){r.export(e,function(n){t(n)})})})}var kE={_export:DE};var oO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ol=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=Ln(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var _d=function(){function r(){this.kind=Ht.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new ol(e)},r.prototype.merge=function(e,t){var n=Io(t.sampleTime)>=Io(e.sampleTime)?t:e;return new ol(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Io(t.sampleTime)>=Io(e.sampleTime)?t:e;return new ol(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.GAUGE,dataPoints:n.map(function(i){var a=oO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var iO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Po=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 il=function(){function r(e){this.monotonic=e,this.kind=Ht.SUM}return r.prototype.createAccumulation=function(e){return new Po(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Po(t.startTime,this.monotonic,o,t.reset):new Po(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 Po(t.startTime,this.monotonic,o,!0):new Po(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.SUM,dataPoints:n.map(function(i){var a=iO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Nn=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)}}(),Vt=function(){function r(){}return r.Drop=function(){return VE},r.Sum=function(){return jE},r.LastValue=function(){return WE},r.Histogram=function(){return $E},r.ExponentialHistogram=function(){return aO},r.Default=function(){return sO},r}();var UE=function(r){Nn(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 bd,e}(Vt);var FE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new il(!0),e.NON_MONOTONIC_INSTANCE=new il(!1),e}(Vt);var BE=function(r){Nn(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 _d,e}(Vt);var zE=function(r){Nn(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 Js([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Vt);var al=function(r){Nn(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(l,c){return l-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 Js(this._boundaries,this._recordMinMax)},e}(Vt);var GE=function(r){Nn(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 xd(this._maxSize,this._recordMinMax)},e}(Vt);var HE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return jE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return WE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new al(t.advice.explicitBucketBoundaries):$E}return F.warn("Unable to recognize instrument type: "+t.type),VE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Vt);var VE=new UE,jE=new FE,WE=new BE,$E=new zE,aO=new GE,sO=new HE;var qE=function(r){return Vt.Default()},KE=function(r){return _o.CUMULATIVE};var Md=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Id=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},YE=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lO=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))},XE=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:qE,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:KE,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 Md(this,void 0,void 0,function(){var t,n,o,i,a,l;return Id(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(lO([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],YE(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=YE.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Ed(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Ed(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return Md(this,void 0,void 0,function(){return Id(this,function(t){switch(t.label){case 0:return this._shutdown?(F.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,Jr(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Md(this,void 0,void 0,function(){return Id(this,function(t){switch(t.label){case 0:return this._shutdown?(F.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,Jr(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();he();var cO=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)}}(),sl=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ll=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},uO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dO=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))},Pd=function(r){cO(e,r);function e(t){var n,o,i,a,l=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 l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return sl(this,void 0,void 0,function(){var t;return ll(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Jr(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof yd?(F.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(nl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return sl(this,void 0,void 0,function(){var o,i,a,l,c,s;return ll(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&&(s=F).error.apply(s,dO(["PeriodicExportingMetricReader: metrics collection errors"],uO(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 l=u.sent(),F.debug("Error while resolving async portion of resource: ",l),nl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,kE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ta.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),ea(this._interval)},e.prototype.onForceFlush=function(){return sl(this,void 0,void 0,function(){return ll(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 sl(this,void 0,void 0,function(){return ll(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}(XE);he();he();function cl(){return"unknown_service:"+process.argv0}var Zr=function(){return Zr=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},Zr.apply(this,arguments)},pO=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},mO=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},gO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ul=function(){function r(e,t){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 F.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[LE]=cl(),e[Qi]=On[Qi],e[Ji]=On[Ji],e[Zi]=On[Zi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.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 pO(this,void 0,void 0,function(){return mO(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=Zr(Zr({},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 l,c=gO(a,2),s=c[0],u=c[1];return Zr(Zr(Zr(Zr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var JE=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}();he();var Dn=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)}}(),dl=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=vo.active()),typeof e!="number"){F.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===_t.INT&&!Number.isInteger(e)&&(F.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,Ln(Date.now()))},r}();var QE=function(r){Dn(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}(dl);var ZE=function(r){Dn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){F.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(dl);var eb=function(r){Dn(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}(dl);var tb=function(r){Dn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){F.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(dl);var pl=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 rb=function(r){Dn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(pl);var nb=function(r){Dn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(pl);var ob=function(r){Dn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(pl);function ra(r){return r instanceof pl}var ib=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=gr(e,oe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new eb(o,n)},r.prototype.createHistogram=function(e,t){var n=gr(e,oe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new tb(o,n)},r.prototype.createCounter=function(e,t){var n=gr(e,oe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new ZE(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=gr(e,oe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new QE(o,n)},r.prototype.createObservableGauge=function(e,t){var n=gr(e,oe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new nb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new ob(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 ml=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=gr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var hO=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)}}(),ab=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},fO=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 ab(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 ab(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 Jt=function(r){hO(e,r);function e(){return r.call(this,Ys)||this}return e}(fO);var SO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gl=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Jt,this._cumulativeMemoStorage=new Jt,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Ys(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 l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.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=SO(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}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,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Jt,e},r}();var Od=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.")},sb=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hl=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,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===_o.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=yO(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Od(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}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 Jt,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Od(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.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 l=sb(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Od(e.keys()),l=a.next();!l.done;l=a.next()){var c=sb(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function yO(r){return Array.from(r.entries())}var EO=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)}}(),bO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lb=function(r){EO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new gl(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new hl(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Jt;Array.from(t.entries()).forEach(function(a){var l=bO(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),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}(ml);he();function Ld(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
12
+ ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as cM}from"lodash-es";async function xu(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Hr,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await ur({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new w("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Ss(r){return Ff(r)}async function Ff({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await xu({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await Ff({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function ys(r,e){for(let{path:t,original:n}of e)cM(r,t,n)}import uM from"fetch-retry";var YX=process.env.MAILINATOR_API_KEY,XX=uM(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{randomUUID as vD}from"crypto";import AD from"path";function _u({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=Gr.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=mM(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_CHECK")return;l.push(g[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!Ja(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=_u({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}default:{let m=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function pM(r,e){return e?`${e}:${r}`:r}function mM(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function Mu(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
13
+ ${JSON.stringify(t)}`);let n=[];return n.push({key:pM(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Es({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&km(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function bs(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}function St(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var vn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},An={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Bf={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},zf={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var $5={CONTENT:"The page"};function Gf(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function gM(r){return typeof r=="object"&&r!==null}function Tn(r){if(Array.isArray(r))return r.map(Tn);if(gM(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Tn(n))}),e}return r}function hM(r){switch(r.type){case"OPEN_APP":return`Open app: ${r.packageName}`;case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${ou(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${ou(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function Hf(r){switch(r.type){case"MOBILE_PRESET_STEP":return hM(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as Vf}from"lodash-es";async function jf(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Ts({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:l}=await Ts({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=l}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function Ts({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await Wf({rawStep:Yt.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function Wf({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...Vf(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let l;try{l=Yt.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(l.map(u=>Wf({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=Vf(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as fM}from"lodash-es";import{v4 as Iu}from"uuid";async function Rn(r){let e=new Map,t=new Set,n=fM(r.steps),o=await $f({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function $f({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Iu():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Iu():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Mu({id:d.id,orgId:n.orgId,testId:n.testId,value:Gr.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Iu():u.id,p=u.moduleId;a.has(p)?p=a.get(p):l!==void 0&&(p=await l(u),a.set(u.moduleId,p));let{cachesToSave:m,stepsToSave:g,moduleUpdates:h}=await $f({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(h),s.cachesToSave=s.cachesToSave.concat(m),t.has(p)||(t.add(p),s.moduleUpdates.push({...po.parse(u),steps:Yt.array().parse(g),moduleId:p}));let f=Ci.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}default:{let d=u}}return s}function SM(r){let e={parentChain:[]};return qf(r,e),e}function qf(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),qf({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function yM(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return SM({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Kf({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!yM([r],t,i).result}function Yf(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let l=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let l=i}}return{firstMetadata:e,lastMetadata:o}}function Xf({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as H3}from"lodash-es";import j3 from"truncate-json";import{v4 as Z3}from"uuid";import{cloneDeep as O3,unset as L3}from"lodash-es";import{cloneDeep as o4}from"lodash-es";import{cloneDeep as xJ}from"lodash-es";import K4 from"diff-lines";import Pu,{gte as X4}from"semver";var Jf={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var Qf={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var EM=["target","fromTarget","toTarget"];function Zf(r){for(let e of EM){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var eS={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return Zf(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Zf(n);return e}default:return e}})};import{v4 as bM}from"uuid";var tS={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=bM()),e;default:return e}})};import{v4 as rS}from"uuid";var nS={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??rS(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??rS()}})),delete e.commands),e;default:return e}})};var oS={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as TM}from"uuid";var iS={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=TM()),e))};import{v4 as aS}from"uuid";var sS={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=aS())}return e.id=aS(),e})};var lS={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as vM}from"uuid";var cS={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=vM()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var uS={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var dS={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&pS(t),e})};function pS(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){pS(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var mS={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var gS={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var hS={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var fS={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var SS={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var yS={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var vs=new Set(["CLICK","TYPE","SELECT_OPTION"]),ES={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||vs.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||vs.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||vs.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||vs.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var bS={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var TS={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var As=[yS,bS,TS,ES,Jf,Qf,eS,tS,nS,oS,iS,sS,lS,cS,uS,dS,mS,gS,hS,fS,SS];if(un!==As[As.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");As.forEach((r,e)=>{if(!Pu.valid(r.toVersion)||!Pu.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Pu.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(As[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as WJ}from"deep-object-diff";import{cloneDeep as qJ}from"lodash-es";import{v4 as l8}from"uuid";import{cloneDeep as p8}from"lodash-es";import{stringify as R8}from"yaml";async function $(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Ou({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function wn({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await Ou({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function Rs(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import AM from"picomatch";var ws=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||AM(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},Cs=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},So=r=>{try{return new URL(r),!0}catch{return!1}},AS=r=>!r.toLowerCase().startsWith("http"),yo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Cn(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as RS}from"uuid";function Lu(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var xs=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:Lu({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(rh(e.type)){this.creditsUsedV2+=1;return}let t=Jc(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Qc(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:RS(),properties:Lu({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:RS(),properties:Lu({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{mkdirSync as QO}from"fs";import{tmpdir as ZO}from"os";import Nb from"path";import{diff as XO}from"deep-object-diff";import{cloneDeep as JO}from"lodash-es";var _s=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function RM(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 Ms(r,e){let t=RM(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var JS="=",Ls=";",Wu=",";var QS=8192;var vo={};$A(vo,{getKeyPairs:()=>nI,parseKeyPairsIntoRecord:()=>oI,parsePairKeyValue:()=>ZS,serializeKeyPairs:()=>rI});he();var tI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function rI(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Wu:"")+t;return n.length>QS?e:n},"")}function nI(r){return r.getAllEntries().map(function(e){var t=tI(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Ls+o.metadata.toString()),i})}function ZS(r){var e=r.split(Ls);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(JS);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Du(e.join(Ls))),{key:o,value:i,metadata:a}}}}}function oI(r){return typeof r!="string"||r.length===0?{}:r.split(Wu).map(function(e){return ZS(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}he();var Ns;(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"})(Ns||(Ns={}));var iI=",",aI=["OTEL_SDK_DISABLED"];function sI(r){return aI.indexOf(r)>-1}var lI=["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 cI(r){return lI.indexOf(r)>-1}var uI=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function dI(r){return uI.indexOf(r)>-1}var $u=1/0,qu=128,pI=128,mI=128,Ku={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:we.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:pI,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:mI,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ns.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 gI(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function hI(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 fI(r,e,t,n){n===void 0&&(n=iI);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var SI={ALL:we.ALL,VERBOSE:we.VERBOSE,DEBUG:we.DEBUG,INFO:we.INFO,WARN:we.WARN,ERROR:we.ERROR,NONE:we.NONE};function yI(r,e,t){var n=t[r];if(typeof n=="string"){var o=SI[n.toUpperCase()];o!=null&&(e[r]=o)}}function ey(r){var e={};for(var t in Ku){var n=t;switch(n){case"OTEL_LOG_LEVEL":yI(n,e,r);break;default:if(sI(n))gI(n,e,r);else if(cI(n))hI(n,e,r);else if(dI(n))fI(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ot(){var r=ey(process.env);return Object.assign({},Ku,r)}function ty(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Ds(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=ty(r.charCodeAt(n)),i=ty(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var ry="1.25.1";var EI="deployment.environment";var bI="process.runtime.name";var TI="service.name";var vI="service.instance.id";var AI="telemetry.sdk.name",RI="telemetry.sdk.language",wI="telemetry.sdk.version";var ny=EI;var oy=bI;var ks=TI;var iy=vI;var zi=AI,Gi=RI,Hi=wI;var CI="nodejs";var ay=CI;var Ao,Us=(Ao={},Ao[zi]="opentelemetry",Ao[oy]="node",Ao[Gi]=ay,Ao[Hi]=ry,Ao);var xI=9,_I=6,MI=Math.pow(10,_I),II=Math.pow(10,xI);function sy(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*MI);return[t,n]}function ly(r){return r[0]*II+r[1]}function Vi(r){return r[0]*1e6+r[1]/1e3}var _n;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_n||(_n={}));var cy=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 PI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},OI=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))},uy=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new cy}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,OI([this._that],PI(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 zt;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(zt||(zt={}));var ct;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(ct||(ct={}));var LI=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 P7=function(r){LI(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function dy(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}he();var Gt;(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"})(Gt||(Gt={}));var py=function(){function r(){this.kind=Gt.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 ee;(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"})(ee||(ee={}));var NI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function DI(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 Yu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=DI(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=dy(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 Xu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Gt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Yu(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,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Yu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Yu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},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:ct.HISTOGRAM,dataPoints:n.map(function(i){var a=NI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ee.GAUGE||e.type===ee.UP_DOWN_COUNTER||e.type===ee.OBSERVABLE_GAUGE||e.type===ee.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var Ju=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Qu=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))},Zu=function(){function r(e,t,n,o){e===void 0&&(e=new kI),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 l=a%n;l<0&&(l+=n);for(var c=l;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 kI=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,Qu([n,this._counts.length-t],Ju(this._counts.slice(t)),!1)),o.splice.apply(o,Qu([0,t],Ju(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(Qu([],Ju(this._counts),!1))},r}();var my=52,UI=2146435072,FI=1048575,ed=1023,Fs=-ed+1,Bs=ed,ji=Math.pow(2,-1022);function zs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&UI)>>20;return n-ed}function Gs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&FI)*Math.pow(2,32);return o+n}function Wi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function hy(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var BI=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)}}(),Kr=function(r){BI(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Sy=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ji)return this._minNormalLowerBoundaryIndex();var t=zs(e),n=this._rightShift(Gs(e)-1,my);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Kr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Kr("overflow: "+e+" is > maximum lower boundary: "+n);return Wi(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=Fs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Bs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var yy=function(){function r(e){this._scale=e,this._scaleFactor=Wi(Math.LOG2E,e),this._inverseFactor=Wi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ji)return this._minNormalLowerBoundaryIndex()-1;if(Gs(e)===0){var t=zs(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 Kr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ji;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Kr("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 Fs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Bs+1<<this._scale)-1},r}();var Ey=-10,by=20,zI=Array.from({length:31},function(r,e){return e>10?new yy(e-10):new Sy(e-10)});function td(r){if(r>by||r<Ey)throw new Kr("expected scale >= "+Ey+" && <= "+by+", got: "+r);return zI[r+10]}var GI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hs=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}(),HI=20,VI=160,rd=2,jI=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=VI),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Zu),u===void 0&&(u=new Zu),d===void 0&&(d=td(HI)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<rd&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+rd),this._maxSize=rd)}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,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);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=hy(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},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=td(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Hs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Hs.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 Hs(0,-1);var o=t-n;return new Hs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Ty=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Gt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jI(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:ct.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=GI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ee.GAUGE||e.type===ee.UP_DOWN_COUNTER||e.type===ee.OBSERVABLE_GAUGE||e.type===ee.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var WI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nd=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=sy(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vy=function(){function r(){this.kind=Gt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new nd(e)},r.prototype.merge=function(e,t){var n=Vi(t.sampleTime)>=Vi(e.sampleTime)?t:e;return new nd(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Vi(t.sampleTime)>=Vi(e.sampleTime)?t:e;return new nd(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.GAUGE,dataPoints:n.map(function(i){var a=WI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var $I=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},$i=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 od=function(){function r(e){this.monotonic=e,this.kind=Gt.SUM}return r.prototype.createAccumulation=function(e){return new $i(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new $i(t.startTime,this.monotonic,o,t.reset):new $i(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 $i(t.startTime,this.monotonic,o,!0):new $i(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.SUM,dataPoints:n.map(function(i){var a=$I(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Mn=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)}}(),pr=function(){function r(){}return r.Drop=function(){return Iy},r.Sum=function(){return Py},r.LastValue=function(){return Oy},r.Histogram=function(){return Ly},r.ExponentialHistogram=function(){return qI},r.Default=function(){return KI},r}();var Ay=function(r){Mn(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 py,e}(pr);var Ry=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ee.COUNTER:case ee.OBSERVABLE_COUNTER:case ee.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new od(!0),e.NON_MONOTONIC_INSTANCE=new od(!1),e}(pr);var wy=function(r){Mn(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 vy,e}(pr);var Cy=function(r){Mn(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 Xu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(pr);var xy=function(r){Mn(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(l,c){return l-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 Xu(this._boundaries,this._recordMinMax)},e}(pr);var _y=function(r){Mn(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 Ty(this._maxSize,this._recordMinMax)},e}(pr);var My=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ee.COUNTER:case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:return Py;case ee.GAUGE:case ee.OBSERVABLE_GAUGE:return Oy;case ee.HISTOGRAM:return t.advice.explicitBucketBoundaries?new xy(t.advice.explicitBucketBoundaries):Ly}return F.warn("Unable to recognize instrument type: "+t.type),Iy},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(pr);var Iy=new Ay,Py=new Ry,Oy=new wy,Ly=new Cy,qI=new _y,KI=new My;he();function Vs(){return"unknown_service:"+process.argv0}var Yr=function(){return Yr=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},Yr.apply(this,arguments)},YI=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},XI=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},JI=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},id=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 F.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[ks]=Vs(),e[Gi]=Us[Gi],e[zi]=Us[zi],e[Hi]=Us[Hi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.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 YI(this,void 0,void 0,function(){return XI(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=Yr(Yr({},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 l,c=JI(a,2),s=c[0],u=c[1];return Yr(Yr(Yr(Yr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var In;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(In||(In={}));he();var QI=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ZI=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},ad=function(){return zt.CUMULATIVE},Ny=function(r){switch(r){case ee.COUNTER:case ee.OBSERVABLE_COUNTER:case ee.GAUGE:case ee.HISTOGRAM:case ee.OBSERVABLE_GAUGE:return zt.DELTA;case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:return zt.CUMULATIVE}},Dy=function(r){switch(r){case ee.COUNTER:case ee.HISTOGRAM:return zt.DELTA;case ee.GAUGE:case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:case ee.OBSERVABLE_COUNTER:case ee.OBSERVABLE_GAUGE:return zt.CUMULATIVE}};function eP(){var r=ot(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?ad:e==="delta"?Ny:e==="lowmemory"?Dy:(F.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."),ad)}function tP(r){return r!=null?r===In.DELTA?Ny:r===In.LOWMEMORY?Dy:ad:eP()}function rP(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return pr.Default()}}var ky=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=rP(t),this._aggregationTemporalitySelector=tP(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return QI(this,void 0,void 0,function(){return ZI(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}();he();he();var nP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Uy=1e4,Fy=5,By=1e3,zy=5e3,Gy=1.5;function qi(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=nP(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):F.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function sd(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function ld(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return F.warn("Could not parse export URL: '"+r+"'"),r}}function cd(r){return typeof r=="number"?r<=0?ud(r,Uy):r:oP()}function oP(){var r,e=Number((r=ot().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ot().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ud(e,Uy):e}function ud(r,e){return F.warn("Timeout must be greater than 0",r),e}function Hy(r){var e=[429,502,503,504];return e.includes(r)}function Vy(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 jy=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 uy(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=cd(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:_n.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:_n.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:_n.SUCCESS})}).catch(function(n){t({code:_n.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{F.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 F.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();he();import*as dd from"url";import*as Ws from"http";import*as $s from"https";import*as Wy from"zlib";import{Readable as aP}from"stream";var Xr;(function(r){r.NONE="none",r.GZIP="gzip"})(Xr||(Xr={}));var iP=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)}}(),Ro=function(r){iP(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 js=function(){return js=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},js.apply(this,arguments)};function pd(r,e,t,n,o){var i=r.timeoutMillis,a=new dd.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new Ro("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:js({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Ws.request:$s.request,g=function(h,f){switch(h===void 0&&(h=Fy),f===void 0&&(f=By),s=m(p,function(b){var v="";b.on("data",function(A){return v+=A}),b.on("aborted",function(){if(u){var A=new Ro("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)F.debug("statusCode: "+b.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&Hy(b.statusCode)&&h>0){var A=void 0;f=Gy*f,b.headers["retry-after"]?A=Vy(b.headers["retry-after"]):A=Math.round(Math.random()*(zy-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var T=new Ro(b.statusMessage,b.statusCode,v);o(T),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(b){if(u){var v=new Ro("Request Timeout",b.code);o(v)}else o(b);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var b=new Ro("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Xr.GZIP:{s.setHeader("Content-Encoding","gzip");var E=sP(e);E.on("error",o).pipe(Wy.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function sP(r){var e=new aP;return e.push(r),e.push(null),e}function md(r){if(r.httpAgentOptions&&r.keepAlive===!1){F.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new dd.URL(r.url),t=e.protocol==="http:"?Ws.Agent:$s.Agent;return new t(js({keepAlive:!0},r.httpAgentOptions))}catch(n){F.error("collector exporter failed to create http agent. err: "+n.message);return}}function gd(r){if(r)return r;var e=ot().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ot().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Xr.GZIP?Xr.GZIP:Xr.NONE}he();var lP=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)}}(),qs=function(r){lP(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&&F.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,qi(t.headers),vo.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=md(t),i.compression=gd(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){F.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;pd(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(jy);function qy(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function cP(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Ky(r){var e=qy(r);return cP(e)}function uP(r){var e=qy(r);return e.toString()}var dP=typeof BigInt<"u"?uP:ly;function $y(r){return r}function Yy(r){if(r!==void 0)return Ds(r)}var pP={encodeHrTime:Ky,encodeSpanContext:Ds,encodeOptionalSpanContext:Yy};function Xy(r){var e,t;if(r===void 0)return pP;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Ky:dP,encodeSpanContext:o?$y:Ds,encodeOptionalSpanContext:o?$y:Yy}}var mP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Jy(r){return{name:r.name,version:r.version}}function wo(r){return Object.keys(r).map(function(e){return Qy(e,r[e])})}function Qy(r,e){return{key:r,value:Zy(e)}}function Zy(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(Zy)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=mP(t,2),o=n[0],i=n[1];return Qy(o,i)})}}:{}}function eE(r){return{attributes:wo(r.attributes),droppedAttributesCount:0}}he();function rE(r,e){var t=Xy(e);return{resource:eE(r.resource),schemaUrl:void 0,scopeMetrics:gP(r.scopeMetrics,t)}}function gP(r,e){return Array.from(r.map(function(t){return{scope:Jy(t.scope),metrics:t.metrics.map(function(n){return hP(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function hP(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=EP(r.aggregationTemporality);switch(r.dataPointType){case ct.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:tE(r,e)};break;case ct.GAUGE:t.gauge={dataPoints:tE(r,e)};break;case ct.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:SP(r,e)};break;case ct.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:yP(r,e)};break}return t}function fP(r,e,t){var n={attributes:wo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case _t.INT:n.asInt=r.value;break;case _t.DOUBLE:n.asDouble=r.value;break}return n}function tE(r,e){return r.dataPoints.map(function(t){return fP(t,r.descriptor.valueType,e)})}function SP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:wo(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 yP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:wo(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 EP(r){switch(r){case zt.DELTA:return 1;case zt.CUMULATIVE:return 2}}function nE(r,e){return{resourceMetrics:r.map(function(t){return rE(t,e)})}}var hd={serializeRequest:function(r){var e=nE(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 oE="0.52.1";var iE=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)}}(),Co=function(){return Co=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},Co.apply(this,arguments)},aE="v1/metrics",bP="http://localhost:4318/"+aE,TP={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+oE},vP=function(r){iE(e,r);function e(t){var n=r.call(this,t,hd,"application/json")||this;return n.headers=Co(Co(Co(Co({},n.headers),TP),vo.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),qi(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?ld(ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ot().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?sd(ot().OTEL_EXPORTER_OTLP_ENDPOINT,aE):bP},e}(qs),sE=function(r){iE(e,r);function e(t){return r.call(this,new vP(t),t)||this}return e}(ky);var xo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(xo||(xo={}));var mr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(mr||(mr={}));he();var AP=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)}}(),lE=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},cE=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},RP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wP=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){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 uE(r){return r!=null}function Ks(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function dE(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var fd=function(r){AP(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Jr(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new fd("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function pE(r){return lE(this,void 0,void 0,function(){var e=this;return cE(this,function(t){return[2,Promise.all(r.map(function(n){return lE(e,void 0,void 0,function(){var o,i;return cE(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 mE(r){return r.status==="rejected"}function Sd(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,wP([],RP(e(n)),!1))}),t}function gE(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=CP(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function hE(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 fE(r,e){return r.toLowerCase()===e.toLowerCase()}he();var Ht;(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"})(Ht||(Ht={}));var yd=function(){function r(){this.kind=Ht.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}();he();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));function gr(r,e,t){var n,o,i,a;return _P(r)||F.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:_t.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function SE(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 yE(r,e){return fE(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var xP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function _P(r){return r.match(xP)!=null}var MP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function IP(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 Ys=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=IP(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=hE(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 Xs=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Ht.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Ys(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,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Ys(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Ys(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},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:mr.HISTOGRAM,dataPoints:n.map(function(i){var a=MP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bd=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))},Td=function(){function r(e,t,n,o){e===void 0&&(e=new PP),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 l=a%n;l<0&&(l+=n);for(var c=l;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 PP=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,bd([n,this._counts.length-t],Ed(this._counts.slice(t)),!1)),o.splice.apply(o,bd([0,t],Ed(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(bd([],Ed(this._counts),!1))},r}();var EE=52,OP=2146435072,LP=1048575,vd=1023,Js=-vd+1,Qs=vd,Ki=Math.pow(2,-1022);function Zs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&OP)>>20;return n-vd}function el(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LP)*Math.pow(2,32);return o+n}function Yi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function TE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NP=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)}}(),Qr=function(r){NP(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var AE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ki)return this._minNormalLowerBoundaryIndex();var t=Zs(e),n=this._rightShift(el(e)-1,EE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Qr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qr("overflow: "+e+" is > maximum lower boundary: "+n);return Yi(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=Js>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Qs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var RE=function(){function r(e){this._scale=e,this._scaleFactor=Yi(Math.LOG2E,e),this._inverseFactor=Yi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ki)return this._minNormalLowerBoundaryIndex()-1;if(el(e)===0){var t=Zs(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 Qr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ki;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qr("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 Js<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Qs+1<<this._scale)-1},r}();var wE=-10,CE=20,DP=Array.from({length:31},function(r,e){return e>10?new RE(e-10):new AE(e-10)});function Ad(r){if(r>CE||r<wE)throw new Qr("expected scale >= "+wE+" && <= "+CE+", got: "+r);return DP[r+10]}var kP=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tl=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}(),UP=20,FP=160,Rd=2,xE=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=FP),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Td),u===void 0&&(u=new Td),d===void 0&&(d=Ad(UP)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Rd&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Rd),this._maxSize=Rd)}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,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);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=TE(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},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=Ad(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=tl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=tl.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 tl(0,-1);var o=t-n;return new tl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var wd=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Ht.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xE(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:mr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();he();var BP=ku("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function _E(r){return r.setValue(BP,!0)}he();function ME(){return function(r){F.error(zP(r))}}function zP(r){return typeof r=="string"?r:JSON.stringify(GP(r))}function GP(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 HP=ME();function rl(r){try{HP(r)}catch{}}var IE="1.30.1";var VP="process.runtime.name";var jP="service.name";var WP="telemetry.sdk.name",$P="telemetry.sdk.language",qP="telemetry.sdk.version";var PE=VP;var OE=jP;var Xi=WP,Ji=$P,Qi=qP;var KP="nodejs";var LE=KP;var _o,Pn=(_o={},_o[Xi]="opentelemetry",_o[PE]="node",_o[Ji]=LE,_o[Qi]=IE,_o);function Zi(r){r.unref()}var tO=9,rO=6,nO=Math.pow(10,rO),Dee=Math.pow(10,tO);function On(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*nO);return[t,n]}function Mo(r){return r[0]*1e6+r[1]/1e3}var ea;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ea||(ea={}));he();function NE(r,e){return new Promise(function(t){To.with(_E(To.active()),function(){r.export(e,function(n){t(n)})})})}var DE={_export:NE};var oO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nl=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=On(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Cd=function(){function r(){this.kind=Ht.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new nl(e)},r.prototype.merge=function(e,t){var n=Mo(t.sampleTime)>=Mo(e.sampleTime)?t:e;return new nl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Mo(t.sampleTime)>=Mo(e.sampleTime)?t:e;return new nl(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.GAUGE,dataPoints:n.map(function(i){var a=oO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var iO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Io=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 ol=function(){function r(e){this.monotonic=e,this.kind=Ht.SUM}return r.prototype.createAccumulation=function(e){return new Io(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Io(t.startTime,this.monotonic,o,t.reset):new Io(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 Io(t.startTime,this.monotonic,o,!0):new Io(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.SUM,dataPoints:n.map(function(i){var a=iO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ln=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)}}(),Vt=function(){function r(){}return r.Drop=function(){return HE},r.Sum=function(){return VE},r.LastValue=function(){return jE},r.Histogram=function(){return WE},r.ExponentialHistogram=function(){return aO},r.Default=function(){return sO},r}();var kE=function(r){Ln(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 yd,e}(Vt);var UE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ol(!0),e.NON_MONOTONIC_INSTANCE=new ol(!1),e}(Vt);var FE=function(r){Ln(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 Cd,e}(Vt);var BE=function(r){Ln(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 Xs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Vt);var il=function(r){Ln(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(l,c){return l-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 Xs(this._boundaries,this._recordMinMax)},e}(Vt);var zE=function(r){Ln(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 wd(this._maxSize,this._recordMinMax)},e}(Vt);var GE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return VE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return jE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new il(t.advice.explicitBucketBoundaries):WE}return F.warn("Unable to recognize instrument type: "+t.type),HE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Vt);var HE=new kE,VE=new UE,jE=new FE,WE=new BE,aO=new zE,sO=new GE;var $E=function(r){return Vt.Default()},qE=function(r){return xo.CUMULATIVE};var xd=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},_d=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},KE=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lO=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))},YE=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:$E,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:qE,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 xd(this,void 0,void 0,function(){var t,n,o,i,a,l;return _d(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(lO([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],KE(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=KE.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Sd(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Sd(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return xd(this,void 0,void 0,function(){return _d(this,function(t){switch(t.label){case 0:return this._shutdown?(F.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,Jr(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return xd(this,void 0,void 0,function(){return _d(this,function(t){switch(t.label){case 0:return this._shutdown?(F.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,Jr(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();he();var cO=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)}}(),al=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},sl=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},uO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dO=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))},Md=function(r){cO(e,r);function e(t){var n,o,i,a,l=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 l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return al(this,void 0,void 0,function(){var t;return sl(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Jr(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof fd?(F.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(rl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return al(this,void 0,void 0,function(){var o,i,a,l,c,s;return sl(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&&(s=F).error.apply(s,dO(["PeriodicExportingMetricReader: metrics collection errors"],uO(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 l=u.sent(),F.debug("Error while resolving async portion of resource: ",l),rl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,DE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ea.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),Zi(this._interval)},e.prototype.onForceFlush=function(){return al(this,void 0,void 0,function(){return sl(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 al(this,void 0,void 0,function(){return sl(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}(YE);he();he();function ll(){return"unknown_service:"+process.argv0}var Zr=function(){return Zr=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},Zr.apply(this,arguments)},pO=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},mO=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},gO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},cl=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 F.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[OE]=ll(),e[Ji]=Pn[Ji],e[Xi]=Pn[Xi],e[Qi]=Pn[Qi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.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 pO(this,void 0,void 0,function(){return mO(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=Zr(Zr({},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 l,c=gO(a,2),s=c[0],u=c[1];return Zr(Zr(Zr(Zr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var XE=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}();he();var Nn=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)}}(),ul=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=To.active()),typeof e!="number"){F.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===_t.INT&&!Number.isInteger(e)&&(F.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,On(Date.now()))},r}();var JE=function(r){Nn(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}(ul);var QE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){F.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ul);var ZE=function(r){Nn(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}(ul);var eb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){F.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ul);var dl=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 tb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);var rb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);var nb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);function ta(r){return r instanceof dl}var ob=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=gr(e,oe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new ZE(o,n)},r.prototype.createHistogram=function(e,t){var n=gr(e,oe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new eb(o,n)},r.prototype.createCounter=function(e,t){var n=gr(e,oe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new QE(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=gr(e,oe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new JE(o,n)},r.prototype.createObservableGauge=function(e,t){var n=gr(e,oe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new nb(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 pl=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=gr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var hO=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)}}(),ib=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},fO=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 ib(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 ib(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 Jt=function(r){hO(e,r);function e(){return r.call(this,Ks)||this}return e}(fO);var SO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ml=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Jt,this._cumulativeMemoStorage=new Jt,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Ks(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 l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.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=SO(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}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,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Jt,e},r}();var Id=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.")},ab=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gl=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,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===xo.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=yO(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Id(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}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 Jt,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Id(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.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 l=ab(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Id(e.keys()),l=a.next();!l.done;l=a.next()){var c=ab(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function yO(r){return Array.from(r.entries())}var EO=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)}}(),bO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sb=function(r){EO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new ml(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new gl(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Jt;Array.from(t.entries()).forEach(function(a){var l=bO(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),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}(pl);he();function Pd(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
14
14
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
15
15
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
16
16
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
17
17
  `),t}function TO(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function vO(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function AO(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function RO(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
18
18
  - OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
19
- - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Nd(r,e){return r.valueType!==e.valueType?TO(r,e):r.unit!==e.unit?vO(r,e):r.type!==e.type?AO(r,e):r.description!==e.description?RO(r,e):""}var Dd=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.")},cb=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Dd(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Dd(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(g){o={error:g}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Dd(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();EE(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),F.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
19
+ - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Od(r,e){return r.valueType!==e.valueType?TO(r,e):r.unit!==e.unit?vO(r,e):r.type!==e.type?AO(r,e):r.description!==e.description?RO(r,e):""}var Ld=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.")},lb=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Ld(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Ld(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Ld(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();yE(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),F.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
20
20
  `,`Details:
21
- `,Ld(s,e),`The longer description will be used.
22
- To resolve the conflict:`,Nd(s,e))),i=c):F.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
21
+ `,Pd(s,e),`The longer description will be used.
22
+ To resolve the conflict:`,Od(s,e))),i=c):F.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
23
23
  `,`Details:
24
- `,Ld(s,e),`To resolve the conflict:
25
- `,Nd(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var ub=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();he();he();var db=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Jt}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){F.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===_t.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var pb=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ra(e)){var o=this._buffer.get(e);if(o==null&&(o=new Jt,this._buffer.set(e,o)),typeof t!="number"){F.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===_t.INT&&!Number.isInteger(t)&&(F.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var kd=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ud=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},mb=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gb=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))},hb=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(ra));if(n.size===0){F.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(ra)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return kd(this,void 0,void 0,function(){var n,o,i,a;return Ud(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,mE(gb(gb([],mb(n),!1),mb(o),!1))];case 1:return i=l.sent(),a=i.filter(gE).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return kd(n,void 0,void 0,function(){var l,c;return Ud(this,function(s){switch(s.label){case 0:return l=new db(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return kd(n,void 0,void 0,function(){var l,c;return Ud(this,function(s){switch(s.label){case 0:return l=new pb,c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&hE(n.instruments,t)})},r}();var wO=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)}}(),fb=function(r){wO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new gl(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new hl(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ml);var Sb=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)}}(),Oo=function(){function r(){}return r.Noop=function(){return xO},r}();var CO=function(r){Sb(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Oo);var yb=function(r){Sb(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(Oo);var xO=new CO;var _O=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},MO=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},IO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Eb=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new cb,this.observableRegistry=new hb,this.meter=new ib(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,fb);return t.length===1?t[0]:new ub(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,lb);return t},r.prototype.collect=function(e,t,n){return _O(this,void 0,void 0,function(){var o,i,a;return MO(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(dE),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=yE(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=IO(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var g=d.createAggregator(e),m=u.selectCardinalityLimit(e.type),h=new t(e,g,Oo.Noop(),[u],m);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var PO=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.")},bb=function(){function r(e){this.resource=e,this.viewRegistry=new JE,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=pE(e),n=this.meterSharedStates.get(t);return n==null&&(n=new Eb(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=PO(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var fl=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Sl=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},OO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LO=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))},Tb=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return fl(this,void 0,void 0,function(){var t,n,o,i,a=this;return Sl(this,function(l){switch(l.label){case 0:return t=Ln(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return fl(a,void 0,void 0,function(){var s;return Sl(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,LO([],OO(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return fl(this,void 0,void 0,function(){return Sl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return fl(this,void 0,void 0,function(){return Sl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var vb=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ab=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Rb=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 NO(r,e){var t=e??ul.empty();return r?ul.default().merge(t):t}var Fd=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new bb(NO((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=Rb(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=Rb(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(g){o={error:g}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(F.warn("A shutdown MeterProvider cannot provide a Meter"),Vu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new Tb(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return vb(this,void 0,void 0,function(){return Ab(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return vb(this,void 0,void 0,function(){return Ab(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var DO=/[\^$\\.+?()[\]{}|]/g,yl=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(DO,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Lo=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var wb=function(){function r(e){var t;this._nameFilter=new yl((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Lo(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var Cb=function(){function r(e){this._nameFilter=new Lo(e?.name),this._versionFilter=new Lo(e?.version),this._schemaUrlFilter=new Lo(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function kO(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Bd=function(){function r(e){var t;if(kO(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||yl.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new yb(e.attributeKeys):this.attributesProcessor=Oo.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Vt.Default(),this.instrumentSelector=new wb({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Cb({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Sne=process.env.APP||"unknown";he();import{v4 as UO}from"uuid";function FO(){return new lE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Pn.DELTA})}var BO=[new Bd({instrumentName:"test_operation_duration_ms",instrumentType:oe.HISTOGRAM,aggregation:new al([100,500,1e3,5e3,1e4,2e4])})],El=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new sd({[Us]:e.serviceName,[oy]:t,[ay]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:UO()}),o=FO(),i=new Pd({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Fd({resource:n,readers:[i],views:BO}),Ls.setGlobalMeterProvider(this.provider),this.meter=Ls.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Is(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=Is(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var Mt=new Ms;function xb(r){r.disabled||(Mt=new El(r))}import Ib from"fontoxpath";import{DOMParser as zO,XMLSerializer as GO}from"slimdom";function zd(r){return r.toLowerCase().endsWith("webview")}function HO(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 VO=new Set(["index","package","a11y-important"]),jO=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),WO=new Set(["live-region","drawing-order"]),$O=new Set(["displayed","enabled"]);function qO(r,e){let t={};for(let[n,o]of Object.entries(e))VO.has(n)||n==="class"&&r===o||jO.has(n)&&o==="false"||n==="text"&&o===""||$O.has(n)&&o==="true"||WO.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function _b(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:l}=r,c=a.value++;t.setAttribute("id",String(c));let s={};for(let p of e.attributes){let g=p.name,m=p.value;m!=null&&(s[g]=String(m))}let u=qO(e.tagName,s);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),zd(e.tagName)&&l?.disallowAccessibilityBridgeForWebviews){for(;t.firstChild;)t.removeChild(t.firstChild);let p=l.injectedWebviewContent??"";p.trim().length>0&&t.appendChild(n.createTextNode(p));return}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p,h=n.createElement(HO(m.tagName));_b(r,m,h),t.appendChild(h)}}}function KO(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},l=o.documentElement;_b(a,e,l);let c=new GO().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function Mb(r,e){let t=new zO,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:l,xml:c}=KO(t,i,o,e);return{xml:c,originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function YO(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(l=>l.tagName===n);for(let l=0;l<a.length;l++)if(a[l]===t){i=l+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function bl(r,e){let t=r.idToElement.get(e);if(t)return YO(t)}function Gd(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 Tl(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 Hd(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Ob({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=Tl(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=bl(t.graph,r.id)??"",a=Gd(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=Hd(l,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?l?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:g,requirements:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=bl(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Hd(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return zd(n.tagName)?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var Pb=(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,l]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==l)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${l}, got ${c}`)}if(i&&t){let a=Tl(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,s)=>c===t[s]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Lb(r){let{target:e,domState:t,stateManager:n,logger:o,signal:i}=r,{graph:a}=t,{document:l}=a;if(e.type==="WEBVIEW"){let m=await n.getActiveWebview();if(!m||!m.browserController)throw new Error("No browser controller is attached to the requested webview");if(!e.browserCache)throw new Error("No browser target available on cache");let h=await m.browserController.browser.resolveTarget(null,e.browserCache,{logger:o,signal:i});return{resolvedTarget:{...e,controller:m.browserController,resolution:h}}}let c=Ib.evaluateXPathToFirstNode(e.xPath,l,null,null);if(!c)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements)for(let m of e.requiredRelatedElements){let h=Ib.evaluateXPathToFirstNode(m.xPath,l);if(!h)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);Pb(h,m.requirements)}let s=Tl(c);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Pb(c,e.requirements,e.bounds);let u;for(let[m,h]of a.idToElement.entries())if(h===c){u=m;break}let d=e.elementOnlySerializedXml,p=e.xPath;return u!==void 0&&(d=Gd(a,u)??d,p=bl(a,u)??p),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:d,xPath:p}}}function Vd(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Qa(e)&&(e[t]={...e[t],[n]:o})}function Nb(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var No=class{driver;stateManager;generator;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(d){this.throwIfAborted(),this.logger.warn({err:d},"Failed to refresh webviews, continuing...")}let s=await this.stateManager.getDomState(),u=await this.stateManager.getCurrentScreenshot();return{emulatorState:s,screenshot:u}}),o=Date.now(),i;try{i=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ce(this.logger),abortSignal:this.aborter.controller?.signal})}catch(s){throw this.throwIfAborted(),this.logger.error({err:s},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${s instanceof Error?s.message:s}`)}if(i.id===-1)throw t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),error:`No matching element found: ${i.thoughts}`}),new Error(`ActionFailureError: No matching element found: ${i.thoughts}`);let a=Ob({aiResponse:i,description:e,emulatorState:n.emulatorState});if(a.type==="NATIVE")return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:a.elementOnlySerializedXml,id:i.id,thoughts:i.thoughts}}),{resolvedTarget:a,thoughts:i.thoughts};let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let c=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:c.target.nodeOnlySerializedHtml??"Unknown HTML element in webview",id:c.target.id,thoughts:c.thoughts}}),{resolvedTarget:{...a,controller:l.browserController,resolution:c.resolution,browserCache:c.target},thoughts:c.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:l,tracer:c}=e,s=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=JO(s),g;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),l&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({cache:p,description:n},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return g=h.thoughts,Vd({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget}),{result:await t(h.resolvedTarget),thoughts:g}}let m;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:c,reason:"Waiting for stability before cache resolution"}),m=await c.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(E){this.logger.warn({err:E},"Failed to refresh webviews, continuing...")}return await this.stateManager.getDomState()});let h=await c.startAsyncSpan("RESOLVE_TARGET_CACHE",async E=>{let{resolvedTarget:b}=await Lb({target:p,domState:m,stateManager:this.stateManager,logger:this.logger}),v=Nb(b),w=XO(p,v);return this.logger.info({cacheDiffs:w},"Successfully resolved and updated target"),Vd({command:o,cacheKey:i,targetName:a,updatedCache:v}),E.result={serializedElement:b.type==="WEBVIEW"?b.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":b.elementOnlySerializedXml},b});return p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),{result:await t(h),thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h,domState:m?.graph.originalXml},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var vl=class extends No{async tapOnAbsoluteCoordinates(e){return e.longPress?await this.driver.execute("mobile: longClickGesture",{x:e.x,y:e.y,duration:e.longPressDurationMs??2e3}):await this.driver.tap({x:e.x,y:e.y})}async tapOnTarget({target:e,command:t}){if("type"in e&&e.type==="NATIVE"){let[n,o,i,a]=e.bounds,l=n+(i-n)/2,c=o+(a-o)/2;await this.tapOnAbsoluteCoordinates({x:l,y:c,longPress:t.longPress,longPressDurationMs:t.longPressDurationMs})}else{let{controller:n}=e;await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let o=Math.random().toString(36).substring(4),i=Db.join(ZO(),"momentic","downloads"),a=Db.join(i,this.orgId,o);return QO(a,{recursive:!0}),a}},{delayMs:t.longPressDurationMs})}}async executeTap({command:e,tracer:t}){if(e.target.type==="coordinates"){let o=await this.driver.getWindowSize(),i=e.target.xPercent*o.width,a=e.target.yPercent*o.height;return await this.tapOnAbsoluteCoordinates({x:i,y:a,longPress:e.longPress,longPressDurationMs:e.longPressDurationMs}),{success:!0,message:`Tapped at ${i}, ${a}`}}let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:o=>this.tapOnTarget({target:o,command:e}),description:e.target.description});return{success:!0,message:n}}};import{execSync as Ev}from"child_process";import{_android as AD,chromium as RD}from"playwright";var kb={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/constants.ts
24
+ `,Pd(s,e),`To resolve the conflict:
25
+ `,Od(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var cb=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();he();he();var ub=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Jt}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){F.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===_t.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var db=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ta(e)){var o=this._buffer.get(e);if(o==null&&(o=new Jt,this._buffer.set(e,o)),typeof t!="number"){F.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===_t.INT&&!Number.isInteger(t)&&(F.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var Nd=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Dd=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},pb=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mb=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))},gb=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(ta));if(n.size===0){F.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(ta)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Nd(this,void 0,void 0,function(){var n,o,i,a;return Dd(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,pE(mb(mb([],pb(n),!1),pb(o),!1))];case 1:return i=l.sent(),a=i.filter(mE).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return Nd(n,void 0,void 0,function(){var l,c;return Dd(this,function(s){switch(s.label){case 0:return l=new ub(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return Nd(n,void 0,void 0,function(){var l,c;return Dd(this,function(s){switch(s.label){case 0:return l=new db,c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&gE(n.instruments,t)})},r}();var wO=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)}}(),hb=function(r){wO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new ml(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new gl(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(pl);var fb=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)}}(),Po=function(){function r(){}return r.Noop=function(){return xO},r}();var CO=function(r){fb(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Po);var Sb=function(r){fb(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(Po);var xO=new CO;var _O=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},MO=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},IO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yb=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new lb,this.observableRegistry=new gb,this.meter=new ob(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,hb);return t.length===1?t[0]:new cb(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,sb);return t},r.prototype.collect=function(e,t,n){return _O(this,void 0,void 0,function(){var o,i,a;return MO(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(uE),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=SE(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=IO(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,Po.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var PO=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.")},Eb=function(){function r(e){this.resource=e,this.viewRegistry=new XE,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=dE(e),n=this.meterSharedStates.get(t);return n==null&&(n=new yb(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=PO(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var hl=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},fl=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},OO=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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LO=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))},bb=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return hl(this,void 0,void 0,function(){var t,n,o,i,a=this;return fl(this,function(l){switch(l.label){case 0:return t=On(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return hl(a,void 0,void 0,function(){var s;return fl(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,LO([],OO(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return hl(this,void 0,void 0,function(){return fl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return hl(this,void 0,void 0,function(){return fl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var Tb=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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},vb=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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Ab=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 NO(r,e){var t=e??cl.empty();return r?cl.default().merge(t):t}var kd=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new Eb(NO((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=Ab(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=Ab(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(F.warn("A shutdown MeterProvider cannot provide a Meter"),Gu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new bb(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return Tb(this,void 0,void 0,function(){return vb(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return Tb(this,void 0,void 0,function(){return vb(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var DO=/[\^$\\.+?()[\]{}|]/g,Sl=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(DO,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Oo=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var Rb=function(){function r(e){var t;this._nameFilter=new Sl((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Oo(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var wb=function(){function r(e){this._nameFilter=new Oo(e?.name),this._versionFilter=new Oo(e?.version),this._schemaUrlFilter=new Oo(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function kO(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Ud=function(){function r(e){var t;if(kO(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Sl.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new Sb(e.attributeKeys):this.attributesProcessor=Po.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Vt.Default(),this.instrumentSelector=new Rb({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new wb({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var hne=process.env.APP||"unknown";he();import{v4 as UO}from"uuid";function FO(){return new sE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:In.DELTA})}var BO=[new Ud({instrumentName:"test_operation_duration_ms",instrumentType:oe.HISTOGRAM,aggregation:new il([100,500,1e3,5e3,1e4,2e4])})],yl=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new id({[ks]:e.serviceName,[ny]:t,[iy]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:UO()}),o=FO(),i=new Md({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new kd({resource:n,readers:[i],views:BO}),Os.setGlobalMeterProvider(this.provider),this.meter=Os.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Ms(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=Ms(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var Mt=new _s;function Cb(r){r.disabled||(Mt=new yl(r))}import Mb from"fontoxpath";import{DOMParser as zO,XMLSerializer as GO}from"slimdom";function Fd(r){return r.toLowerCase().endsWith("webview")}function HO(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 VO=new Set(["index","package","a11y-important"]),jO=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),WO=new Set(["live-region","drawing-order"]),$O=new Set(["displayed","enabled"]);function qO(r,e){let t={};for(let[n,o]of Object.entries(e))VO.has(n)||n==="class"&&r===o||jO.has(n)&&o==="false"||n==="text"&&o===""||$O.has(n)&&o==="true"||WO.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function xb(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:l}=r,c=a.value++;t.setAttribute("id",String(c));let s={};for(let p of e.attributes){let m=p.name,g=p.value;g!=null&&(s[m]=String(g))}let u=qO(e.tagName,s);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),Fd(e.tagName)&&l?.disallowAccessibilityBridgeForWebviews){for(;t.firstChild;)t.removeChild(t.firstChild);let p=l.injectedWebviewContent??"";p.trim().length>0&&t.appendChild(n.createTextNode(p));return}let d=Array.from(e.childNodes??[]);for(let p of d){let m=p.nodeType;if(m===3){let g=p.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(m===1){let g=p,h=n.createElement(HO(g.tagName));xb(r,g,h),t.appendChild(h)}}}function KO(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},l=o.documentElement;xb(a,e,l);let c=new GO().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function _b(r,e){let t=new zO,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:l,xml:c}=KO(t,i,o,e);return{xml:c,originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function YO(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(l=>l.tagName===n);for(let l=0;l<a.length;l++)if(a[l]===t){i=l+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function El(r,e){let t=r.idToElement.get(e);if(t)return YO(t)}function Bd(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 bl(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 zd(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Pb({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=bl(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=El(t.graph,r.id)??"",a=Bd(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=zd(l,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?l?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:m,requirements:g})=>{let h=t.graph.idToElement.get(m);if(!h)return;let f=El(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:zd(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return Fd(n.tagName)?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var Ib=(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,l]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==l)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${l}, got ${c}`)}if(i&&t){let a=bl(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,s)=>c===t[s]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Ob(r){let{target:e,domState:t,stateManager:n,logger:o,signal:i}=r,{graph:a}=t,{document:l}=a;if(e.type==="WEBVIEW"){let g=await n.getActiveWebview();if(!g||!g.browserController)throw new Error("No browser controller is attached to the requested webview");if(!e.browserCache)throw new Error("No browser target available on cache");let h=await g.browserController.browser.resolveTarget(null,e.browserCache,{logger:o,signal:i});return{resolvedTarget:{...e,controller:g.browserController,resolution:h}}}let c=Mb.evaluateXPathToFirstNode(e.xPath,l,null,null);if(!c)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements)for(let g of e.requiredRelatedElements){let h=Mb.evaluateXPathToFirstNode(g.xPath,l);if(!h)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);Ib(h,g.requirements)}let s=bl(c);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Ib(c,e.requirements,e.bounds);let u;for(let[g,h]of a.idToElement.entries())if(h===c){u=g;break}let d=e.elementOnlySerializedXml,p=e.xPath;return u!==void 0&&(d=Bd(a,u)??d,p=El(a,u)??p),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:d,xPath:p}}}function Gd(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Ja(e)&&(e[t]={...e[t],[n]:o},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Lb(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Lo=class{driver;stateManager;generator;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(d){this.throwIfAborted(),this.logger.warn({err:d},"Failed to refresh webviews, continuing...")}let s=await this.stateManager.getDomState(),u=await this.stateManager.getCurrentScreenshot();return{emulatorState:s,screenshot:u}}),o=Date.now(),i;try{i=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:pe(this.logger),abortSignal:this.aborter.controller?.signal})}catch(s){throw this.throwIfAborted(),this.logger.error({err:s},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${s instanceof Error?s.message:s}`)}if(i.id===-1)throw t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),error:`No matching element found: ${i.thoughts}`}),new Error(`ActionFailureError: No matching element found: ${i.thoughts}`);let a=Pb({aiResponse:i,description:e,emulatorState:n.emulatorState});if(a.type==="NATIVE")return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:a.elementOnlySerializedXml,id:i.id,thoughts:i.thoughts}}),{resolvedTarget:a,thoughts:i.thoughts};let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let c=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:c.target.nodeOnlySerializedHtml??"Unknown HTML element in webview",id:c.target.id,thoughts:c.thoughts}}),{resolvedTarget:{...a,controller:l.browserController,resolution:c.resolution,browserCache:c.target},thoughts:c.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:l,tracer:c}=e,s=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=JO(s),m;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),l&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({cache:p,description:n},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return m=h.thoughts,Gd({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:await t(h.resolvedTarget),thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:c,reason:"Waiting for stability before cache resolution"}),g=await c.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(E){this.logger.warn({err:E},"Failed to refresh webviews, continuing...")}return await this.stateManager.getDomState()});let h=await c.startAsyncSpan("RESOLVE_TARGET_CACHE",async E=>{let{resolvedTarget:b}=await Ob({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),v=Lb(b),A=XO(p,v);return this.logger.info({cacheDiffs:A},"Successfully resolved and updated target"),Gd({command:o,cacheKey:i,targetName:a,updatedCache:v,updatedWithAI:!1}),E.result={serializedElement:b.type==="WEBVIEW"?b.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":b.elementOnlySerializedXml},b}),f=await t(h);return p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h,domState:g?.graph.originalXml},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Tl=class extends Lo{async tapOnAbsoluteCoordinates(e){return e.longPress?await this.driver.execute("mobile: longClickGesture",{x:e.x,y:e.y,duration:e.longPressDurationMs??2e3}):await this.driver.tap({x:e.x,y:e.y})}async tapOnTarget({target:e,command:t}){if("type"in e&&e.type==="NATIVE"){let[n,o,i,a]=e.bounds,l=n+(i-n)/2,c=o+(a-o)/2;await this.tapOnAbsoluteCoordinates({x:l,y:c,longPress:t.longPress,longPressDurationMs:t.longPressDurationMs})}else{let{controller:n}=e;await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let o=Math.random().toString(36).substring(4),i=Nb.join(ZO(),"momentic","downloads"),a=Nb.join(i,this.orgId,o);return QO(a,{recursive:!0}),a}},{delayMs:t.longPressDurationMs})}}async executeTap({command:e,tracer:t}){if(e.target.type==="coordinates"){let o=await this.driver.getWindowSize(),i=e.target.xPercent*o.width,a=e.target.yPercent*o.height;return await this.tapOnAbsoluteCoordinates({x:i,y:a,longPress:e.longPress,longPressDurationMs:e.longPressDurationMs}),{success:!0,message:`Tapped at ${i}, ${a}`}}let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:o=>this.tapOnTarget({target:o,command:e}),description:e.target.description});return{success:!0,message:n}}};import{execSync as yv}from"child_process";import{_android as bD,chromium as TD}from"playwright";var Db={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/constants.ts
26
26
  var momenticConstants = {
27
27
  bannedClassSubstrings: [
28
28
  "relative",
@@ -3936,45 +3936,45 @@ function registerAllMomenticListeners() {
3936
3936
 
3937
3937
  // src/html/index.ts
3938
3938
  registerAllMomenticListeners();
3939
- `};var jt={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var Ub="BoundingBoxMovedError",Fb="ZeroOpacityError",Al="visual_actions",_r="data-momentic-id";function Bb(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
3939
+ `};var jt={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var kb="BoundingBoxMovedError",Ub="ZeroOpacityError",vl="visual_actions",_r="data-momentic-id";function Fb(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
3940
3940
  `,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
3941
3941
  `;)c++,l--;return l>n&&r[l]===`
3942
- `&&(i=l),r.slice(o,i)}function Qt(r){let e=typeof r=="string"?r:r.toString();return`[${_r}="${e}"]`}import{execSync as ON}from"child_process";import{randomUUID as fp}from"crypto";import{diff as Sp}from"deep-object-diff";import{existsSync as Bn,mkdirSync as LN,readFileSync as NN,readdirSync as DN,rmSync as kN,statSync as jT,writeFileSync as UN}from"fs";import{Jimp as WT}from"jimp";import FN from"js-beautify";import{cloneDeep as Uo}from"lodash-es";import BN from"mime";import{homedir as Fo,hostname as zN,platform as Nl}from"os";import{basename as GN,extname as HN,join as yr,resolve as VN}from"path";import{chromium as qT,devices as jN}from"playwright";import{addExtra as WN}from"playwright-extra";import $N from"puppeteer-extra-plugin-recaptcha";import{v4 as qN}from"uuid";import{rmSync as sT}from"fs";import{basename as _L,join as ML}from"path";import{errors as IL}from"playwright-core";var zb=new Set(["about:blank","chrome-error://chromewebdata/"]);var jd=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Wd=1e4,oa=500;import{mkdirSync as tL,rmSync as Gb,statSync as rL}from"fs";import*as Yd from"node:fs";import nL from"nodejs-file-downloader";import{tmpdir as oL}from"os";import en,{basename as iL,dirname as aL}from"path";var Xd="file://",Kd=en.join(oL(),"momentic","downloads"),qd=1e4,sL=50*1024*1024;async function Hb(r){let{uri:e}=r;if(e.startsWith(Xd))return cL(r);if(e.startsWith("http"))return dL(r);if(Rh)return uL(r);throw new R("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function lL(r,e){let t=en.join(Kd,r,e.slice(Xd.length)),n=en.join(Kd,r),o=t.startsWith(n);if(!Yd.existsSync(t)||!o)throw new R("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function cL({uri:r,orgId:e}){let t=lL(e,r);return{filePath:t,cleanup:()=>{Gb(aL(t),{recursive:!0,force:!0})}}}async function uL({uri:r}){let e=en.resolve(r);if(!Yd.existsSync(e))throw new R("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function dL({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=iL(n.href),i=Qd(o),a=en.extname(i);if(yh.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Jd(t),c=new nL({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:qd}),{downloadStatus:s,filePath:u}=await B(c.download(),{milliseconds:qd,message:`Download timed out after ${qd}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=rL(u).size;if(p>sL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let g;return{filePath:u,cleanup:()=>{clearTimeout(g),g=setTimeout(()=>Gb(l,{recursive:!0,force:!0}),10*60*1e3)}}}function Vb(r,e){return`${Xd}${r}/${e}`}function Jd(r){let e=Math.random().toString(36).substring(4),t=en.join(Kd,r,e);return tL(t,{recursive:!0}),t}function Qd(r){let e=en.extname(r),t=en.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Mr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var Rl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function jb(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await B(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Wb(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await B(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function $b(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await B(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function qb(r,e,t,n,o){try{await pL(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function pL(r,e,t,n){let o=n.text();o.length>oa&&(o=o.slice(0,oa)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>oa?i.push(c.slice(0,oa)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Zd(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Zd(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>Wd&&(i[t]=i[t].slice(Math.floor(Wd/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Wt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Nu({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import mL from"truncate-json";var gL="[redacted due to size]",Kb=5e3,hL=5e3;async function Xb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function ep(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await Qb(e),url:n.toString(),method:e.method(),queryString:o,postData:await SL(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:Zb(t).timings}}async function Jb(r,e,t){await t.finished();let n={};try{n=await TL(t)}catch{}let o={...await Qb(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=Zb(a);r.time=c,r.timings=l}function ia(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Yb(r){try{return new Date(r).toISOString()}catch{return}}function fL(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=hr(i),e.value=hr(a);continue}i==="Domain"&&(e.domain=hr(a)),i==="Expires"&&(e.expires=Yb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Yb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=hr(a)),i==="Secure"&&(e.secure=!0)}return e}async function Qb(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(fL)??[];return{headers:Object.entries(e).map(([n,o])=>({name:hr(n),value:hr(o)})),cookies:t}}async function SL(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:hr(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:hr(i),value:a?hr(a):void 0})}return n}var yL=["text"],EL=["json","xml","html","javascript"];function bL(r){let[e,t]=r.split("/");return e?yL.includes(e)?!0:t?!!EL.some(n=>t?.includes(n)):!1:!1}async function TL(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&bL(t)&&(n.text=hr(await r.text())),n}function hr(r){try{let e=JSON.parse(r),{jsonString:t}=mL(r,hL);return t}catch{return r.length>Kb?r.slice(0,Kb)+gL:r}}function kn(r){return r<0?0:r}function Zb(r){return{timings:{blocked:kn(r.domainLookupStart),dns:kn(r.domainLookupEnd-r.domainLookupStart),connect:kn(r.connectEnd-r.connectStart),send:kn(r.responseStart-r.requestStart),wait:0,receive:kn(r.responseEnd-r.responseStart),ssl:kn(r.connectEnd-r.secureConnectionStart)},total:kn(r.responseEnd)}}function eT(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function je({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await B(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function tp(){return window.lastCursorPos}import{errors as vL}from"playwright-core";async function Un({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof vL.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await AL(c,i.locator,n,t);else throw c}throw l instanceof R?l:new R("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function AL(r,e,t,n){return r.message.includes("attempt #")?RL(r,e,t,n):wL(r)}async function RL(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3943
- `,";").replace(/\s+/g," ");let a="",l=await Mr(e,n);if(l&&(a=`Target element HTML: ${St(l,100,!0)}`),i.includes("element is not enabled"))return new R("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Qt(s)),d=await Mr(u,n);d&&(c=`Covering element HTML: ${St(d,100,!0)}`)}return new R("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
3944
- ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new R("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new R("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function wL(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new R("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function tT(r){try{return await CL(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function CL({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await Mr(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},m=s._MOMENTIC_FEATURE_FLAGS?.[Al],h=c.getAttribute(_r),f=!m&&h?Qt(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:g,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var nT=["date","datetime-local","month","time","week"],rT={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function oT(r){try{await B(xL(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function xL({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await je({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!rT[i])return;rT[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as wt}from"zod";var iT=wt.object({doubleClick:wt.boolean().optional(),rightClick:wt.boolean().optional(),force:wt.boolean().optional(),waitForDownload:wt.boolean().optional(),delayMs:wt.number().optional(),downloadTimeoutMs:wt.number().optional(),relativePosition:wt.object({x:wt.number(),y:wt.number()}).optional()}),$ie=wt.object({repeat:wt.number().optional(),convertMeta:wt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:wt.number().optional()});async function wl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await rp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let g=window.getComputedStyle(d,null).getPropertyValue("display");if(g==="none"||g==="contents")return!1;let m=d.getBoundingClientRect();return!(!m.height||!m.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await B(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function rp(r,e=1e3){let t=await r.state.getRoot();await je({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function np(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Un({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>lT({...r,targetingResult:t,useVisualClick:e})})}async function PL(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await OL(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function OL(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),lT({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function LL(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await Cn({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(m){throw new R("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${m.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await kL({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),g=iT.safeParse(i);t.info({frameCoordinates:c,position:o,options:g.success?g.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function NL(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await tT({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(FL(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),PL(s,{...r,targetingResult:{...i,locator:i}})}}async function lT(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof IL.TimeoutError?new R("ActionFailureError",`Download did not complete in ${c}ms`):new R("ActionFailureError",`Download failed: ${s.message}`)}})());try{await wl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await LL(r):await NL(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new R("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await B(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await UL(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function DL(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new R("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function kL({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await DL(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function UL(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Qd(r.suggestedFilename()),i=e();await r.saveAs(ML(i,o)),sT(n,{force:!0}),setTimeout(()=>{sT(i,{recursive:!0,force:!0})},5*60*1e3);let a=Vb(_L(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function FL(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as BL}from"os";var zL={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function GL(){let r=BL();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function cT(r){return JSON.stringify(r.split("+").sort())}function Cl(r){let e=GL(),t=cT(r);for(let n of Object.values(zL))if(Object.values(n).some(o=>cT(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function op({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await je({root:r,fn:([d,p,g,m])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(p??window.innerHeight)*m),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Br,p=await je({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[g,m,h]=await je({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let E=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,v,w]=await B(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let x=T.getBoundingClientRect();return[T.scrollTop,x.x,x.y]}),{milliseconds:1e3});if(E===p&&b===g&&v===m&&w===h)break;p=E,g=b,m=v,h=w,await $(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function ip(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await $(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as XL}from"crypto";import{cloneDeep as sp}from"lodash-es";function tn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as HL}from"crypto";var VL="v1";function xl(r,e){if(r.tagName.toLowerCase()==="svg"&&!WL(r))try{let t=uT(r,e),n=jL(JSON.stringify(t));return{version:VL,json:t,hash:n}}catch{return}}function jL(r){return HL("md5").update(r).digest("hex")}function uT(r,e){let t=r.tagName.toLowerCase(),n=$L(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=uT(a,e);l&&o.children.push(l)}}return o}function WL(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function $L(r){let e={},t=r.attributes;for(let n of Object.keys(t))jt.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Fn={r:147,g:196,b:125,a:.55},pT={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Fn,paddingColor:Fn,borderColor:Fn,marginColor:Fn,eventTargetColor:Fn,shapeColor:Fn,shapeMarginColor:Fn,showInfo:!0,showAccessibilityInfo:!0};function mT({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=qL({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function qL({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((N,k)=>{u[N]=k});let d=s.styles,p=s.bounds??[],g=c.nodes,m=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],b=g.nodeName??[],v=g.nodeType??[],w=g.pseudoType??{index:[],value:[]},T=g.inputChecked??{index:[]},x=e[c.frameId];for(let N=0;N<h.length;N++){let k=h[N],q=v[N],ke=f[N]??[],te=E[N]!==void 0&&E[N]>=0?E[N]:void 0,ie=te!==void 0?h[te]:void 0,ut=ie!==void 0?a[ie]:void 0,M=w.index.indexOf(N),V=M!==-1?e[w.value[M]]:void 0,re=u[N],Ce;re?Ce=p[re]??[]:Ce=[];let Me=b[N]!==void 0?e[b[N]]?.toLowerCase():void 0;if(!Me){l.warn({backendNodeId:k,frameId:x,frameIndex:o,nodeBounds:Ce},"DOM node has no tag name");continue}let Ae={backendNodeId:k,psuedoType:V,nodeType:q,frameIndex:o,parentFrameId:x,ownedFrameId:void 0,bounds:{x:Ce[0]??null,y:Ce[1]??null,width:Ce[2]??null,height:Ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:ie??null,tagName:Me,parent:ut??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ut&&ut.childrenBackendIds.push(k);let xt=m.index.indexOf(N);if(xt!==-1){let Re=m.value[xt];i[Re]=Ae;let We=r[Re]?.frameId;Ae.ownedFrameId=We!==void 0?e[We]:void 0}for(let Re of Object.keys(Ae.bounds)){let We=Re;Ae.bounds[We]!==null&&(Ae.bounds[We]/=n)}let dt=re!==void 0?d[re]??[]:[];for(let Re=0;Re<dt.length&&!(Re>=t.length);Re++){let We=dt[Re];if(We===void 0||isNaN(We))continue;let an=e[We];if(an===void 0)continue;let vr=t[Re];Ae.computedStyles[vr]=an}for(let Re=0;Re<ke.length;Re+=2){let We=ke[Re],an=ke[Re+1];if(!We||!an)continue;let vr=e[We],Zo=e[an];!vr||!Zo||(Ae.attributes[vr]=Zo)}T.index.includes(N)&&(Ae.attributes.checked="true"),a[Ae.backendNodeId]=Ae}return a[h[0]]}function ap(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${ap(t,e)}${a}`}return r.mPathSelector=n,n}function dT(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var KL=["html","#document","#document-fragment"];function gT({node:r,domGraph:e}){let t=[],n=r,o=dT(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=dT(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,KL.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function hT(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function fT(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=tn(o,_r);if(!i)throw new Error(`Could not find attribute ${_r} for object ${e}`);return i}function ST(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=YL({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function YL(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let l=xl(a,t);l&&!n[l.hash]&&o.push(l)}for(let l of a.childrenBackendIds){let c=t.backendIdToNode[l];c&&i.push(c)}}return o}var JL=["focusable","keyshortcuts","controls","live","relevant","orientation"],QL=["selected","readonly","modal","required","invalid"],ZL=["id","name","role","content"],yT=["absolute","fixed","sticky"],eN=["i"],tN=["path"],rN=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],TT=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],vT=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],nN=["menulistpopup","statictext","inlinetextbox"],oN=80,ET=100,AT=50,up=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],iN=["cite"],aN={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},sN={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},bT={indentLevel:0},lp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<AT?t:""),this.role=this.role||(e.domNode.attributes.role??""),dN(this.properties,e.domNode,e.importantProperties)}mN(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&tN.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>vT.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>_T(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>MT(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&eN.includes(this.domNode.tagName)||rN.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||jt.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>xT(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=bT){let t=Object.assign({},bT,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=sp(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===g&&(g="")}let f=up.includes(this.role)||iN.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
3945
- `;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let b=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==p&&!(aN[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),g&&(E+=` name=${JSON.stringify(g)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${jt.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let T=this.domNode.bounds,x=Math.round(T.x??0),N=Math.round(T.y??0),k=Math.round((T.x??0)+(T.width??0)),q=Math.round((T.y??0)+(T.height??0));E+=` bounds=[${x} ${N} ${k} ${q}]`}let v=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([T,x])=>{if(!JL.includes(T)){{if(QL.includes(T)&&(!x||x==="false"))return;if(T==="value"&&b&&(s.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${x}`=="1")return;if(T==="url"&&s.src&&p==="img")return;if(T==="url"&&s.href&&p==="a")return;if(T==="editable"&&x==="plaintext")return;if(T==="type"&&x===p)return;if(c&&!sN[T])return}typeof x=="string"?E+=` ${T}="${St(x,ET,!0)}"`:typeof x=="boolean"?x?E+=` ${T}`:E+=` ${T}={false}`:typeof x<"u"&&(E+=` ${T}={${St(JSON.stringify(x),ET,!0)}}`)}})}if(p==="::before"||p==="::after"){let T="";for(let x of this.children)T+=x.serialize({...e,indentLevel:n,neighbors:0});return T}let w=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||w)E+=` />
3946
- `;else{let T="";for(let N of this.children)T+=N.serialize({...e,indentLevel:n+2,neighbors:0});let x=T.trim();x.length<=oN&&!x.includes(`
3942
+ `&&(i=l),r.slice(o,i)}function Qt(r){let e=typeof r=="string"?r:r.toString();return`[${_r}="${e}"]`}import{execSync as PN}from"child_process";import{randomUUID as hp}from"crypto";import{diff as fp}from"deep-object-diff";import{existsSync as Fn,mkdirSync as ON,readFileSync as LN,readdirSync as NN,rmSync as DN,statSync as HT,writeFileSync as kN}from"fs";import{Jimp as VT}from"jimp";import UN from"js-beautify";import{cloneDeep as ko}from"lodash-es";import FN from"mime";import{homedir as Uo,platform as Ol}from"os";import{basename as BN,extname as zN,join as yr,resolve as GN}from"path";import{chromium as WT,devices as HN}from"playwright";import{addExtra as VN}from"playwright-extra";import jN from"puppeteer-extra-plugin-recaptcha";import{v4 as WN}from"uuid";import{rmSync as aT}from"fs";import{basename as _L,join as ML}from"path";import{errors as IL}from"playwright-core";var Bb=new Set(["about:blank","chrome-error://chromewebdata/"]);var Hd=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Vd=1e4,na=500;import{mkdirSync as tL,rmSync as zb,statSync as rL}from"fs";import*as qd from"node:fs";import nL from"nodejs-file-downloader";import{tmpdir as oL}from"os";import en,{basename as iL,dirname as aL}from"path";var Kd="file://",$d=en.join(oL(),"momentic","downloads"),Wd=1e4,sL=50*1024*1024;async function Gb(r){let{uri:e}=r;if(e.startsWith(Kd))return cL(r);if(e.startsWith("http"))return dL(r);if(Ah)return uL(r);throw new w("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function lL(r,e){let t=en.join($d,r,e.slice(Kd.length)),n=en.join($d,r),o=t.startsWith(n);if(!qd.existsSync(t)||!o)throw new w("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function cL({uri:r,orgId:e}){let t=lL(e,r);return{filePath:t,cleanup:()=>{zb(aL(t),{recursive:!0,force:!0})}}}async function uL({uri:r}){let e=en.resolve(r);if(!qd.existsSync(e))throw new w("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function dL({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=iL(n.href),i=Xd(o),a=en.extname(i);if(Sh.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Yd(t),c=new nL({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Wd}),{downloadStatus:s,filePath:u}=await B(c.download(),{milliseconds:Wd,message:`Download timed out after ${Wd}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=rL(u).size;if(p>sL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>zb(l,{recursive:!0,force:!0}),10*60*1e3)}}}function Hb(r,e){return`${Kd}${r}/${e}`}function Yd(r){let e=Math.random().toString(36).substring(4),t=en.join($d,r,e);return tL(t,{recursive:!0}),t}function Xd(r){let e=en.extname(r),t=en.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Mr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var Al=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function Vb(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await B(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function jb(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await B(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Wb(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await B(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function $b(r,e,t,n,o){try{await pL(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function pL(r,e,t,n){let o=n.text();o.length>na&&(o=o.slice(0,na)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>na?i.push(c.slice(0,na)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Jd(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Jd(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>Vd&&(i[t]=i[t].slice(Math.floor(Vd/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Wt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Ou({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import mL from"truncate-json";var gL="[redacted due to size]",qb=5e3,hL=5e3;async function Yb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function Qd(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await Jb(e),url:n.toString(),method:e.method(),queryString:o,postData:await SL(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:Qb(t).timings}}async function Xb(r,e,t){await t.finished();let n={};try{n=await TL(t)}catch{}let o={...await Jb(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=Qb(a);r.time=c,r.timings=l}function oa(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Kb(r){try{return new Date(r).toISOString()}catch{return}}function fL(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=hr(i),e.value=hr(a);continue}i==="Domain"&&(e.domain=hr(a)),i==="Expires"&&(e.expires=Kb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Kb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=hr(a)),i==="Secure"&&(e.secure=!0)}return e}async function Jb(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(fL)??[];return{headers:Object.entries(e).map(([n,o])=>({name:hr(n),value:hr(o)})),cookies:t}}async function SL(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:hr(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:hr(i),value:a?hr(a):void 0})}return n}var yL=["text"],EL=["json","xml","html","javascript"];function bL(r){let[e,t]=r.split("/");return e?yL.includes(e)?!0:t?!!EL.some(n=>t?.includes(n)):!1:!1}async function TL(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&bL(t)&&(n.text=hr(await r.text())),n}function hr(r){try{let e=JSON.parse(r),{jsonString:t}=mL(r,hL);return t}catch{return r.length>qb?r.slice(0,qb)+gL:r}}function Dn(r){return r<0?0:r}function Qb(r){return{timings:{blocked:Dn(r.domainLookupStart),dns:Dn(r.domainLookupEnd-r.domainLookupStart),connect:Dn(r.connectEnd-r.connectStart),send:Dn(r.responseStart-r.requestStart),wait:0,receive:Dn(r.responseEnd-r.responseStart),ssl:Dn(r.connectEnd-r.secureConnectionStart)},total:Dn(r.responseEnd)}}function Zb(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function je({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await B(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Zd(){return window.lastCursorPos}import{errors as vL}from"playwright-core";async function kn({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof vL.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await AL(c,i.locator,n,t);else throw c}throw l instanceof w?l:new w("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function AL(r,e,t,n){return r.message.includes("attempt #")?RL(r,e,t,n):wL(r)}async function RL(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3943
+ `,";").replace(/\s+/g," ");let a="",l=await Mr(e,n);if(l&&(a=`Target element HTML: ${St(l,100,!0)}`),i.includes("element is not enabled"))return new w("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Qt(s)),d=await Mr(u,n);d&&(c=`Covering element HTML: ${St(d,100,!0)}`)}return new w("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
3944
+ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new w("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new w("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function wL(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new w("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function eT(r){try{return await CL(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function CL({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await Mr(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[vl],h=c.getAttribute(_r),f=!g&&h?Qt(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var rT=["date","datetime-local","month","time","week"],tT={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function nT(r){try{await B(xL(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function xL({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await je({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!tT[i])return;tT[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as wt}from"zod";var oT=wt.object({doubleClick:wt.boolean().optional(),rightClick:wt.boolean().optional(),force:wt.boolean().optional(),waitForDownload:wt.boolean().optional(),delayMs:wt.number().optional(),downloadTimeoutMs:wt.number().optional(),relativePosition:wt.object({x:wt.number(),y:wt.number()}).optional()}),jie=wt.object({repeat:wt.number().optional(),convertMeta:wt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:wt.number().optional()});async function Rl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await ep(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await B(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function ep(r,e=1e3){let t=await r.state.getRoot();await je({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function tp(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return kn({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>sT({...r,targetingResult:t,useVisualClick:e})})}async function PL(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await OL(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function OL(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),sT({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function LL(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await wn({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new w("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await kL({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=oT.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function NL(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await eT({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(FL(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),PL(s,{...r,targetingResult:{...i,locator:i}})}}async function sT(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof IL.TimeoutError?new w("ActionFailureError",`Download did not complete in ${c}ms`):new w("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Rl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await LL(r):await NL(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new w("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await B(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await UL(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function DL(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new w("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function kL({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await DL(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function UL(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Xd(r.suggestedFilename()),i=e();await r.saveAs(ML(i,o)),aT(n,{force:!0}),setTimeout(()=>{aT(i,{recursive:!0,force:!0})},5*60*1e3);let a=Hb(_L(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function FL(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as BL}from"os";var zL={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function GL(){let r=BL();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function lT(r){return JSON.stringify(r.split("+").sort())}function wl(r){let e=GL(),t=lT(r);for(let n of Object.values(zL))if(Object.values(n).some(o=>lT(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function rp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await je({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Br,p=await je({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await je({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let E=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,v,A]=await B(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let x=T.getBoundingClientRect();return[T.scrollTop,x.x,x.y]}),{milliseconds:1e3});if(E===p&&b===m&&v===g&&A===h)break;p=E,m=b,g=v,h=A,await $(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function np(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await $(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as YL}from"crypto";import{cloneDeep as ap}from"lodash-es";function tn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as HL}from"crypto";var VL="v1";function op(r,e){if(r.tagName.toLowerCase()==="svg"&&!WL(r))try{let t=cT(r,e),n=jL(JSON.stringify(t));return{version:VL,json:t,hash:n}}catch{return}}function jL(r){return HL("md5").update(r).digest("hex")}function cT(r,e){let t=r.tagName.toLowerCase(),n=$L(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=cT(a,e);l&&o.children.push(l)}}return o}function WL(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function $L(r){let e={},t=r.attributes;for(let n of Object.keys(t))jt.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Un={r:147,g:196,b:125,a:.55},dT={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Un,paddingColor:Un,borderColor:Un,marginColor:Un,eventTargetColor:Un,shapeColor:Un,shapeMarginColor:Un,showInfo:!0,showAccessibilityInfo:!0};function pT({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=qL({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function qL({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((N,U)=>{u[N]=U});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],E=m.parentIndex??[],b=m.nodeName??[],v=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},T=m.inputChecked??{index:[]},x=e[c.frameId];for(let N=0;N<h.length;N++){let U=h[N],Y=v[N],ke=f[N]??[],te=E[N]!==void 0&&E[N]>=0?E[N]:void 0,ie=te!==void 0?h[te]:void 0,ut=ie!==void 0?a[ie]:void 0,M=A.index.indexOf(N),V=M!==-1?e[A.value[M]]:void 0,re=u[N],Ce;re?Ce=p[re]??[]:Ce=[];let Me=b[N]!==void 0?e[b[N]]?.toLowerCase():void 0;if(!Me){l.warn({backendNodeId:U,frameId:x,frameIndex:o,nodeBounds:Ce},"DOM node has no tag name");continue}let Ae={backendNodeId:U,psuedoType:V,nodeType:Y,frameIndex:o,parentFrameId:x,ownedFrameId:void 0,bounds:{x:Ce[0]??null,y:Ce[1]??null,width:Ce[2]??null,height:Ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:ie??null,tagName:Me,parent:ut??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ut&&ut.childrenBackendIds.push(U);let xt=g.index.indexOf(N);if(xt!==-1){let Re=g.value[xt];i[Re]=Ae;let We=r[Re]?.frameId;Ae.ownedFrameId=We!==void 0?e[We]:void 0}for(let Re of Object.keys(Ae.bounds)){let We=Re;Ae.bounds[We]!==null&&(Ae.bounds[We]/=n)}let dt=re!==void 0?d[re]??[]:[];for(let Re=0;Re<dt.length&&!(Re>=t.length);Re++){let We=dt[Re];if(We===void 0||isNaN(We))continue;let an=e[We];if(an===void 0)continue;let vr=t[Re];Ae.computedStyles[vr]=an}for(let Re=0;Re<ke.length;Re+=2){let We=ke[Re],an=ke[Re+1];if(!We||!an)continue;let vr=e[We],Qo=e[an];!vr||!Qo||(Ae.attributes[vr]=Qo)}T.index.includes(N)&&(Ae.attributes.checked="true"),a[Ae.backendNodeId]=Ae}return a[h[0]]}function ip(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${ip(t,e)}${a}`}return r.mPathSelector=n,n}function uT(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var KL=["html","#document","#document-fragment"];function mT({node:r,domGraph:e}){let t=[],n=r,o=uT(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=uT(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,KL.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function gT(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function hT(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=tn(o,_r);if(!i)throw new Error(`Could not find attribute ${_r} for object ${e}`);return i}var XL=["focusable","keyshortcuts","controls","live","relevant","orientation"],JL=["selected","readonly","modal","required","invalid"],QL=["id","name","role","content"],fT=["absolute","fixed","sticky"],ZL=["i"],eN=["path"],tN=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],ET=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],bT=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],rN=["menulistpopup","statictext","inlinetextbox"],nN=80,ST=100,TT=50,cp=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],oN=["cite"],iN={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},aN={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},yT={indentLevel:0},sp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<TT?t:""),this.role=this.role||(e.domNode.attributes.role??""),uN(this.properties,e.domNode,e.importantProperties)}pN(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&eN.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>bT.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>CT(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>xT(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&ZL.includes(this.domNode.tagName)||tN.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||jt.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>wT(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=yT){let t=Object.assign({},yT,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=ap(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===m&&(m="")}let f=cp.includes(this.role)||oN.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
3945
+ `;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let b=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==p&&!(iN[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),m&&(E+=` name=${JSON.stringify(m)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${jt.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let T=this.domNode.bounds,x=Math.round(T.x??0),N=Math.round(T.y??0),U=Math.round((T.x??0)+(T.width??0)),Y=Math.round((T.y??0)+(T.height??0));E+=` bounds=[${x} ${N} ${U} ${Y}]`}let v=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([T,x])=>{if(!XL.includes(T)){{if(JL.includes(T)&&(!x||x==="false"))return;if(T==="value"&&b&&(s.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${x}`=="1")return;if(T==="url"&&s.src&&p==="img")return;if(T==="url"&&s.href&&p==="a")return;if(T==="editable"&&x==="plaintext")return;if(T==="type"&&x===p)return;if(c&&!aN[T])return}typeof x=="string"?E+=` ${T}="${St(x,ST,!0)}"`:typeof x=="boolean"?x?E+=` ${T}`:E+=` ${T}={false}`:typeof x<"u"&&(E+=` ${T}={${St(JSON.stringify(x),ST,!0)}}`)}})}if(p==="::before"||p==="::after"){let T="";for(let x of this.children)T+=x.serialize({...e,indentLevel:n,neighbors:0});return T}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
3946
+ `;else{let T="";for(let N of this.children)T+=N.serialize({...e,indentLevel:n+2,neighbors:0});let x=T.trim();x.length<=nN&&!x.includes(`
3947
3947
  `)?E+=`>${x}</${p}>
3948
3948
  `:E+=`>
3949
3949
  ${T}${u}</${p}>
3950
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(k=>k.id===this.id),x=T>0?this.parent.children[T-1]?.serialize({...e,neighbors:0}):"",N=T<this.parent.children.length-1?this.parent.children[T+1]?.serialize({...e,neighbors:0}):"";return`${x||""}
3950
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(U=>U.id===this.id),x=T>0?this.parent.children[T-1]?.serialize({...e,neighbors:0}):"",N=T<this.parent.children.length-1?this.parent.children[T+1]?.serialize({...e,neighbors:0}):"";return`${x||""}
3951
3951
  ${E}
3952
- ${N||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:sp(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=sp(this.properties),e}},cp=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let g=n(p,l||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,l||u)return c;if(up.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function lN(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function cN(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(hs({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(hs({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function RT({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:g,logger:m,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(M,V={})=>{},E=r.backendDOMNodeId,b=nN.includes(r.role?.value?.toLowerCase()??"");if(!b&&E===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let v=E?i.backendIdToNode[E]:void 0;if(!b&&!v)try{let M=await B(g.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(M&&M.node.nodeName.toLowerCase()==="slot"&&M.node.distributedNodes?.length)m.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:M},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:M}),[]}catch(M){return f("Filtering out node since it doesn't exist in the DOM",{err:M}),[]}if(v&&e&&s&&u&&r.backendDOMNodeId&&!cN(v,u,m,h))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let w=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",T=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",x=new lp({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:w,nameSources:r.name?.sources,content:T,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(M=>TT.includes(M.name)||vT.includes(M.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+lN(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),N=n,k=a[t],q=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let M=n.childFrames.find(Ce=>Ce.frameId===v.ownedFrameId),V=o[M?.frameId??""]?.root,re=a[M?.frameId??""];if(M&&V&&re){r.childIds&&r.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let Ce=V;r.childIds=Ce.childIds,N=M,k=re,q=M.frameId}}let ke=v?.childrenBackendIds?.length??0,te=(r.childIds??[]).filter(M=>!!k.get(parseInt(M))).length;if(ke>te){let M=r.childIds?.map(re=>k.get(parseInt(re))).filter(Boolean).map(re=>re?.backendDOMNodeId).filter(re=>re!==void 0)??[],V=0;for(let re of v?.childrenBackendIds??[]){if(M.includes(re)){V=(r.childIds?.findIndex(dt=>k.get(parseInt(dt))?.backendDOMNodeId===re)??0)+1;continue}let Ce=i.backendIdToNode[re];if(!Ce||Ce?.tagName.toLowerCase()!=="svg")continue;let Me=Math.floor(-1*Math.random()*1e7),Ae={nodeId:Me.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:re,frameId:q,role:{type:"string",value:"graphics-symbol"}};k.set(Me,Ae),r.childIds||(r.childIds=[]),r.childIds.splice(V,0,Me.toString()),V++}}if(r.childIds?.length===1&&v){let M=k.get(parseInt(r.childIds[0])),V=M?.role?.value,re=v.childrenBackendIds;if(M&&V==="StaticText"&&re.length===1){let Ce=i.backendIdToNode[re[0]];if(Ce?.tagName?.toLowerCase()==="span"){let Me=Math.floor(-1*Math.random()*1e7).toString(),Ae={nodeId:Me,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ce.backendNodeId,frameId:q,childIds:[M.nodeId]};M.parentId=Me,k.set(parseInt(Me),Ae),r.childIds=[Me]}}}for(let M of r.childIds??[]){if(!M)continue;let V=k.get(parseInt(M));if(!V)continue;let re=await RT({node:V,parent:x,domGraph:i,axGraph:o,frameId:q,frameContext:N,inputNodeMap:a,cdpClient:g,logger:m,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});re.length&&(x.children=x.children.concat(re))}if(x.role==="StaticText"&&(x.children=[]),x.children.length===1&&x.children[0].role==="StaticText"){let M=x.name,V=x.children[0]?.name;(M===V||!V)&&(x.children=[])}let ie=[];for(let M=x.children.length-1;M>=0;M--){let V=x.children[M];if(V.role!=="StaticText"){ie.push(V);continue}if(M===0||x.children[M-1].role!=="StaticText"){ie.push(V);continue}x.children[M-1].name+=V.name}if(x.children=ie.reverse(),!x.isInteresting(p)&&r.parentId)return v&&(v.momenticIgnored=!0),x.children;for(let M of x.children)M.parent=x;return pN(x),v&&d&&ap(v,i),[x]}function wT({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:up.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=xl(d,i),g=p?c[p.hash]:void 0,m=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)s=wT({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function CT({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let g=t??"root",m=r[g]?.root;if(!m)throw new Error("A11y tree has no root");let h=XL(),f=x=>{let N=x.allNodes.filter(q=>!q.ignoredReasons?.find(te=>TT.includes(te.name))),k=new Map;return N.forEach(q=>{k.set(parseInt(q.nodeId),q)}),k},E={};Object.entries(r).forEach(([x,N])=>{E[x]=f(N)});let b=await RT({node:m,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:g,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},w={},T={};return wT({node:b[0],a11yIdNodeMap:v,dataMomenticIdMap:w,selectorToNodeMap:T,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new cp(b[0],v,w,T)}function uN(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<AT&&!jt.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(xT(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function dN(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||ZL.includes(a);if((jt.relevantElementAttributes.includes(a)||_T(a,t))&&!c){let u=uN(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&yT.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of yT)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function pN(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(St(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let g=u.children.filter(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>St(m.name,100,!1)),i.length===g.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),p=d.length===i?.length;d.forEach((g,m)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=m+1),p&&(g.properties.col||(g.properties.col=i[m])))})}}}function mN(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function xT(r,e){if(e&&MT(r,e))return!0;if(jt.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(jt.alwaysInterestingClassNames.includes(r))return!0;for(let t of jt.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function _T(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function MT(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var _l=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await B(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new R("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await $(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await B(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new R("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await B(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new R("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await B(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await B(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new R("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await B(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await B(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var Do="<empty>";function gN(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function PT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||gN(r.url)}async function hN(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function ko({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(PT(d.frame))return null;try{return await OT({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function OT({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await hN(r,a),c=l.attributes??[],s=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=tn(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},g=(e.childFrames??[]).map(async(m,h)=>{if(PT(m.frame))return null;try{return await OT({cdpClient:r,rawFrameTree:m,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(g)).filter(m=>m!==null),d}async function fN(r){try{return await r.owner().count()===1}catch{return!1}}async function SN(r){try{return await r.count()===1}catch{return!1}}async function fr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,Do]){let p=o.frameLocator(d===Do?"iframe":`iframe[${d}]`);if(await fN(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new R("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,Do]){let u=o.locator(s===Do?"iframe":`iframe[${s}]`);if(await SN(u)){a=u,i.push(s);break}}if(!a)throw new R("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new R("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function IT(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function LT({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Do?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===Do?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=IT(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=IT(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Vr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Ml(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function dp(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function NT(r){let e=dp(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function DT(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function kT({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await yN({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function yN({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Cn({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function UT(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as bN}from"crypto";function FT(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function BT(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(g=>[g.name,g.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let g=await e.fetch();s={body:await g.text(),options:{status:g.status(),statusText:g.statusText(),headers:Object.entries(await g.headers())}}}let u=await EN(t,c,s),d={};u.headers.forEach((g,m)=>{d[m]=g});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([g,m])=>({name:g,value:m})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},ia(o,n,i);for(let g of Object.values(a))g.onRequestComplete(i,n)}catch(g){g.message.includes("has been closed")||l.warn({err:g},"Failed to add response to HAR")}}async function EN(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function pp(r){try{await TN(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function TN(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=bN(),s=await ep(e,n);try{ia(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=FT(n,l);u?await BT({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await vN({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function vN({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Jb(i,e,l),ia(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function AN(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function RN(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Il(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function mp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await RN(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await AN(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var rn=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:Cs(t,this.requestMatcher.urlMatcher)}};function Pl(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function zT({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(m=>m.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,g;if(s)try{let m=await n.frameElement();p=await B(m?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(m){i.warn({err:m},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as Sr}from"crypto";import wN from"js-beautify";var CN=["Dead"],Ol=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Sr(),type:"PRESET_ACTION",command:Ar(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:ce(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=wN.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Bb(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...ce(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let g=this.recordedSteps.get(u)?.step??a,m=g?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...g,command:m},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(CN.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Ar("TYPE");i={id:Sr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Ar("PRESS");i={id:Sr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Ar(s);u.deltaY=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Ar(s);u.deltaX=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as gp}from"zod";var ule=gp.object({type:gp.literal("url"),url:gp.string()});var Ll=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let g=p[0]?.trim(),m=p[1]?.trim();if(g===void 0||m===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(g)||this.computedStylesToFetch.push(g)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=dp(e),{frame:o,mPathSelectorTokens:i}=await fr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await ko({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await LT({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Ml(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Ml(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await kT({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await ko({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[B(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(fr(c,n).then(({frame:u})=>B(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await ko({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Wt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new R("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Wt({fn:()=>ko({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Wt({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Wt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Wt({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Wt({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:bn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=gT({node:o,domGraph:this.domGraph});return hT(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await fT(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Qt(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await ko({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof R&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await $(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Ml(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=tn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await fr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await fr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new R("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await CT({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await fr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await je({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(tn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=tn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let g=0;g<3;g++)try{s=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(m){c=m,i.warn({err:m},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let m=async()=>{try{let h=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,signal:a,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};p.push(m())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await $(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new R("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return mT({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=NT(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function hp(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var yp=yr(Fo(),"momentic","chromium"),KN=yr(Fo(),"video"),Dl=process.env.TWO_CAPTCHA_KEY,KT=WN(qT);KT.use($N({provider:{id:"2captcha",token:Dl},visualFeedback:!0}));var sa=class r{static USER_AGENT=jN["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:l,logger:c,userBrowserSettings:s,viewport:u,properties:d,clientCallbacks:p,iconKnowledgeBase:g}){if(vf(s),this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=l,this.logger=c,this.userControlledBrowserSettings=s,this.viewport=u,this.properties=d,this.clientCallbacks=p,d.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=g}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Al]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:kb.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&Nl()==="darwin"&&ON("system_profiler SPDisplaysDataType").toString().includes("Retina")?(A.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await _l.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Ll({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,contextArgs:l,recordVideo:c,iconKnowledgeBase:s,callbacks:u}){r.clearCrashReportsDirs(),process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let d;switch(a.browserType){case"Google Chrome":d="chrome";break;case"Chrome for Testing":d=void 0;break;case"Chromium":d="chromium";break;default:d="chromium";break}let p={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},g={...l??{},geolocation:l?.geolocation||mg,locale:l?.locale||dg,timezoneId:l?.timezoneId||pg,colorScheme:l?.colorScheme,httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,ignoreHTTPSErrors:a.ignoreHttpsErrors??!1,userAgent:a.userAgent??r.USER_AGENT,viewport:l?.viewport??Br},m=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2","--enable-crashpad","--crash-on-hang-threads"];process.env.MOMENTIC_CHROME_EXTRA_ARGS&&m.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let h=null,f,E,b={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(b.isNewHeadless=!0,p.headless&&m.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&m.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&m.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let v=a.localChromeExtensionPaths?.map(T=>T.startsWith("~")?yr(Fo(),T.slice(1)):T);if(v?.length){if(d===void 0)throw new R("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let k of v){let q=yr(k,"manifest.json");if(!Bn(q))throw new R("UserConfigurationError",`Chrome extension path ${q} does not exist.`)}if(En)throw new R("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let T=yr(yp,`momentic-session-${Date.now()}`);if(!Bn(T))try{LN(T,{recursive:!0})}catch(k){throw new R("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${yp} folder: ${k}`)}let x=[...m],N=v.map(k=>VN(k)).join(",");x.push(`--disable-extensions-except=${N}`),g?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${g.deviceScaleFactor}`,`--device-scale-factor=${g.deviceScaleFactor}`),g.viewport&&x.push(`--window-size=${g.viewport.width},${g.viewport.height}`),f=await qT.launchPersistentContext(yr(yp,`momentic-session-${Date.now()}`),{...p,...g,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:e}),t.info({sharedContextOptions:g,sharedBrowserOptions:p,userBrowserSettings:a,chromeArgs:x,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (persistent)"),E=f.pages()[0]}else{h=await KT.launch({...p,args:m});let T={...g,baseURL:e,recordVideo:c?{dir:KN}:void 0};f=await h.newContext(T),t.info({contextArgs:T,sharedBrowserOptions:p,chromeArgs:m,userBrowserSettings:a,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (standard)"),E=await f.newPage()}En&&await f.route("**",Pl);let w=new r({browser:h,context:f,page:E,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:g.viewport||Br,properties:b,clientCallbacks:u,iconKnowledgeBase:s});return await w.initialize({grantPermissions:!0,runInitScripts:!1}),w}static async fromExistingContext({context:e,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize(),s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await ip(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=fp(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await B(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!xn(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=fp(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{qb(e,o,this.debugData,a,this.logger)});let i=async()=>{await Xb(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await pp({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",UT(this.customHeaders,this.logger)),En&&await e.route("**/*",Pl),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=ST({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(l=>{this.iconKnowledgeBase[l.hash]=l}),!n.length)return;let o=ce(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:zN()};for(let l of["runId","testId"])o[l]&&(i[l]=o[l]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!xn(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await B(rp(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await je({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await $(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),je({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await $(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await WT.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&UN(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:m,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");g=Math.floor(g),m=Math.floor(m),h=Math.floor(h),f=Math.floor(f);try{let E=await WT.fromBuffer(c),b=E.bitmap.width,v=E.bitmap.height;g=Math.max(0,Math.min(g,b-1)),m=Math.max(0,Math.min(m,v-1)),h=Math.max(1,Math.min(h,b-g)),f=Math.max(1,Math.min(f,v-m)),c=await E.crop({x:g,y:m,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${m}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){RS(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await $(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new R("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(zb.has(l))throw new R("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await je({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await oT({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await $(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Dm}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return wl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await $b(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await Wb(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await jb(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new R("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return ip(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof sr)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!jd.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new R("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||jt.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new R("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new R("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,g;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let b=c.parentFrame,{cache:v,config:w}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=v,p=w,u=w.frame,g="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),g="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),g="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:ce(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:g,frameConfig:DT(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:m,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:m,logger:i}));try{return{resolution:{locator:m,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:g}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let g,m=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),m=!0;break}catch(f){g=f,await $(500,a)}if(!m)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:g?i:bn,allowNotActionableNodesOverride:l,signal:a});break}catch(m){if(m instanceof Ii)break;if(m instanceof sr){if(d++,d>2)throw i.error({err:m},"Got multiple cache disqualification errors, giving up"),m;i.warn({err:m},"Got cache disqualification error, waiting and retrying resolution"),await $(500,a)}a?.throwIfAborted(),g&&i.info({err:m},`Could not resolve target using primary cache only (x${u})`),await $(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=ce(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=Uo(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof Vr&&c.push(...p.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:Uo(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new Vr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new Ii("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await je({fn:b=>window.evaluatePrimaryCaches(b),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let b={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(b),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let b=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,v=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:b,selectors:v}),n.debug({reason:b,workingSelectors:v},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new Vr("Cache evaluation failed",d);let p,g,m,h=!1;if(this.userBrowserSettings.visualActions){let b=s.mPath;if(!b)throw new Error("Found element did not have an mPath despite using visual actions");let v=b.join(" > ");p=e.locator(v),g=this.stateManager.getNodeUsingMPathSelector(v)}else if(s.dataMomenticId!==void 0)m=parseInt(s.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[m],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Qt(m));else throw new R("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=Uo(t);await this.updateCacheWithNewNodeDetails({node:g,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let E=Sp(f,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ce(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:E},"Updated cache")),{a11yNode:g,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),g;try{return await p.waitFor({state:"attached",timeout:1e3}),g=await Mr(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:g,decisions:d}}catch(m){let h=m.message;u=new R("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await $(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await je({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,g;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(Qt(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),g=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=s.closestNodeSerialized??await Mr(g,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let h=Uo(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:g,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=Sp(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ce(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:m,savedElement:t.nodeOnlySerializedHtml}),{locator:g,a11yNode:p,displayString:m,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&jd.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=qN(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:g}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),m=p.boundingBox?.width,h=p.boundingBox?.height;if(!m||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,E=this.stateManager.a11yIdToNodeMap[f],b=Uo(n);await this.updateCacheWithNewNodeDetails({target:n,node:E,locator:g,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let v=Sp(b,n);return v&&Object.keys(v).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=ce(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:v,templateMatch:d},"Updated cache after template matching resolution")),{locator:g,a11yNode:E,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=nT.some(a=>a===o.toLowerCase());return await np({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return np({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),Cs(l,t,n)){a=!0;break}await $(500,this.abortSignal)}if(!a)throw new R("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Hf(t)} in ${o}ms.
3953
- Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new R("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(tp);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Un({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Un({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await je({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Un({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await Un({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new R("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Cl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=Cl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of hp(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Cl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of hp(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new R("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await je({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await $(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(tp);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let b=0;b<l.length;b++)if(c[b]===e){d=s.indexOf(b);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,g=0,m=0,h=0]=u[d];p/=n,g/=n,m/=n,h/=n;let f=p+m/2,E=g+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return op({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return op({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await $(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new R("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3954
- Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!xn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Ja(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Dl,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await $(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Dl,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&zT({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];xn(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Cn({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new R("UserInfrastructureError",`The page with URL ${St(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await Cn({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return FN.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await je({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new R("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return je({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Hr}){let i=eT(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new R("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new R("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,g=d+c;return this.getDomNodeFromPixelPosition(p,g)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:pT,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[_r],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Qt(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await B(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await Mr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:g,error:m,serializedElement:h,point:f,force:E,logs:b}=await e.evaluate(w=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(w)},void 0,{timeout:1e3}),v=Date.now()-o;if(m){t.warn({error:m,serializedElement:h,duration:v,force:E,logs:b},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Qt(p)),hints:{clickableXY:f,force:E}};if(g)return t.info({newMPathSelector:g,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(g),hints:{clickableXY:f,force:E}};if(f)return t.info({point:f,serializedElement:h,duration:v,force:E,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:E}};if(E)return t.info({serializedElement:h,duration:v,force:E,logs:b},"Forcing click on original element"),{locator:e,hints:{force:E}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(Ub)?new as(l.error):l.error.startsWith(Fb)?new ss(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!Dl}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Zd(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Bn(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||GN(e),o=NN(e),i=HN(e),a=gu[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Bn(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:BN.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),g=new Array(p.length);for(let h=0;h<p.length;h++)g[h]=p.charCodeAt(h);let m=new Uint8Array(g);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([m],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([m]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??fp();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}static getPossibleCrashReportsDirs(){let e=[];if(Nl()==="linux"){let t=Fo();["chromium","google-chrome","chrome-canary"].forEach(n=>{e.push(yr(t,".config",n,"Crash Reports"))})}else if(Nl()==="darwin"){let t=Fo();["Chromium","Google","Chrome for Testing"].forEach(n=>{e.push(yr(t,"Library","Application Support",n,"Crashpad"))})}else if(Nl()==="win32"){let t=Fo();["Chromium","Google","Google Chrome Canary"].forEach(n=>{e.push(yr(t,"AppData","Local",n,"User Data","CrashPad","reports"))})}return e}static clearCrashReportsDirs(){try{r.getPossibleCrashReportsDirs().forEach(t=>{Bn(t)&&kN(t,{recursive:!0,force:!0})})}catch{}}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return Uo(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=r.getPossibleCrashReportsDirs();for(let t of e)if(!(!Bn(t)||!jT(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=yr(t,o);return Bn(i)&&jT(i).isDirectory()&&DN(i).length>0})))return t}};import bD from"fetch-cookie";import{cloneDeep as Sv}from"lodash-es";import{CookieJar as TD}from"tough-cookie";async function nn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}async function Er({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var YN=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function YT({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(YN.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await $(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let g=u[p];if(xn(g,o)&&g!==r&&g!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var zn=3.1783027;function XN(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Ir(r){return Math.ceil(Ep(r)/zn)}function Ep(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
3955
- `,""),t=t.replaceAll(" ","");let n=XN(t);return t.length-n+zn*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Ep(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*zn:e+=85*zn:e+=Ep(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var JT={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},QT={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},XT=/<(\S+) id="(\d+)".*?>/g,JN=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,ZT=["h1","h2","section","footer","nav","aside","form","label","dialog"],QN=[...ZT,"span","div","h3"],ZN=["table","select","form","ul","ol","menu","pre","code","dialog"],eD=["table","form","dialog","nav","section","ul","select"];function kl(r){return tD(r)}function tD({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
3956
- `),s=0,u=[],d=0,p=[],g=[],m=!1;for(;s<c.length;){m&&(l.push({ids:p,content:u.join(`
3957
- `),tokenLength:d}),u=[],d=0,p=g.length?[g[g.length-1].id]:[],m=!1);let h=c[s],f=Ir(h);d+=f,h.length>a&&(h=h.slice(0,a));let v=Array.from(h.matchAll(XT)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),T=Array.from(h.matchAll(JN)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);T.reverse();let x=h.replace(/ id="[0-9]+"/g,"");u.push(x);for(let M of v)p.push(M.id),g.push(M);for(let M of T){let V=g[g.length-1];V&&V.tagName===M&&g.pop()}let N=g.some(M=>ZN.includes(M.tagName)),k=c[s+1]??"",q=Ir(k),te=Array.from(k.matchAll(XT)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),ie=te.some(M=>ZT.includes(M)),ut=te.some(M=>QN.includes(M));d+q>=i&&(m=!0),d>=n&&(ie&&!N||T.some(M=>eD.includes(M)))&&(m=!0),d>=o&&ut&&!N&&(m=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
3958
- `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var rD=9e5,Ul=3e5,nD=5e3;async function Gn(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Ir(u);if(d>rD)try{let p=kl({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await iD({...r,tokenLimit:Ul-1e4,chunks:p.chunks}),u=s.serialize();let g=Ir(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(Ul*zn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>Ul)try{if(o){let p=kl({serializedTree:u,options:QT,logger:i});s=await B(oD({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let g=Ir(u);i.info({oldTokens:d,newTokens:g},"Filtered page using AI chunk ranking"),d=g}else{let p=kl({serializedTree:u,options:JT,logger:i});s=await B(aD({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let g=Ir(u);i.info({oldTokens:d,newTokens:g},"Filtered page using RAG"),d=g}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(Ul*zn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>nD&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:ce(i),abortSignal:c});i.info(p,"Got AI summaries");let g=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),E=Math.max(h.startId,h.endId);for(let b=f;b<=E;b++)g.add(b.toString())}s=s.pruneUsingRelevantIds(g),u=s.serialize();let m=Ir(u);i.info({newTokens:m,oldTokens:d},"Filtered page using AI summary"),d=m}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function oD({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:ce(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function iD(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 l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:ce(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(g=>g.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((g,m)=>g+m.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(g=>g.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function aD(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:ce(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function Tp(r,e){if(!r.description)throw new R("UserConfigurationError","Cannot locate element with empty description");return Er({action:async()=>sD(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function sD(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:g,localCodeEvalTools:m,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await Mu({orgId:p,s:E,context:n,localTools:m,signal:f,logger:s})),a&&(E=cD(E,a));let{serializedTree:v,tree:w}=await nn(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),T,x=Date.now(),N;for(;!T&&Date.now()-x<3e3;){f.throwIfAborted();try{T=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Ce){N=Ce}}if(!T)throw new R("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${N?.message}`);let k=v,q=!1,te=`data:image/jpeg;base64,${T.toString("base64")}`;k=await Gn({type:"locator",description:E,screenshot:te,serializedTree:v,options:{aiPageFiltering:c},tree:w,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),k!==v&&(q=!0);let ie=await h.getElementLocation({browserState:k,goal:E,screenshot:te,source:a,memory:b?l:void 0},{disableCache:t,abortSignal:f,loggerTags:ce(s),useMemory:b});s.debug({usedRag:q,result:ie},"Got locator result");let ut=ie.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:ut,pageState:k,ragUsed:q,thoughts:ie.thoughts}),!ut)throw new ho(`Could not find any relevant element: ${ie.thoughts}`,ie.updatedMemory?{type:"GCS_TRACES",traces:ie.updatedMemory}:void 0);let{resolution:M,target:V,frameConfig:re}=await g.createTargetFromA11yId({id:ie.id,requirements:ie.requirements,additionalElements:ie.additionalElements,description:E,targetSource:"AI",logger:s});if(M.a11yNode?.properties?.hidden&&M.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: ${M.displayString}`);return b&&(ie.updatedMemory?V.memory={type:"GCS_TRACES",traces:ie.updatedMemory}:l&&(V.memory=l)),{thoughts:ie.thoughts,target:V,resolution:M,frameConfig:re,screenshot:te}}var lD=["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:"],ev="<select> element:",tv="text input or contenteditable element:",rv="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:",nv="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:",bp=[ev,tv,rv,nv,...lD];function ov(r,e){if(r===e)return!0;for(let t of bp){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(bp.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!bp.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function cD(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${ev} ${r}`;case"TYPE":return`${tv} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${rv}
3959
- ${r}`;case"ELEMENT_CHECK":return`${nv}
3960
- ${r}`;default:return r}}var uD=15;async function Fl({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=uD}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=ws(c),u=0,d=Date.now(),p,g,m;try{await Er({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,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 $(s,n.abortSignal),h=Date.now();try{if(p=await Er({action:async()=>{let E=await iv(l,t,n.abortSignal);return g&&g.serializedTree===E.serializedTree&&g.screenshotBuff.equals(E.screenshotBuff)?p:(g=E,av({command:r,state:E,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:l}),p?.updatedMemory&&Ts(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new R("AssertionFailureError",p.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Er({action:async()=>av({command:r,state:await iv(l,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:l})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new R("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function iv(r,e,t){let[n,o]=await Promise.all([nn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function av({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),v=r.contextChoice??"MULTIMODAL",w=m;v!=="VISION_ONLY"&&(w=await Gn({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),w!==m&&(g.ragUsed=!0),g.pageState=w);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:w,screenshot:E,contextChoice:v,source:c},N=await(v==="VISION_ONLY"?(k,q)=>d.getVisualAssertionResult(k,q):(k,q)=>d.getAssertionResult(k,q))(T,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:ce(s)});return(N.result||i)&&N.relevantElements&&(g.relevantElementsSerialized=N.relevantElements.map(k=>u.getSerializedFormFromA11yId(k)).filter(k=>!!k),await dD(N.relevantElements,u,s)),{success:N.result,thoughts:N.thoughts,afterScreenshotOverride:f,updatedMemory:o?N.updatedMemory:void 0}}async function dD(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 B(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}}}import{cloneDeep as pD}from"lodash-es";async function lv(r){let{command:e,timeoutMs:t,fixtures:n}=r,{logger:o,abortSignal:i}=n,a=Lm(e.cache)?e.cache:void 0,l=Date.now(),c=0,s,u=500,d=!1;for(;c<2||Date.now()-l<t;){c++,c>1&&await $(u,i),i?.throwIfAborted();let{result:p,updatedCache:g,elementWasFound:m}=await sv({cacheToUse:a,params:r});if(s=p,d=m,p.success){g?.target&&Tn({cmd:e,key:"target",newTarget:g?.target,logger:o});break}g?.target?.memory&&a?.target&&(a.target.memory=g.target.memory),u=Math.min(u*2,1e4)}if(!s)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(i?.throwIfAborted(),!s.success&&a?.target&&Ma(a.target)){let p=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:g,updatedCache:m}=await sv({cacheToUse:p,params:r});s=g,g.success&&m?.target&&Tn({cmd:e,key:"target",newTarget:m.target,logger:o})}return s.success&&a?.target&&!d&&Cm(a.target),s}async function sv({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Nr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=gD(t.assertion),s,u=!1,d=pD(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>mD(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:hi(t),targetName:"target"}});return s={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(l.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),s={...g,thoughts:m}),{result:s,elementWasFound:u,updatedCache:d}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u,updatedCache:d};if(!(p instanceof R)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u,updatedCache:d}}}async function mD(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:St(c,500,!0)},!Bl(c,n.value,n.operation,!!n.negated)){let s=n.negated?An[n.operation]:Rn[n.operation];o=!1,i=new R("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:St(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new R("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Bl(c,n.value,n.operation,!!n.negated)){let s=n.negated?An[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new R("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new R("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(g=>setTimeout(g,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},kr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:kr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:kr*1e3});break}case"FOCUSED":{o=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"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?zf[n.condition]:Gf[n.condition];i=new R("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Bl(c,n.value,n.operation,!!n.negated)){let s=n.negated?An[n.operation]:Rn[n.operation];o=!1,i=new R("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Bl(c,n.value,n.operation,!!n.negated)){let s=n.negated?An[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new R("AssertionFailureError",`The style property ${n.property} ${s}`):i=new R("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Bl(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function gD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function cv(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as hD}from"jimp";async function la(r,e){let t=await r.screenshot(e),n=await hD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as uv}from"jimp";import vp from"jpeg-js";import fD from"pixelmatch";async function dv({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Nr(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},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async te=>la(o,{locator:te.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await la(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let ke=`${s.width}x${s.height}`,te=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ke}) does not match saved screenshot dimensions (${te}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await uv.fromBuffer(s.buffer),p={width:s.width,height:s.height},g=await uv.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),v=Math.abs(p.width-m.width);if(f>E){let ke=d.cover({w:m.width,h:m.height});s.buffer=await ke.getBuffer("image/jpeg"),h="current",s.width=m.width,s.height=m.height}else if(E>f){let ke=g.cover({w:p.width,h:p.height});u.buffer=await ke.getBuffer("image/jpeg"),h="saved"}let w={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},T=t.threshold??.1,N=fD(vp.decode(u.buffer).data,vp.decode(s.buffer).data,w.data,s.width,s.height,{threshold:T,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,k=N>T*100,q=`Visual diff of ${N.toFixed(2)}% detected, which is ${k?"over":"under"} the threshold of ${T*100}%.`;if(h&&(q+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${v} pixels.`),k)throw new R("ActionFailureError",q);return{fail:k,thoughts:q,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:vp.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var SD=3e4;async function pv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??SD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let l=a.toString(),c;if(yo(r.url)&&(c=r.url),t&&Eo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await B((async()=>{let g=l?`${c}?${l}`:c;try{return await n(g,{headers:i,method:r.method,body:r.body})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(m){g=`Failed to read response body: ${m}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,m)=>{d[m]=g});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var yD=5e3;async function hv({timeout:r=kr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=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 mv(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await $(l,e.signal),l=Math.min(Math.floor(l*1.5),yD);else return i}return i=await mv(e),i}async function mv({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(gv,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(gv,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?An.CONTAINS:Rn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function gv({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 ED=3e4;async function fv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??ED/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(yo(r.url)&&(l=r.url),t&&Eo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let s=await B((async()=>{try{return await n(l,{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(!s)throw new R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var zl=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,flagStore:o,storage:i,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:s,options:u}){this.orgId=a,this.options=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=s,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.flagStore=o}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:l=this.logger}){let[c,s]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await Gn({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:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ce(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await Gn({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ce(a)},langfuseSessionId:l})}catch(m){throw new R("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return nn(this.browser,e)}async locateElement(e){return await Tp({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Er({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,flagStore:this.flagStore,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:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await l(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),s>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:l,options:c,retriesWithAI:s-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 Er({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&&cu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(du(i)||uu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(pu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof sr&&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:l}=o;if(t.type!=="description")throw new R("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,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()-s<500&&await $(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:g}=l,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,E=!1,b=Sv(e.cache);if((!b||s)&&!Sc(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(m.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!ov(o.elementDescriptor,b.inputDescription)&&(m.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let v=T=>!!T&&Ma(T),w=!0;if(!v(b)){w=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await $(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let T;try{T=await Tp({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:g,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(k){if(k instanceof ho&&k.updatedLocatorMemory){let q={id:-1,...i,memory:k.updatedLocatorMemory};Tn({cmd:c,key:d,newTarget:q,logger:m})}throw new R("ActionFailureError",k.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let x=l.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,m),N=await a(x);return Tn({cmd:c,key:d,newTarget:T.target,logger:m}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=ce(m)),{result:N,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let x=l.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,m),N=await a(x);if(Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]),Tn({cmd:c,key:d,newTarget:b,logger:m}),w){let k=T.decisions.filter(q=>q.matched);if(k.length!==1)m.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let q=k[0].type;n.recordTargetAutoHeal({healType:q})}}return{result:N,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]);let x=!1;if((T instanceof sr||cu(T)||du(T)||pu(T)||fh(T)||uu(T))&&(x=!0),T instanceof R&&!x)throw m.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){m.info({err:T},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&xm(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return la(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await $(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new R("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Um(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await YT({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{bs(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Jd(e)}}async resolveCommandTemplateStrings(e,t){return Es({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 l=n.condition;return l?.assertion.trim()?Fl({command:l,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 Fl({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=Tf(n.schema);if(f)throw new R("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ce(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(!yo(n.url)&&!Eo(n.url,this.browser.baseUrl))throw new R("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,h;if(n.target&&nr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:w=>this.browser.hover(w),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=v}let f=this.browser.getViewport()?.height??Br.height,E=this.browser.getViewport()?.width??Br.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await $(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f};return xs(m,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(nr(n.fromTarget)&&nr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(nr(n.fromTarget)||nr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&nr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,n.target.pixels,{force:n.force});break}let E,b,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:w,result:T,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async N=>N.locator,options:{disableCache:i,targetName:"target",...n}});E=T,b=w,v=x}return await this.browser.mouseDrag(m,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:v}}case"SELECT_OPTION":{if(!Nr(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:hi(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await ur({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),h,f,E=Sv(n.target);if(E){let{elementInteractedDisplayString:v,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:T=>this.browser.typeIntoTarget(n.value,T,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:hi(n)}});h=v,f=w}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return xs(m,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(nr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"FOCUS":{if(!Nr(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"BLUR":{if(n.target&&!Nr(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return xs(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new TD,h=bD(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await pv({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:$g(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await fv({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return dv({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await Hb({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=Wg.optional().parse(m)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??kr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(cv(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 Fl({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&&Ts(n,E.cache?.memory.traces,a)}}let f=await lv({command:n,tracer:t,timeoutMs:m,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await Er({action:async()=>hv({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new rn(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await mp(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await B(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new rn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,m,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Il(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Il(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new rn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new rn(n.requestMatcher),async(h,f)=>{let E=await ur({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=ah.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ce(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 Ol({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:ce(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ce(this.logger)})}};import{z as De}from"zod";var yv=De.array(De.object({proc:De.string(),webview:De.string(),info:De.object({"Android-Package":De.string(),Browser:De.string(),"Protocol-Version":De.string(),"User-Agent":De.string(),"V8-Version":De.string(),"WebKit-Version":De.string(),webSocketDebuggerUrl:De.string()}),pages:De.array(De.object({description:De.string(),devtoolsFrontendUrl:De.string(),id:De.string(),title:De.string(),type:De.string(),url:De.string(),webSocketDebuggerUrl:De.string()})),webviewName:De.string()}));var Gl=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:l,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=l,this.aborter=c;for(let s of["SIGINT","SIGTERM"])process.on(s,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:l}){let c=await e.getContext(),s=typeof c=="string"?c:c.id,u=(await AD.devices()).filter(g=>g._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:s,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:l})}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 getCurrentScreenshot(){return`data:image/png;base64,${await this.driver.takeScreenshot()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tracer:o}){await o.startAsyncSpan("WAIT_FOR_STABILITY",async()=>{let i=Date.now(),a,l=!1;for(;Date.now()-i<e;){if(t?.throwIfAborted(),!a){a=await this.getCurrentScreenshot();continue}if(await this.getCurrentScreenshot()===a){l=!0;break}await $(250,t)}l||this.logger.warn({reason:n},"Timed out waiting for screenshot stability")})}async getDomState(e){let t;if(e?.includeWebviews)try{let i=await this.getActiveWebview();i&&i.browserController&&(t=(await i.browserController.getBrowserState({abortSignal:this.aborter.controller?.signal})).serializedTree)}catch(i){this.logger.error({err:i},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let n=await this.driver.getPageSource();return this.throwIfAborted(),{graph:await Mb(n,{injectedWebviewContent:t,disallowAccessibilityBridgeForWebviews:this.options.disableDefaultWebviewAccessibilityTree}),context:this.currentContext}}async refreshWebviews(){await this.driver.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let l;if(i==="com.android.chrome"?(l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Attempting to connect Playwright to webview: ${o.webview}`),l=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!l)continue;a.browserController=l,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await this.refreshWebviews();let e=await this.driver.getCurrentPackage(),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 l=Ev(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${l}`),l}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),yv.parse(e)}async createBrowserController({context:e}){let t=await sa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},storage:this.fixtures.storage,flagStore:mu,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new zl({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,flagStore:mu,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Ss})}async connectPlaywrightToWebview(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(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 RD.connectOverCDP({endpointURL:o,timeout:12e3}),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.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);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}`:"",l=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${l}`);let c=Ev(l,{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 Bo=class r extends No{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:l,adbPort:c}){let s={controller:l},u=await Gl.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:s,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:s,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${CD.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Es({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.aborter.controller?.signal,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{bs(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts();return{output:{xml:n.graph.xml,contexts:o},success:!0}}case"TAP":return new vl(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":{let n;if(e.target){let o={type:"TAP",id:wD(),target:e.target,cache:e.cache,longPress:e.clearContent};try{n=(await this.executeCommand({command:o,tracer:t})).message}finally{e.cache=o.cache}}if(await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for keyboard to appear before typing"}),e.clearContent)try{let o=await this.driver.$('//android.widget.LinearLayout[@package="app.lawnchair" and @content-desc="Select all" and @clickable="true"]');await o.waitForExist({timeout:750}),await o.click(),await this.driver.pressKeyCode(67)}catch(o){throw new Error(`Failed to clear content because the select all button was not found: ${o}`)}if(e.keyPressDelayMs)for(let o of e.text)await this.driver.keys(o),await $(e.keyPressDelayMs);else await this.driver.keys(e.text);return{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=ws(o),a=Date.now(),l=0,c,s=!1,u;for(;l<15&&!s;){this.throwIfAborted(),s||c&&c-a>=o&&(s=!0),l!==0&&await $(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{d=(await this.stateManager.getDomState({includeWebviews:!0})).graph.xml,p=await this.stateManager.getCurrentScreenshot()});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async m=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ce(this.logger)});return m.result={thoughts:h.thoughts,result:h.result},h});if(g.result)return{success:g.result,message:g.thoughts};{let m=`AssertionFailureError: ${g.thoughts}`;u=new Error(m)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${l} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{l++}}return{success:!1,message:u?.message}}case"JAVASCRIPT":{let n=await ur({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.aborter.controller?.signal});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"OPEN_NOTIFICATION_DRAWER":return await this.driver.pressKeyCode(83),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let o=await B(this.driver.execute("mobile: shell",{command:"pm",args:["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName]}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof o!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${o}`);if(o.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=o.trim().split(`
3961
- `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${o}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let o={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[o]),this.appsWithGrantedPermissions.add(e.packageName)}return await this.driver.execute("mobile: shell",{command:"am",args:["start","-n",`${e.packageName}/${n}`]}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=o=>e.longPress?this.driver.longPressKeyCode(o):this.driver.pressKeyCode(o);switch(e.key){case"HOME":await n(3);break;case"BACK":await n(4);break;case"APP_SWITCHER":await n(187);break;case"POWER":await n(26);break;case"SEARCH":await n(84);break;case"VOLUME_UP":await n(24);break;case"VOLUME_DOWN":await n(25);break;case"VOLUME_MUTE":await n(164);break}return{success:!0}}case"ADB":return{success:!0,output:await this.driver.execute("mobile: shell",{command:e.command}),message:"ADB command executed successfully"};case"PRESS_KEYBOARD":{switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await this.driver.pressKeyCode(66);break;case"BACKSPACE":await this.driver.pressKeyCode(67);break;default:{let n=e}}return{success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}async screenshot(){return this.driver.takeScreenshot()}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function bv({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:l,localToolsFactory:c,globalStateManager:s,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,g=r.handshake.query?.fileName,m=g?.endsWith("test.yaml")?g.slice(0,-"test.yaml".length):g,h=ar.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let T={...(await u(v,e)).emulator,...h.settings?.emulator},x=Date.now(),{driver:N,cleanup:k,limbarToken:q,limbarUrl:ke,emulatorName:te,adbTunnelPort:ie}=await t({socket:r,logger:e,creationOpts:{region:T.region,apkToInstall:E?{channel:E,tag:b}:void 0}});e.info({adbTunnelPort:ie,apkChannel:E,apkTag:b,duration:Date.now()-x,emulatorName:te},"Android emulator session initiated"),e=e.child({emulator:te});let ut=await o(v,e),M=await i(v,e),V=await a(v,e),re=await l(v),Ce=c?await c(v):void 0,Me={};h.settings?.defaultEnv&&(Me=(await re.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let Ae=new uo({variablesFromEnvironment:Me,envName:h.settings?.defaultEnv,testName:m}),xt=await Bo.init({driver:N,generator:ut,logger:e,options:{emulator:T},fixtures:{storage:re,browserEnricher:V,browserGenerator:M,localCodeEvalTools:Ce,testContext:Ae},orgId:v,adbPort:ie,abortController:new AbortController});if(!r.connected)throw await k(),new Error("Socket not connected anymore, not proceeding with Android session setup");let dt=xD({socket:r,testContext:Ae}),Re=async()=>{clearInterval(dt);try{await k()}catch(We){e.warn({err:We},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:xt,cleanup:Re,emulatorName:te}),r.emit("session",{testId:f,sessionId:d,limbarUrl:ke,limbarToken:q}),{sessionId:d,testId:f,orgId:v,emulatorName:te,logger:e}}function xD({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function Tv({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var _D=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},vv={event:"cancel",createHandler:_D};import{diff as $D}from"deep-object-diff";import{cloneDeep as qD}from"lodash-es";import Tge,{multistream as Age}from"pino";import wge from"pino-pretty";import MD from"fetch-retry";import ID from"os";import Av,{multistream as PD}from"pino";import OD from"pino-pretty";import LD from"pino-std-serializers";var Go=new Map,ND=!0,Rv="Log throttle exceeded",DD=100,kD=5e3,UD=MD(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}}),Ap=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??ID.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=ND?Av(a):Av(a,PD([{stream:OD({colorize:!0})}]))}getLevel(){return gs[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}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 UD(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:$r(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Rv)return!0;let t=Date.now();return t-this.lastWindowStart>kD&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Rv),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<DD?(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(Pi[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=LD.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 l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:wh({message:n||"",...i})};this.buffer.push(l),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,Go.set("app",this),Go.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=gs[e]):(this.minLevelValue=Pi[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Hl=({app:r,hostname:e,disableConsoleLogs:t})=>(Go.has(r)||Go.set(r,new Ap({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Go.get(r));function wv(){for(let r of Go.values())r.flush()}import{PostHog as Gge}from"posthog-node";import{PostHog as Xge}from"posthog-node";import ca from"os";import FD from"v8";var Cv,br,BD=ca.platform(),zD=ca.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),{});function xv(r){if(En)return;let e=()=>{try{let t=!1,n=GD(),o=HD();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=FD.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:zD,platform:BD}}function GD(){let r=ca.totalmem(),e=ca.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function HD(){let r=ca.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,!br)return br=t,null;let n={user:t.user-br.user,nice:t.nice-br.nice,sys:t.sys-br.sys,idle:t.idle-br.idle,irq:t.irq-br.irq,total:t.total-br.total};return Cv={measurementTime:e,intervalMs:e-br.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},br=t,Cv}function _v(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof l=="string"&&l.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${l}`)}catch(l){o++;let c=l instanceof Error?l.message:`${l}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function Mv(r){let e=Date.now(),t=r.fixtures.controller;try{return await VD(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function VD({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await jD({step:n,params:e}),l={};Object.entries(a).forEach(([p,g])=>{l[p]=JSON.stringify(g)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:l,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},s=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:s}});return c.steps=d,c.status=u,c.endTime=Date.now(),Jf({result:c,...Xf(d)}),c}async function jD({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as Iv}from"crypto";async function Pv({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,l;if(!t.interactive)try{l=await a.screenshot()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c=n.startCommand();try{let s=await a.executeCommand({command:e.command,tracer:c}),u=c.getRootSpan(),d={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,trace:u,startTime:o,endTime:Date.now(),data:s.output};if(!t.interactive){try{let p=Iv(),g=await a.screenshot();d.afterSnapshot=p,n.attachAfterScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(g,"base64")})}catch(p){i.warn({err:p},"Failed to take after screenshot")}if(l){let p=Iv();d.beforeSnapshot=p,n.attachBeforeScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(l,"base64")})}}return d}catch(s){let u=c.getRootSpan();return s instanceof Error&&s.name==="AbortError"||a.isAborted()?{...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now(),trace:u}:(i.error({err:s},"Failed to execute preset step"),{...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now(),trace:u})}}async function Rp(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:l,controller:c,usageTracker:s}=e,u=a.getParentStepIdChain(),d=[],p,g="SUCCESS",{fromStep:m,toStep:h}=t,f=!!m;for(let E=0;E<i.length;E++){let b=i[E];if(l.info({step:b},`Executing step ${E+1} of ${i.length} in ${o}: ${Vf(b)}`),b.skipped){l.debug("Step skipped");continue}if(f&&m){let T=JSON.stringify(u);if(b.id===m.fromStepId&&T===JSON.stringify(m.parentStepIdChain))f=!1;else if(!Yf({currentStep:b,currentParentChain:u,desiredStepId:m.fromStepId,desiredStepParentChain:m.parentStepIdChain}))continue}let v=await a.startStep({logger:l,step:b,attempt:1,parentStepIdChain:[]});s.trackStepExecution(b);let w=await WD({step:b,stepTracer:v,params:r});if(d.push(w),await v.finish({parentStepIdChain:[],result:w}),w.status!=="SUCCESS"){g=w.status,p=w;break}if(b.envKey&&c.context.setVariable(b.envKey,w.data),h){let T=JSON.stringify([]);if(b.id===h.toStepId&&T===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:g,terminalResult:p}}async function WD({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await Pv({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await Mv({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Rp}});break}}return i}async function Vl(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:l}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=qD(n);a.info({testMetadata:ar.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=xv(a),d=_v(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:g}=await Rp({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let m=$D(c,n);if(m&&Object.keys(m).length>0){a.debug({diffs:m},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await wn({steps:n,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}return{status:"PASSED",results:g}}return p==="CANCELLED"?{status:"CANCELLED",results:g}:{status:"FAILED",results:g}}var wp=class{parentTracer=null;socket;step;commandTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.commandTracer=new So("command")}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){switch(e.result.status){case"SUCCESS":this.socket.emit("success",e);break;case"FAILED":this.socket.emit("failure",e);break;case"CANCELLED":this.socket.emit("cancelled",e);break}return this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Ho({parentStep:this.step,socket:this.socket,parentTracer:this})}},Ho=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new wp({step:e.step,parentTracer:this,socket:this.socket})}},jl=class{constructor(e){this.socket=e}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Ho({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Ho({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Ho({parentStep:null,parentTracer:null,socket:this.socket})}};var KD=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Android session found");let c=await o(r.orgId),s=l.controller;s.resetAbortController();let u=new jl(n),d=await Vl({fixtures:{controller:s,logger:e,cacheStorage:c,usageTracker:new Xa},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:u});await u.finish();let p={results:d.results,status:d.status},g=JSON.parse($r(p));a?.(g)},Ov={event:"execute",createHandler:KD};import{debounce as YD}from"ts-debounce";var XD=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=YD(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},Lv={event:"keepalive",createHandler:XD};var Nv=[Ov,vv,Lv];function Dv(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new JD(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async l=>{e.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await Tv({socket:l,globalStateManager:n,logger:e})});let c;try{c=await bv({...r,socket:l,globalStateManager:n})}catch(s){e.error({err:s},"Failed to setup Android connection"),l.emit("error",{message:s instanceof Error?s.message:JSON.stringify(s)}),l.disconnect(!0);return}Nv.forEach(s=>a(s,{...r,socket:l,metadata:c,logger:e}))});let a=(l,c)=>{let s=l.createHandler(c),u=(...d)=>{l.event!=="keepalive"&&c.logger.debug({event:l.event},`Websocket event (${l.event})`);let p=g=>{c.logger.error({event:l.event,err:g instanceof Error?g:new Error(`${g}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:g instanceof Error?g.message:`${g}`})};try{let g=s.apply(this,d);g&&typeof g.catch=="function"&&g.catch(p)}catch(g){p(g)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{cloneDeep as QD}from"lodash-es";import zv from"truncate-json";var kv=1e3,Uv=5e6,ZD=5*1024*1024;function Gv(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=zv(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":Fv(n);break;case"MOBILE_MODULE_STEP":Fv(n),Gv(n.steps,e);break;default:return(()=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})()}}}function Fv(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Bv(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 Wl(r,e){let t=QD(r);if(Gv(t,e),t.length>kv)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,kv);let n=Bv(t,e);if(n.length>Uv)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Uv;)t.pop(),n=Bv(t,e);let{jsonString:o}=zv(n,ZD);try{return yn.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}}var ua=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{confirm as r0,input as n0}from"@inquirer/prompts";import{existsSync as xSe,mkdirSync as _Se,statSync as o0}from"fs";import Vo,{supportsColor as t0}from"chalk";import{Console as Hv}from"console";import{format as da}from"util";var Cp=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},$l=class r extends Hv{_buffer=[];_groupDepth=0;Console=Hv;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Cp(void 0,r.write).stack;if(!i)return e;let a=i.split(`
3952
+ ${N||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ap(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ap(this.properties),e}},lp=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(cp.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function sN(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function lN(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(ms({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(ms({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function vT({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:m,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(M,V={})=>{},E=r.backendDOMNodeId,b=rN.includes(r.role?.value?.toLowerCase()??"");if(!b&&E===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let v=E?i.backendIdToNode[E]:void 0;if(!b&&!v)try{let M=await B(m.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(M&&M.node.nodeName.toLowerCase()==="slot"&&M.node.distributedNodes?.length)g.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:M},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:M}),[]}catch(M){return f("Filtering out node since it doesn't exist in the DOM",{err:M}),[]}if(v&&e&&s&&u&&r.backendDOMNodeId&&!lN(v,u,g,h))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",T=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",x=new sp({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:T,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(M=>ET.includes(M.name)||bT.includes(M.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+sN(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),N=n,U=a[t],Y=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let M=n.childFrames.find(Ce=>Ce.frameId===v.ownedFrameId),V=o[M?.frameId??""]?.root,re=a[M?.frameId??""];if(M&&V&&re){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let Ce=V;r.childIds=Ce.childIds,N=M,U=re,Y=M.frameId}}let ke=v?.childrenBackendIds?.length??0,te=(r.childIds??[]).filter(M=>!!U.get(parseInt(M))).length;if(ke>te){let M=r.childIds?.map(re=>U.get(parseInt(re))).filter(Boolean).map(re=>re?.backendDOMNodeId).filter(re=>re!==void 0)??[],V=0;for(let re of v?.childrenBackendIds??[]){if(M.includes(re)){V=(r.childIds?.findIndex(dt=>U.get(parseInt(dt))?.backendDOMNodeId===re)??0)+1;continue}let Ce=i.backendIdToNode[re];if(!Ce||Ce?.tagName.toLowerCase()!=="svg")continue;let Me=Math.floor(-1*Math.random()*1e7),Ae={nodeId:Me.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:re,frameId:Y,role:{type:"string",value:"graphics-symbol"}};U.set(Me,Ae),r.childIds||(r.childIds=[]),r.childIds.splice(V,0,Me.toString()),V++}}if(r.childIds?.length===1&&v){let M=U.get(parseInt(r.childIds[0])),V=M?.role?.value,re=v.childrenBackendIds;if(M&&V==="StaticText"&&re.length===1){let Ce=i.backendIdToNode[re[0]];if(Ce?.tagName?.toLowerCase()==="span"){let Me=Math.floor(-1*Math.random()*1e7).toString(),Ae={nodeId:Me,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ce.backendNodeId,frameId:Y,childIds:[M.nodeId]};M.parentId=Me,U.set(parseInt(Me),Ae),r.childIds=[Me]}}}for(let M of r.childIds??[]){if(!M)continue;let V=U.get(parseInt(M));if(!V)continue;let re=await vT({node:V,parent:x,domGraph:i,axGraph:o,frameId:Y,frameContext:N,inputNodeMap:a,cdpClient:m,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});re.length&&(x.children=x.children.concat(re))}if(x.role==="StaticText"&&(x.children=[]),x.children.length===1&&x.children[0].role==="StaticText"){let M=x.name,V=x.children[0]?.name;(M===V||!V)&&(x.children=[])}let ie=[];for(let M=x.children.length-1;M>=0;M--){let V=x.children[M];if(V.role!=="StaticText"){ie.push(V);continue}if(M===0||x.children[M-1].role!=="StaticText"){ie.push(V);continue}x.children[M-1].name+=V.name}if(x.children=ie.reverse(),!x.isInteresting(p)&&r.parentId)return v&&(v.momenticIgnored=!0),x.children;for(let M of x.children)M.parent=x;return dN(x),v&&d&&ip(v,i),[x]}function AT({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:cp.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=op(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=AT({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function RT({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let h=YL(),f=x=>{let N=x.allNodes.filter(Y=>!Y.ignoredReasons?.find(te=>ET.includes(te.name))),U=new Map;return N.forEach(Y=>{U.set(parseInt(Y.nodeId),Y)}),U},E={};Object.entries(r).forEach(([x,N])=>{E[x]=f(N)});let b=await vT({node:g,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},A={},T={};return AT({node:b[0],a11yIdNodeMap:v,dataMomenticIdMap:A,selectorToNodeMap:T,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new lp(b[0],v,A,T)}function cN(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<TT&&!jt.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(wT(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function uN(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||QL.includes(a);if((jt.relevantElementAttributes.includes(a)||CT(a,t))&&!c){let u=cN(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&fT.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of fT)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function dN(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(St(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>St(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function pN(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function wT(r,e){if(e&&xT(r,e))return!0;if(jt.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(jt.alwaysInterestingClassNames.includes(r))return!0;for(let t of jt.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function CT(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function xT(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var Cl=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await B(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new w("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await $(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await B(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new w("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await B(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new w("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await B(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await B(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new w("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await B(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await B(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var No="<empty>";function mN(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function MT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||mN(r.url)}async function gN(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Do({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(MT(d.frame))return null;try{return await IT({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function IT({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await gN(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=tn(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(MT(g.frame))return null;try{return await IT({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function hN(r){try{return await r.owner().count()===1}catch{return!1}}async function fN(r){try{return await r.count()===1}catch{return!1}}async function fr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,No]){let p=o.frameLocator(d===No?"iframe":`iframe[${d}]`);if(await hN(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new w("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,No]){let u=o.locator(s===No?"iframe":`iframe[${s}]`);if(await fN(u)){a=u,i.push(s);break}}if(!a)throw new w("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new w("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function _T(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function PT({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===No?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===No?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=_T(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=_T(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Vr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function xl(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function up(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function OT(r){let e=up(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function LT(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function NT({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await SN({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function SN({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await wn({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function DT(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as EN}from"crypto";function kT(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function UT(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await yN(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},oa(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function yN(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function dp(r){try{await bN(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function bN(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=EN(),s=await Qd(e,n);try{oa(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=kT(n,l);u?await UT({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await TN({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function TN({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Xb(i,e,l),oa(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function vN(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function AN(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function _l(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function pp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await AN(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await vN(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var rn=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:ws(t,this.requestMatcher.urlMatcher)}};function Ml(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function FT({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await B(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Sr}from"crypto";import RN from"js-beautify";var wN=["Dead"],Il=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Sr(),type:"PRESET_ACTION",command:Ar(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:pe(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=RN.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Fb(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...pe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(wN.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Ar("TYPE");i={id:Sr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Ar("PRESS");i={id:Sr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Ar(s);u.deltaY=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Ar(s);u.deltaX=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as mp}from"zod";var lle=mp.object({type:mp.literal("url"),url:mp.string()});var Pl=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=up(e),{frame:o,mPathSelectorTokens:i}=await fr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await Do({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await PT({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(xl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:xl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await NT({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Do({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[B(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(fr(c,n).then(({frame:u})=>B(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await Do({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Wt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new w("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Wt({fn:()=>Do({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Wt({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Wt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Wt({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Wt({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:bn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=mT({node:o,domGraph:this.domGraph});return gT(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await hT(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Qt(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Do({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof w&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await $(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:xl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=tn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await fr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await fr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new w("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await RT({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await fr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await je({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(tn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=tn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await $(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new w("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return pT({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=OT(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function gp(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Sp=yr(Uo(),"momentic","chromium"),$N=yr(Uo(),"video"),Ll=process.env.TWO_CAPTCHA_KEY,$T=VN(WT);$T.use(jN({provider:{id:"2captcha",token:Ll},visualFeedback:!0}));var aa=class r{static USER_AGENT=HN["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(Tf(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[vl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Db.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&Ol()==="darwin"&&PN("system_profiler SPDisplaysDataType").toString().includes("Retina")?(R.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Cl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Pl({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,contextArgs:a,recordVideo:l,iconKnowledgeBase:c,callbacks:s}){r.clearCrashReportsDirs(),process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...a??{},geolocation:a?.geolocation||dg,locale:a?.locale||cg,timezoneId:a?.timezoneId||ug,colorScheme:a?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??r.USER_AGENT,viewport:a?.viewport??Br},m=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2","--enable-crashpad","--crash-on-hang-threads"];process.env.MOMENTIC_CHROME_EXTRA_ARGS&&m.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,h,f,E={systemDevicePixelRatio:a?.deviceScaleFactor,recordVideo:l,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(E.isNewHeadless=!0,d.headless&&m.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&m.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&m.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let b=i.localChromeExtensionPaths?.map(A=>A.startsWith("~")?yr(Uo(),A.slice(1)):A);if(b?.length){if(u===void 0)throw new w("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let N of b){let U=yr(N,"manifest.json");if(!Fn(U))throw new w("UserConfigurationError",`Chrome extension path ${U} does not exist.`)}if(En)throw new w("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let A=yr(Sp,`momentic-session-${Date.now()}`);if(!Fn(A))try{ON(A,{recursive:!0})}catch(N){throw new w("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Sp} folder: ${N}`)}let T=[...m],x=b.map(N=>GN(N)).join(",");T.push(`--disable-extensions-except=${x}`),p?.deviceScaleFactor&&T.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&T.push(`--window-size=${p.viewport.width},${p.viewport.height}`),h=await WT.launchPersistentContext(yr(Sp,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:T,baseURL:e}),t.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:i,chromeArgs:T,properties:E,baseUrl:e},"Browser initialization context args (persistent)"),f=h.pages()[0]}else{g=await $T.launch({...d,args:m});let A={...p,baseURL:e,recordVideo:l?{dir:$N}:void 0};h=await g.newContext(A),t.info({contextArgs:A,sharedBrowserOptions:d,chromeArgs:m,userBrowserSettings:i,properties:E,baseUrl:e},"Browser initialization context args (standard)"),f=await h.newPage()}En&&await h.route("**",Ml);let v=new r({browser:g,context:h,page:f,baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,viewport:p.viewport||Br,properties:E,clientCallbacks:s,iconKnowledgeBase:c});return await v.initialize({grantPermissions:!0,runInitScripts:!1}),v}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,logger:i}){let a=e.pages()[0];if(!a)throw new Error("No page found in existing context");let l=a.viewportSize(),c=a?.url(),s=new r({browser:e.browser(),context:e,page:a,baseUrl:c,logger:i,storage:t,enricher:n,userBrowserSettings:o,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await s.initialize({grantPermissions:!1,runInitScripts:!0}),s}async handleAvailableTabsChangeHelper(){try{let e=await np(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=hp(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await B(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Cn(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=hp(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{$b(e,o,this.debugData,a,this.logger)});let i=async()=>{await Yb(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await dp({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",DT(this.customHeaders,this.logger)),En&&await e.route("**/*",Ml),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!Cn(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await B(ep(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await je({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await $(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),je({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await $(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await VT.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&kN(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let E=await VT.fromBuffer(c),b=E.bitmap.width,v=E.bitmap.height;m=Math.max(0,Math.min(m,b-1)),g=Math.max(0,Math.min(g,v-1)),h=Math.max(1,Math.min(h,b-m)),f=Math.max(1,Math.min(f,v-g)),c=await E.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){AS(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await $(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new w("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(Bb.has(l))throw new w("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await je({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await nT({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await $(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Lm}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Rl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await Wb(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await jb(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Vb(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new w("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return np(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof sr)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Hd.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new w("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||jt.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new w("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new w("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let b=c.parentFrame,{cache:v,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=v,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:pe(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:LT(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await $(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:bn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof Mi)break;if(g instanceof sr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await $(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await $(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=pe(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=ko(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof Vr&&c.push(...p.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:ko(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new Vr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new Mi("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await je({fn:b=>window.evaluatePrimaryCaches(b),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let b={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(b),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let b=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,v=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:b,selectors:v}),n.debug({reason:b,workingSelectors:v},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new Vr("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let b=s.mPath;if(!b)throw new Error("Found element did not have an mPath despite using visual actions");let v=b.join(" > ");p=e.locator(v),m=this.stateManager.getNodeUsingMPathSelector(v)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Qt(g));else throw new w("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=ko(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let E=fp(f,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:E},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await Mr(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new w("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await $(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await je({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(Qt(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await Mr(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=ko(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=fp(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&Hd.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=WN(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,E=this.stateManager.a11yIdToNodeMap[f],b=ko(n);await this.updateCacheWithNewNodeDetails({target:n,node:E,locator:m,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let v=fp(b,n);return v&&Object.keys(v).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=pe(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:v,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:E,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=rT.some(a=>a===o.toLowerCase());return await tp({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return tp({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),ws(l,t,n)){a=!0;break}await $(500,this.abortSignal)}if(!a)throw new w("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Gf(t)} in ${o}ms.
3953
+ Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new w("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Zd);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await kn({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await kn({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await je({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await kn({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await kn({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=wl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=wl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of gp(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=wl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of gp(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new w("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await je({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await $(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Zd);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let b=0;b<l.length;b++)if(c[b]===e){d=s.indexOf(b);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,E=m+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return rp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return rp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await $(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3954
+ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Cn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Xa(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Ll,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await $(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ll,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&FT({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Cn(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await wn({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new w("UserInfrastructureError",`The page with URL ${St(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await wn({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return UN.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await je({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new w("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return je({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Hr}){let i=Zb(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new w("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new w("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:dT,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[_r],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Qt(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await B(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await Mr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:E,logs:b}=await e.evaluate(A=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(A)},void 0,{timeout:1e3}),v=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:v,force:E,logs:b},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Qt(p)),hints:{clickableXY:f,force:E}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:E}};if(f)return t.info({point:f,serializedElement:h,duration:v,force:E,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:E}};if(E)return t.info({serializedElement:h,duration:v,force:E,logs:b},"Forcing click on original element"),{locator:e,hints:{force:E}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(kb)?new is(l.error):l.error.startsWith(Ub)?new as(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!Ll}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Jd(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Fn(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||BN(e),o=LN(e),i=zN(e),a=pu[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Fn(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:FN.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??hp();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}static getPossibleCrashReportsDirs(){let e=[];if(Ol()==="linux"){let t=Uo();["chromium","google-chrome","chrome-canary"].forEach(n=>{e.push(yr(t,".config",n,"Crash Reports"))})}else if(Ol()==="darwin"){let t=Uo();["Chromium","Google","Chrome for Testing"].forEach(n=>{e.push(yr(t,"Library","Application Support",n,"Crashpad"))})}else if(Ol()==="win32"){let t=Uo();["Chromium","Google","Google Chrome Canary"].forEach(n=>{e.push(yr(t,"AppData","Local",n,"User Data","CrashPad","reports"))})}return e}static clearCrashReportsDirs(){try{r.getPossibleCrashReportsDirs().forEach(t=>{Fn(t)&&DN(t,{recursive:!0,force:!0})})}catch{}}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return ko(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=r.getPossibleCrashReportsDirs();for(let t of e)if(!(!Fn(t)||!HT(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=yr(t,o);return Fn(i)&&HT(i).isDirectory()&&NN(i).length>0})))return t}};import SD from"fetch-cookie";import{cloneDeep as fv}from"lodash-es";import{CookieJar as yD}from"tough-cookie";async function nn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}async function Er({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var qN=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function qT({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(qN.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await $(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Cn(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var Bn=3.1783027;function KN(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Ir(r){return Math.ceil(yp(r)/Bn)}function yp(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
3955
+ `,""),t=t.replaceAll(" ","");let n=KN(t);return t.length-n+Bn*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=yp(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*Bn:e+=85*Bn:e+=yp(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var YT={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},XT={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},KT=/<(\S+) id="(\d+)".*?>/g,YN=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,JT=["h1","h2","section","footer","nav","aside","form","label","dialog"],XN=[...JT,"span","div","h3"],JN=["table","select","form","ul","ol","menu","pre","code","dialog"],QN=["table","form","dialog","nav","section","ul","select"];function Nl(r){return ZN(r)}function ZN({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
3956
+ `),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
3957
+ `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=Ir(h);d+=f,h.length>a&&(h=h.slice(0,a));let v=Array.from(h.matchAll(KT)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),T=Array.from(h.matchAll(YN)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);T.reverse();let x=h.replace(/ id="[0-9]+"/g,"");u.push(x);for(let M of v)p.push(M.id),m.push(M);for(let M of T){let V=m[m.length-1];V&&V.tagName===M&&m.pop()}let N=m.some(M=>JN.includes(M.tagName)),U=c[s+1]??"",Y=Ir(U),te=Array.from(U.matchAll(KT)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),ie=te.some(M=>JT.includes(M)),ut=te.some(M=>XN.includes(M));d+Y>=i&&(g=!0),d>=n&&(ie&&!N||T.some(M=>QN.includes(M)))&&(g=!0),d>=o&&ut&&!N&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
3958
+ `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var eD=9e5,Dl=3e5,tD=5e3;async function zn(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Ir(u);if(d>eD)try{let p=Nl({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await nD({...r,tokenLimit:Dl-1e4,chunks:p.chunks}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(Dl*Bn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>Dl)try{if(o){let p=Nl({serializedTree:u,options:XT,logger:i});s=await B(rD({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using AI chunk ranking"),d=m}else{let p=Nl({serializedTree:u,options:YT,logger:i});s=await B(oD({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(Dl*Bn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>tD&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:pe(i),abortSignal:c});i.info(p,"Got AI summaries");let m=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),E=Math.max(h.startId,h.endId);for(let b=f;b<=E;b++)m.add(b.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let g=Ir(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function rD({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:pe(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function nD(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 l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:pe(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function oD(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:pe(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function bp(r,e){if(!r.description)throw new w("UserConfigurationError","Cannot locate element with empty description");return Er({action:async()=>iD(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function iD(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await xu({orgId:p,s:E,context:n,localTools:g,signal:f,logger:s})),a&&(E=sD(E,a));let{serializedTree:v,tree:A}=await nn(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),T,x=Date.now(),N;for(;!T&&Date.now()-x<3e3;){f.throwIfAborted();try{T=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Ce){N=Ce}}if(!T)throw new w("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${N?.message}`);let U=v,Y=!1,te=`data:image/jpeg;base64,${T.toString("base64")}`;U=await zn({type:"locator",description:E,screenshot:te,serializedTree:v,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),U!==v&&(Y=!0);let ie=await h.getElementLocation({browserState:U,goal:E,screenshot:te,source:a,memory:b?l:void 0},{disableCache:t,abortSignal:f,loggerTags:pe(s),useMemory:b});s.debug({usedRag:Y,result:ie},"Got locator result");let ut=ie.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:ut,pageState:U,ragUsed:Y,thoughts:ie.thoughts}),!ut)throw new go(`Could not find any relevant element: ${ie.thoughts}`,ie.updatedMemory?{type:"GCS_TRACES",traces:ie.updatedMemory}:void 0);let{resolution:M,target:V,frameConfig:re}=await m.createTargetFromA11yId({id:ie.id,requirements:ie.requirements,additionalElements:ie.additionalElements,description:E,targetSource:"AI",logger:s});if(M.a11yNode?.properties?.hidden&&M.a11yNode?.properties?.hidden!=="false")throw new w("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: ${M.displayString}`);return b&&(ie.updatedMemory?V.memory={type:"GCS_TRACES",traces:ie.updatedMemory}:l&&(V.memory=l)),{thoughts:ie.thoughts,target:V,resolution:M,frameConfig:re,screenshot:te}}var aD=["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:"],QT="<select> element:",ZT="text input or contenteditable element:",ev="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:",tv="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:",Ep=[QT,ZT,ev,tv,...aD];function rv(r,e){if(r===e)return!0;for(let t of Ep){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Ep.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Ep.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function sD(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${QT} ${r}`;case"TYPE":return`${ZT} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${ev}
3959
+ ${r}`;case"ELEMENT_CHECK":return`${tv}
3960
+ ${r}`;default:return r}}var lD=15;async function kl({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=lD}){if(!r.assertion.trim())throw new w("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=Rs(c),u=0,d=Date.now(),p,m,g;try{await Er({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,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 $(s,n.abortSignal),h=Date.now();try{if(p=await Er({action:async()=>{let E=await nv(l,t,n.abortSignal);return m&&m.serializedTree===E.serializedTree&&m.screenshotBuff.equals(E.screenshotBuff)?p:(m=E,ov({command:r,state:E,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:l}),p?.updatedMemory&&bs(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new w("AssertionFailureError",p.thoughts):new w("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Er({action:async()=>ov({command:r,state:await nv(l,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:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new w("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function nv(r,e,t){let[n,o]=await Promise.all([nn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function ov({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),v=r.contextChoice??"MULTIMODAL",A=g;v!=="VISION_ONLY"&&(A=await zn({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:v,source:c},N=await(v==="VISION_ONLY"?(U,Y)=>d.getVisualAssertionResult(U,Y):(U,Y)=>d.getAssertionResult(U,Y))(T,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:pe(s)});return(N.result||i)&&N.relevantElements&&(m.relevantElementsSerialized=N.relevantElements.map(U=>u.getSerializedFormFromA11yId(U)).filter(U=>!!U),await cD(N.relevantElements,u,s)),{success:N.result,thoughts:N.thoughts,afterScreenshotOverride:f,updatedMemory:o?N.updatedMemory:void 0}}async function cD(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 B(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}}}import{cloneDeep as av}from"lodash-es";async function sv(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=Pm(e.cache)?e.cache:void 0,a=av(i),l=()=>{i&&(a?i.target={...a.target,memory:i.target.memory}:hc(i.target))},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await $(d,o),o?.throwIfAborted();let{result:m,elementWasFound:g}=await iv({cacheToUse:i,params:r});if(u=m,p=g,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new w("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&_a(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:g}=await iv({cacheToUse:m,params:r});u=g,u.success||l()}return u.success&&i?.target&&!p&&hc(i.target),u}async function iv({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Nr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=dD(t.assertion),s,u=!1,d=av(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>uD(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:gi(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u};if(!(p instanceof w)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u}}}async function uD(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:St(c,500,!0)},!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,i=new w("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:St(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new w("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new w("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},kr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:kr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:kr*1e3});break}case"FOCUSED":{o=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"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Bf[n.condition]:zf[n.condition];i=new w("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,i=new w("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The style property ${n.property} ${s}`):i=new w("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Ul(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function dD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function lv(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pD}from"jimp";async function sa(r,e){let t=await r.screenshot(e),n=await pD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as cv}from"jimp";import Tp from"jpeg-js";import mD from"pixelmatch";async function uv({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Nr(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},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async te=>sa(o,{locator:te.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await sa(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let ke=`${s.width}x${s.height}`,te=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ke}) does not match saved screenshot dimensions (${te}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await cv.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await cv.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,b=Math.abs(p.height-g.height),v=Math.abs(p.width-g.width);if(f>E){let ke=d.cover({w:g.width,h:g.height});s.buffer=await ke.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let ke=m.cover({w:p.width,h:p.height});u.buffer=await ke.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},T=t.threshold??.1,N=mD(Tp.decode(u.buffer).data,Tp.decode(s.buffer).data,A.data,s.width,s.height,{threshold:T,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,U=N>T*100,Y=`Visual diff of ${N.toFixed(2)}% detected, which is ${U?"over":"under"} the threshold of ${T*100}%.`;if(h&&(Y+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${v} pixels.`),U)throw new w("ActionFailureError",Y);return{fail:U,thoughts:Y,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Tp.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gD=3e4;async function dv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??gD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(So(r.url)&&(c=r.url),t&&yo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await B((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new w("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new w("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var hD=5e3;async function gv({timeout:r=kr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=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 pv(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await $(l,e.signal),l=Math.min(Math.floor(l*1.5),hD);else return i}return i=await pv(e),i}async function pv({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(mv,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(mv,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?vn.CONTAINS:An.CONTAINS;a=new w("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new w("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function mv({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 fD=3e4;async function hv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??fD/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(So(r.url)&&(l=r.url),t&&yo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);let s=await B((async()=>{try{return await n(l,{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(!s)throw new w("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var Fl=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:l,visualDiffScreenshotStorage:c,options:s}){this.orgId=i,this.options=s,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=l,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:l=this.logger}){let[c,s]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await zn({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:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await zn({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(a)},langfuseSessionId:l})}catch(g){throw new w("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return nn(this.browser,e)}async locateElement(e){return await bp({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Er({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:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),s>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:l,options:c,retriesWithAI:s-1});throw new w("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 Er({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&&lu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(uu(i)||cu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(du(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof sr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof w?n:new w("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:l}=o;if(t.type!=="description")throw new w("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,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()-s<500&&await $(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,E=!1,b=fv(e.cache);if((!b||s)&&!fc(o))throw new w("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!rv(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let v=T=>!!T&&_a(T),A=!0;if(!v(b)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await $(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let T;try{T=await bp({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(U){if(U instanceof go&&U.updatedLocatorMemory){let Y={id:-1,...i,memory:U.updatedLocatorMemory};Es({cmd:c,key:d,newTarget:Y,logger:g})}throw new w("ActionFailureError",U.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let x=l.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,g),N=await a(x);return Es({cmd:c,key:d,newTarget:T.target,logger:g}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=pe(g)),{result:N,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let x=l.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,g),N=await a(x);if(Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]),Es({cmd:c,key:d,newTarget:b,logger:g}),A){let U=T.decisions.filter(Y=>Y.matched);if(U.length!==1)g.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let Y=U[0].type;n.recordTargetAutoHeal({healType:Y})}}return{result:N,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]);let x=!1;if((T instanceof sr||lu(T)||uu(T)||du(T)||gh(T)||cu(T))&&(x=!0),T instanceof w&&!x)throw g.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){g.info({err:T},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&wm(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new w("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return sa(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await $(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new w("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Dm(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await qT({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{ys(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Yd(e)}}async resolveCommandTemplateStrings(e,t){return Ss({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 l=n.condition;return l?.assertion.trim()?kl({command:l,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 w("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new w("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return kl({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new w("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=bf(n.schema);if(f)throw new w("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:pe(a)});if(f.result==="NOT_FOUND")throw new w("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new w("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 w("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 w("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(!So(n.url)&&!yo(n.url,this.browser.baseUrl))throw new w("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&nr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=v}let f=this.browser.getViewport()?.height??Br.height,E=this.browser.getViewport()?.width??Br.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new w("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new w("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await $(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f};return Cs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(nr(n.fromTarget)&&nr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(nr(n.fromTarget)||nr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new w("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&nr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:T,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async N=>N.locator,options:{disableCache:i,targetName:"target",...n}});E=T,b=A,v=x}return await this.browser.mouseDrag(g,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:v}}case"SELECT_OPTION":{if(!Nr(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:gi(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await ur({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 w("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new w("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=fv(n.target);if(E){let{elementInteractedDisplayString:v,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:T=>this.browser.typeIntoTarget(n.value,T,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:gi(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 b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Cs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(nr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Nr(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Nr(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Cs(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new yD,h=SD(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await dv({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:jg(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await hv({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return uv({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await Gb({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new w("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new w("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Vg.optional().parse(g)}catch(f){throw new w("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??kr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(lv(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 kl({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&&bs(n,E.cache?.memory.traces,a)}}let f=await sv({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Er({action:async()=>gv({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new rn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await pp(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new w("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await B(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new rn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=_l(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=_l(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new w("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new rn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new rn(n.requestMatcher),async(h,f)=>{let E=await ur({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=oh.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:pe(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 Il({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:pe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})}};import{z as De}from"zod";var Sv=De.array(De.object({proc:De.string(),webview:De.string(),info:De.object({"Android-Package":De.string(),Browser:De.string(),"Protocol-Version":De.string(),"User-Agent":De.string(),"V8-Version":De.string(),"WebKit-Version":De.string(),webSocketDebuggerUrl:De.string()}),pages:De.array(De.object({description:De.string(),devtoolsFrontendUrl:De.string(),id:De.string(),title:De.string(),type:De.string(),url:De.string(),webSocketDebuggerUrl:De.string()})),webviewName:De.string()}));var Bl=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:l,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=l,this.aborter=c;for(let s of["SIGINT","SIGTERM"])process.on(s,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:l}){let c=await e.getContext(),s=typeof c=="string"?c:c.id,u=(await bD.devices()).filter(m=>m._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:s,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:l})}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 getCurrentScreenshot(){return`data:image/png;base64,${await this.driver.takeScreenshot()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tracer:o}){await o.startAsyncSpan("WAIT_FOR_STABILITY",async()=>{let i=Date.now(),a,l=!1;for(;Date.now()-i<e;){if(t?.throwIfAborted(),!a){a=await this.getCurrentScreenshot();continue}if(await this.getCurrentScreenshot()===a){l=!0;break}await $(250,t)}l||this.logger.warn({reason:n},"Timed out waiting for screenshot stability")})}async getDomState(e){let t;if(e?.includeWebviews)try{let i=await this.getActiveWebview();i&&i.browserController&&(t=(await i.browserController.getBrowserState({abortSignal:this.aborter.controller?.signal})).serializedTree)}catch(i){this.logger.error({err:i},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let n=await this.driver.getPageSource();return this.throwIfAborted(),{graph:await _b(n,{injectedWebviewContent:t,disallowAccessibilityBridgeForWebviews:this.options.disableDefaultWebviewAccessibilityTree}),context:this.currentContext}}async refreshWebviews(){await this.driver.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let l;if(i==="com.android.chrome"?(l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Attempting to connect Playwright to webview: ${o.webview}`),l=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!l)continue;a.browserController=l,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await this.refreshWebviews();let e=await this.driver.getCurrentPackage(),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 l=yv(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${l}`),l}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),Sv.parse(e)}async createBrowserController({context:e}){let t=await aa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new Fl({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new hs})}async connectPlaywrightToWebview(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(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 TD.connectOverCDP({endpointURL:o,timeout:12e3}),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.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);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}`:"",l=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${l}`);let c=yv(l,{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 Fo=class r extends Lo{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:l,adbPort:c}){let s={controller:l},u=await Bl.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:s,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:s,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${AD.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Ss({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.aborter.controller?.signal,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{ys(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts();return{output:{xml:n.graph.xml,contexts:o},success:!0}}case"TAP":return new Tl(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":{let n;if(e.target){let o={type:"TAP",id:vD(),target:e.target,cache:e.cache,longPress:e.clearContent};try{n=(await this.executeCommand({command:o,tracer:t})).message}finally{e.cache=o.cache}}if(await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for keyboard to appear before typing"}),e.clearContent)try{let o=await this.driver.$('//android.widget.LinearLayout[@package="app.lawnchair" and @content-desc="Select all" and @clickable="true"]');await o.waitForExist({timeout:750}),await o.click(),await this.driver.pressKeyCode(67)}catch(o){throw new Error(`Failed to clear content because the select all button was not found: ${o}`)}if(e.keyPressDelayMs)for(let o of e.text)await this.driver.keys(o),await $(e.keyPressDelayMs);else await this.driver.keys(e.text);return{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Rs(o),a=Date.now(),l=0,c,s=!1,u;for(;l<15&&!s;){this.throwIfAborted(),s||c&&c-a>=o&&(s=!0),l!==0&&await $(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{d=(await this.stateManager.getDomState({includeWebviews:!0})).graph.xml,p=await this.stateManager.getCurrentScreenshot()});let m=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:pe(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(m.result)return{success:m.result,message:m.thoughts};{let g=`AssertionFailureError: ${m.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${l} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{l++}}return{success:!1,message:u?.message}}case"JAVASCRIPT":{let n=await ur({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.aborter.controller?.signal});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"OPEN_NOTIFICATION_DRAWER":return await this.driver.pressKeyCode(83),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let o=await B(this.driver.execute("mobile: shell",{command:"pm",args:["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName]}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof o!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${o}`);if(o.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=o.trim().split(`
3961
+ `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${o}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let o={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[o]),this.appsWithGrantedPermissions.add(e.packageName)}return await this.driver.execute("mobile: shell",{command:"am",args:["start","-n",`${e.packageName}/${n}`]}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=o=>e.longPress?this.driver.longPressKeyCode(o):this.driver.pressKeyCode(o);switch(e.key){case"HOME":await n(3);break;case"BACK":await n(4);break;case"APP_SWITCHER":await n(187);break;case"POWER":await n(26);break;case"SEARCH":await n(84);break;case"VOLUME_UP":await n(24);break;case"VOLUME_DOWN":await n(25);break;case"VOLUME_MUTE":await n(164);break}return{success:!0}}case"ADB":return{success:!0,output:await this.driver.execute("mobile: shell",{command:e.command}),message:"ADB command executed successfully"};case"PRESS_KEYBOARD":{switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await this.driver.pressKeyCode(66);break;case"BACKSPACE":await this.driver.pressKeyCode(67);break;default:{let n=e}}return{success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}async screenshot(){return this.driver.takeScreenshot()}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function Ev({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:l,localToolsFactory:c,globalStateManager:s,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,m=r.handshake.query?.fileName,g=m?.endsWith("test.yaml")?m.slice(0,-"test.yaml".length):m,h=ar.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let T={...(await u(v,e)).emulator,...h.settings?.emulator},x=Date.now(),{driver:N,cleanup:U,limbarToken:Y,limbarUrl:ke,emulatorName:te,adbTunnelPort:ie}=await t({socket:r,logger:e,creationOpts:{region:T.region,apkToInstall:E?{channel:E,tag:b}:void 0}});e.info({adbTunnelPort:ie,apkChannel:E,apkTag:b,duration:Date.now()-x,emulatorName:te},"Android emulator session initiated"),e=e.child({emulator:te});let ut=await o(v,e),M=await i(v,e),V=await a(v,e),re=await l(v),Ce=c?await c(v):void 0,Me={};h.settings?.defaultEnv&&(Me=(await re.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let Ae=new co({variablesFromEnvironment:Me,envName:h.settings?.defaultEnv,testName:g}),xt=await Fo.init({driver:N,generator:ut,logger:e,options:{emulator:T},fixtures:{storage:re,browserEnricher:V,browserGenerator:M,localCodeEvalTools:Ce,testContext:Ae},orgId:v,adbPort:ie,abortController:new AbortController});if(!r.connected)throw await U(),new Error("Socket not connected anymore, not proceeding with Android session setup");let dt=RD({socket:r,testContext:Ae}),Re=async()=>{clearInterval(dt);try{await U()}catch(We){e.warn({err:We},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:xt,cleanup:Re,emulatorName:te}),r.emit("session",{testId:f,sessionId:d,limbarUrl:ke,limbarToken:Y}),{sessionId:d,testId:f,orgId:v,emulatorName:te,logger:e}}function RD({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function bv({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var wD=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},Tv={event:"cancel",createHandler:wD};import{diff as VD}from"deep-object-diff";import{cloneDeep as jD}from"lodash-es";import Age,{multistream as wge}from"pino";import xge from"pino-pretty";import CD from"fetch-retry";import xD from"os";import vv,{multistream as _D}from"pino";import MD from"pino-pretty";import ID from"pino-std-serializers";var zo=new Map,PD=!0,Av="Log throttle exceeded",OD=100,LD=5e3,ND=CD(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}}),vp=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??xD.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=PD?vv(a):vv(a,_D([{stream:MD({colorize:!0})}]))}getLevel(){return ps[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}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 ND(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:$r(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Av)return!0;let t=Date.now();return t-this.lastWindowStart>LD&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Av),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<OD?(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(Ii[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=ID.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 l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Rh({message:n||"",...i})};this.buffer.push(l),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,zo.set("app",this),zo.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=ps[e]):(this.minLevelValue=Ii[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},zl=({app:r,hostname:e,disableConsoleLogs:t})=>(zo.has(r)||zo.set(r,new vp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),zo.get(r));function Rv(){for(let r of zo.values())r.flush()}import{PostHog as Vge}from"posthog-node";import{PostHog as Qge}from"posthog-node";import la from"os";import DD from"v8";var wv,br,kD=la.platform(),UD=la.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),{});function Cv(r){if(En)return;let e=()=>{try{let t=!1,n=FD(),o=BD();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=DD.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:UD,platform:kD}}function FD(){let r=la.totalmem(),e=la.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function BD(){let r=la.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,!br)return br=t,null;let n={user:t.user-br.user,nice:t.nice-br.nice,sys:t.sys-br.sys,idle:t.idle-br.idle,irq:t.irq-br.irq,total:t.total-br.total};return wv={measurementTime:e,intervalMs:e-br.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},br=t,wv}function xv(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof l=="string"&&l.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${l}`)}catch(l){o++;let c=l instanceof Error?l.message:`${l}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function _v(r){let e=Date.now(),t=r.fixtures.controller;try{return await zD(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function zD({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await GD({step:n,params:e}),l={};Object.entries(a).forEach(([p,m])=>{l[p]=JSON.stringify(m)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:l,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},s=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:s}});return c.steps=d,c.status=u,c.endTime=Date.now(),Xf({result:c,...Yf(d)}),c}async function GD({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as Mv}from"crypto";async function Iv({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,l;if(!t.interactive)try{l=await a.screenshot()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c=n.startCommand();try{let s=await a.executeCommand({command:e.command,tracer:c}),u=c.getRootSpan(),d={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,trace:u,startTime:o,endTime:Date.now(),data:s.output};if(!t.interactive){try{let p=Mv(),m=await a.screenshot();d.afterSnapshot=p,n.attachAfterScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(m,"base64")})}catch(p){i.warn({err:p},"Failed to take after screenshot")}if(l){let p=Mv();d.beforeSnapshot=p,n.attachBeforeScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(l,"base64")})}}return d}catch(s){let u=c.getRootSpan();return s instanceof Error&&s.name==="AbortError"||a.isAborted()?{...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now(),trace:u}:(i.error({err:s},"Failed to execute preset step"),{...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now(),trace:u})}}async function Ap(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:l,controller:c,usageTracker:s}=e,u=a.getParentStepIdChain(),d=[],p,m="SUCCESS",{fromStep:g,toStep:h}=t,f=!!g;for(let E=0;E<i.length;E++){let b=i[E];if(l.info({step:b},`Executing step ${E+1} of ${i.length} in ${o}: ${Hf(b)}`),b.skipped){l.debug("Step skipped");continue}if(f&&g){let T=JSON.stringify(u);if(b.id===g.fromStepId&&T===JSON.stringify(g.parentStepIdChain))f=!1;else if(!Kf({currentStep:b,currentParentChain:u,desiredStepId:g.fromStepId,desiredStepParentChain:g.parentStepIdChain}))continue}let v=await a.startStep({logger:l,step:b,attempt:1,parentStepIdChain:[]});s.trackStepExecution(b);let A=await HD({step:b,stepTracer:v,params:r});if(d.push(A),await v.finish({parentStepIdChain:[],result:A}),A.status!=="SUCCESS"){m=A.status,p=A;break}if(b.envKey&&c.context.setVariable(b.envKey,A.data),h){let T=JSON.stringify([]);if(b.id===h.toStepId&&T===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:m,terminalResult:p}}async function HD({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await Iv({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await _v({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Ap}});break}}return i}async function Gl(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:l}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=jD(n);a.info({testMetadata:ar.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=Cv(a),d=xv(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:m}=await Ap({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let g=VD(c,n);if(g&&Object.keys(g).length>0){a.debug({diffs:g},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await Rn({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}return{status:"PASSED",results:m}}return p==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var Rp=class{parentTracer=null;socket;step;commandTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.commandTracer=new fo("command")}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){switch(e.result.status){case"SUCCESS":this.socket.emit("success",e);break;case"FAILED":this.socket.emit("failure",e);break;case"CANCELLED":this.socket.emit("cancelled",e);break}return this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Go({parentStep:this.step,socket:this.socket,parentTracer:this})}},Go=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new Rp({step:e.step,parentTracer:this,socket:this.socket})}},Hl=class{constructor(e){this.socket=e}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}};var WD=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Android session found");let c=await o(r.orgId),s=l.controller;s.resetAbortController();let u=new Hl(n),d=await Gl({fixtures:{controller:s,logger:e,cacheStorage:c,usageTracker:new Ya},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:u});await u.finish();let p={results:d.results,status:d.status},m=JSON.parse($r(p));a?.(m)},Pv={event:"execute",createHandler:WD};import{debounce as $D}from"ts-debounce";var qD=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=$D(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},Ov={event:"keepalive",createHandler:qD};var Lv=[Pv,Tv,Ov];function Nv(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new KD(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async l=>{e.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await bv({socket:l,globalStateManager:n,logger:e})});let c;try{c=await Ev({...r,socket:l,globalStateManager:n})}catch(s){e.error({err:s},"Failed to setup Android connection"),l.emit("error",{message:s instanceof Error?s.message:JSON.stringify(s)}),l.disconnect(!0);return}Lv.forEach(s=>a(s,{...r,socket:l,metadata:c,logger:e}))});let a=(l,c)=>{let s=l.createHandler(c),u=(...d)=>{l.event!=="keepalive"&&c.logger.debug({event:l.event},`Websocket event (${l.event})`);let p=m=>{c.logger.error({event:l.event,err:m instanceof Error?m:new Error(`${m}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:m instanceof Error?m.message:`${m}`})};try{let m=s.apply(this,d);m&&typeof m.catch=="function"&&m.catch(p)}catch(m){p(m)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{cloneDeep as YD}from"lodash-es";import Bv from"truncate-json";var Dv=1e3,kv=5e6,XD=5*1024*1024;function zv(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Bv(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":Uv(n);break;case"MOBILE_MODULE_STEP":Uv(n),zv(n.steps,e);break;default:return(()=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})()}}}function Uv(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Fv(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 Vl(r,e){let t=YD(r);if(zv(t,e),t.length>Dv)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Dv);let n=Fv(t,e);if(n.length>kv)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>kv;)t.pop(),n=Fv(t,e);let{jsonString:o}=Bv(n,XD);try{return yn.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}}var ca=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{confirm as ZD,input as e0}from"@inquirer/prompts";import{existsSync as MSe,mkdirSync as ISe,statSync as t0}from"fs";import Ho,{supportsColor as QD}from"chalk";import{Console as Gv}from"console";import{format as ua}from"util";var wp=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},jl=class r extends Gv{_buffer=[];_groupDepth=0;Console=Gv;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new wp(void 0,r.write).stack;if(!i)return e;let a=i.split(`
3962
3962
  `).slice(o).filter(Boolean).join(`
3963
- `);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",da(e,...t))}error(e,...t){this._log("error",da(e,...t))}info(e,...t){this._log("info",da(e,...t))}log(e,...t){this._log("log",da(e,...t))}warn(e,...t){this._log("warn",da(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Vv(r){let e=globalThis.console,t=new $l;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
3963
+ `);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",ua(e,...t))}error(e,...t){this._log("error",ua(e,...t))}info(e,...t){this._log("info",ua(e,...t))}log(e,...t){this._log("log",ua(e,...t))}warn(e,...t){this._log("warn",ua(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Hv(r){let e=globalThis.console,t=new jl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
3964
3964
  `);process.stderr.write(`${o}
3965
- `),globalThis.console=e}}var xp=" ".repeat(6);import{hostname as e0}from"os";var Ct=Hl({app:"cli",hostname:e0(),disableConsoleLogs:!0}).child({cliVersion:"0.0.19"});function _p(r){if(!r)return;r=r.toLowerCase();let e=ms.safeParse(r);if(e.success)return A.setMinLevel(e.data),e.data}function jv({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),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return Vv(()=>{if(c.forEach(u=>{A.log(""),o(u)}),c.length){A.log("");let u=c.length===1?"":"s";A.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{A.dimmed(n(d))})}if(s.length){A.log("");let u=s.length===1?"":"s";A.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{A.dimmed(n(d))})}if(a.length){A.log("");let u=a.length===1?"":"s";A.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{A.dimmed(n(d))})}if(l.length){A.log("");let u=l.length===1?"":"s";A.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{A.dimmed(n(d))})}if(i.length){A.log("");let u=i.length===1?"":"s";A.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{A.dimmed(n(d))})}A.log(""),A.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var pa=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Vo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Vo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Vo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Vo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Vo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Vo.bgMagenta.white("RUNNING"),a=0):(A.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),t0||(i=`${i}`),A.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var i0=!1,Wv=(()=>{try{return o0("/.dockerenv"),!0}catch{return!1}})();async function ql(r,e){return ua||i0||Wv?!0:(A.flush(),Ct.flush(),await new Promise(n=>setTimeout(n,500)),await r0({message:r}))}async function $v(r,e){return ua||Wv?e:(await n0({message:r,default:e})).trim()||e}import a0 from"fs";import{tmpdir as s0}from"os";import l0 from"path";import{registry as ma}from"playwright-core/lib/server";import qv from"proper-lockfile";var Kv=l0.join(s0(),"momenticBrowserInstallation");var Mp=["chrome","chromium","chrome-for-testing"],c0={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Yv={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Xv(r){let e=Yv[c0[r]??""]??"",t=ma.findExecutable(e);return!t||t.installType==="none"?!1:Ip(t)}function Ip(r){let e=r.executablePath();return a0.existsSync(e)}function u0(r,e){let t=Yv[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ma.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Ip(n)))return n}async function d0({browser:r,force:e}){let t=u0(r,e);if(!t){A.info(`Browser '${r}' is already installed, skipping...`);return}A.info(`Installing browser '${r}'...`);try{await ma.installDeps([t],!1),await ma.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){A.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ma.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Ip(o);)A.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function Kl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Mp:Array.from(new Set(r));try{await qv.lock(Kv,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){A.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 d0({browser:i,force:e})}catch(a){o=a,A.error(`Failed to install the ${i} browser: ${a}`)}}finally{await qv.unlock(Kv,{realpath:!1})}if(o)throw o}import{createServer as p0}from"http";async function Yl(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await m0(o))return o}A.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function m0(r){return new Promise((e,t)=>{let n=p0();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(A.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{randomUUID as uU}from"crypto";import{diff as Mye}from"deep-object-diff";import zye from"yaml";import{z as Hye}from"zod";import{execSync as g0}from"child_process";function Hn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,A.debug({postSaveCommand:n},"Executing post-save hook command");try{g0(n,{encoding:"utf-8"})}catch(o){A.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as aye}from"deep-object-diff";import{cloneDeep as lye}from"lodash-es";import{v4 as bye}from"uuid";import vye from"yaml";import h0 from"@dotenvx/dotenvx";import f0 from"fs";import Jv from"path";function S0(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function y0(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=S0(i);l&&(n[o]=l);continue}let a;try{a=f0.readFileSync(Jv.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&A.debug(n,"Set environment variables with interpolation from project configuration"),n}function E0(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=h0.config({path:Jv.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Xl(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=y0({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=E0({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as O0,readFileSync as L0,readdirSync as N0,writeFileSync as D0}from"fs";import{globSync as k0}from"glob";import Vn,{dirname as tA}from"path";import{cwd as Dp}from"process";import rA from"yaml";import{z as be}from"zod";import Qv from"fs";import{globSync as b0}from"glob";import ga from"path";import T0 from"yaml";import{z as Pp}from"zod";var Zv=!1,Op=["**/*.test.yaml","**/*.module.yaml"],Lp=Pp.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Np=50,v0=Pp.object({fileType:Pp.nativeEnum(ye)});function Zt(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Op,o=Array.from(r.config.exclude??[]).concat(ds),i=b0(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Np,nodir:!0});for(let a of i){let l=A0(r.rootDir,a,t,e?bn:A);l&&(t.duplicateEntities[l.id]=l.paths)}return Zv=!0,t}function A0(r,e,t,n){let o=ga.join(r,e),i=R0(o,n);if(!i)return;let a=w0(i,o,n);if(!a)return;let l=v0.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=C0(o,n);if(!s)return;let u=x0(e,o,s);switch(c){case ye.TEST:try{return _0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ye.MODULE:try{return M0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case ye.MOBILE_TEST:try{return P0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case ye.MOBILE_MODULE:try{return I0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function R0(r,e){try{return Qv.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function w0(r,e,t){try{let n=T0.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function C0(r,e){try{return Qv.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function x0(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ga.sep,fullPathSegments:e.split(ga.sep),relativePathSegments:r.split(ga.sep),fileName:ga.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function _0(r,e,t,n,o){let i=po.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:ye.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function M0(r,e,t,n,o){let i=Nt.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:ye.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!Zv&&zr(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function I0(r,e,t,n,o){let i=wi.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let l=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:ye.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function P0(r,e,t,n,o){let i=ar.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:ye.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var jo="momentic.config.yaml",eA="momentic.workspace.yaml",U0=be.object({projects:be.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),F0=be.union([be.string(),be.object({fromFile:be.string(),json:be.boolean().optional()})]),B0=be.object({name:Lp,baseUrl:be.string().optional().describe("Optional for mobile tests"),envFile:be.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:be.record(be.string(),F0).optional(),inheritFromShell:be.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:dn.optional().describe("deprecated: use project-level configuration only")}),z0=be.object({postSave:be.string().optional()}),G0=be.object({name:Lp,include:be.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:be.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:be.string().optional(),reporterDir:be.string().optional(),outputDir:be.string().optional(),retries:be.number().optional().describe("number of retries per test"),parallel:be.number().optional().describe("degree of parallelism"),environments:be.array(B0).optional(),gitMainBranch:be.string().optional(),gitProtectedBranches:be.string().array().optional(),ai:yu.optional(),browser:dn.optional(),emulator:su.optional(),advanced:Eu.optional(),hooks:z0.optional()});function nA(r,e){let t;try{t=L0(r,"utf-8")}catch(o){A.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=rA.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){A.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function kp(r){let e=nA(r,"project configuration");if(e!==void 0)try{return G0.parse(e)}catch(t){A.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function H0(r){let e=nA(r,"workspace configuration");if(e!==void 0)try{return U0.parse(e)}catch(t){A.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function V0(){let r=[],e=Dp(),t=Vn.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Vn.basename(e);if(us.includes(i))return A.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of N0(e))if(a.endsWith(jo)){let l=Vn.join(e,a),c=kp(l);c&&r.push({configFilePath:l,config:c,rootDir:tA(l)})}if(r.length)return r;if(e=Vn.dirname(e),e===t)break}return r}function ha(r={}){let{configFilePath:e,nameFilter:t}=r,n=W0(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
3966
- ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return A.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function j0(r){let e=H0(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${jo}`)),n=k0(t,{absolute:!1,cwd:Dp(),dotRelative:!1,maxDepth:Np,nodir:!0}),o=[];for(let i of n){let a=Vn.join(Dp(),i),l=kp(a);l&&o.push({configFilePath:a,config:l,rootDir:tA(a)})}return o}function W0(r){if(r){r=Vn.resolve(r);let t=kp(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Vn.dirname(r)}]}if(O0(eA)){let t=j0(eA);if(t)return t}return V0()}function oA(r,e){let t=rA.stringify(r);D0(e,t)}import{z as Up}from"zod";var iA="test-results";var CEe=Up.object({width:Up.number(),height:Up.number()});import{execFile as $0}from"node:child_process";import{promisify as q0}from"node:util";import K0 from"simple-git";var Te=K0(),aA=q0($0);async function Y0(r){let e=await ve(r,Te.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
3967
- `)){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 X0(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 aA("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await aA("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function J0(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return X0(r,e,t);if(o)return}catch{}}function Jl(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 ve(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function Q0(){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 Z0(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.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{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 ek(r){let[e,t,n]=await Promise.all([ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]);return{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 tk(r){let[e,t,n,o]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Jl(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function rk(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Jl(o):void 0;return{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?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function nk(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Jl(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function ok(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([ve(r,Te.revparse(["HEAD"])),ve(r,Te.revparse(["--short","HEAD"])),ve(r,Te.revparse(["--abbrev-ref","HEAD"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"])),e?ve(r,Te.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),Y0(r)]),d=s?await ve(r,Te.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?Jl(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await J0(r,i,u)??E??void 0;return r.debug({userUsername:b,gitLocalUserLogin:E,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function ik(){let r=process.env._HEAD_REPO_URL;return{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 ak(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Fp(r,e){let t=Q0();if(!t)return ok(r,e);switch(t){case"GithubActions":return Z0(r);case"GitlabCI":return ek(r);case"CircleCI":return tk(r);case"Buildkite":return rk(r);case"AzureDevOps":return nk(r);case"GCPCloudBuild":return ik()}}async function sk(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 lk(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 ck(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await lk(r,e,n,o,t)}else if(t.gitlabProjectPath)return await sk(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ql(r,e,t){let n=await ak(t),o=await Fp(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 ck(r,e,i);return{...n,...o,...a}}import{diff as sA}from"deep-object-diff";import jn from"fs";import{cloneDeep as uk}from"lodash-es";import Bp from"path";import{v4 as JEe}from"uuid";import Zl from"yaml";function lA({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!jn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=jn.readFileSync(i,"utf-8"),l=Zl.parse(a),c={...r,schemaVersion:e},s=vn({fileType:ye.MOBILE_MODULE,...wi.parse(c),steps:Yt.array().parse(r.steps)}),u=sA(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=Zl.stringify(s);jn.writeFileSync(i,d,"utf-8"),Hn(i,n.config)}function cA({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=fa(i,o),l={...a,...e},c=vn({fileType:ye.MOBILE_MODULE,...es.parse(l)}),s=sA(c,a);if(s&&Object.keys(s).length===0)return;let u=Zl.stringify(c);jn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${zr(e.name)}.module.yaml`;if(d=Bp.join(Bp.dirname(i),p),jn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);jn.renameSync(i,d)}Hn(d||i,n.config)}function fa(r,e){let t=jn.readFileSync(r,"utf-8"),n=Zl.parse(t);try{return{...es.parse(n),name:Bp.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 zp(r,e,t,n){let o=fa(r.fullFilePath,t),{resolvedSteps:i}=await vs({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async l=>{let c=e.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${l}`);return fa(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=uk(a)),a}async function uA(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await zp(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as dk}from"crypto";import Wn from"fs";import Gp from"path";import ec from"yaml";function dA({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${zr(r)}.test.yaml`,l=Gp.join(o,a);if(Wn.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:ye.MOBILE_TEST,id:dk(),description:e,schemaVersion:Pc,settings:n,steps:t},s=ec.stringify(c);return Wn.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function pk(r){if(!Wn.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=Wn.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
3968
- `),t=ec.parse(e),n=ns.parse(t);if(n.fileType!==ye.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function tc(r,e,t){let n=pk(r),o;try{o=ar.parse(n)}catch(l){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedStepLists:i}=await Wf({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async l=>{let c=t.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Mobile module ${l} not found`);return fa(c,e)}});return{...o,steps:i.steps}}async function pA({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=Gp.isAbsolute(r)?r:Gp.join(n,r);if(!Wn.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=Wn.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
3969
- `),c=ec.parse(l),s=ns.parse(c);if(s.fileType!==ye.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await wn({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=ec.stringify(ns.parse(d));for(let g of u?.moduleUpdates??[])lA({content:g,schemaVersion:Pc,momenticFiles:i,project:o});Wn.writeFileSync(a,p,"utf-8"),Hn(a,o.config)}import{randomUUID as mk}from"crypto";import Pr from"fs";import $n from"path";var mA={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 gk(r,e,t){if(mA[t]){let i=mA[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 gA=new Set([".DS_Store","__MACOSX"]);function hA(r,e,t){let n=mk(),o=r.child({runGroupId:n});Pr.rmSync(e,{recursive:!0,force:!0});let i=Pr.readdirSync(t).filter(s=>!gA.has(s)).map(s=>$n.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Pr.mkdirSync(e,{recursive:!0});let a=$n.join(i[0],"metadata.json"),l={...Li.parse(JSON.parse(Pr.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=$n.join(s,"runs");if(!Pr.existsSync(u))continue;let d=Pr.readdirSync(u);for(let m of d){if(gA.has(m))continue;let h=$n.join(u,m),f=$n.join(e,"runs",m);Pr.cpSync(h,f,{recursive:!0})}let p=$n.join(s,"metadata.json"),g=Li.parse(JSON.parse(Pr.readFileSync(p,"utf-8")));o.info({oldRunGroupId:g.id},"Merging metadata from run groups");for(let m in g){if(m==="id")continue;let h=m;l[h]=gk(l,g,h)}}let c=$n.join(e,"metadata.json");Pr.writeFileSync(c,JSON.stringify(l,null,2))}import SA from"adm-zip";import qp from"fs";import{z as jp}from"zod";var D="v1",Hp="mobile-cli",Sa="0.0.19";var hk=9e4,fk=3,Sk=1500,yk=15e3,er=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function Ek(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Vp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Sa&&(e[Oh]=Sa),Hp&&(e[Lh]=Hp),e}async sendRequest(e,t){let{retries:n=fk,requestTimeoutMs:o=hk,initialRetryDelayMs:i=Sk,maxRetryDelayMs:a=yk}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof er&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new qr),l===0)throw s;let p=c-l,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(m=>setTimeout(m,g))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await Ek(s);throw new er(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Tr=class extends Vp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var tr=class extends Tr{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${D}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return Jh.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${D}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return qh.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${D}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return zh.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${D}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Hh.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${D}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Vh.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${D}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Bh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${D}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Xh.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${D}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Qh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${D}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return mf.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${D}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${D}/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(`/${D}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Zh.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${D}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return yg.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${D}/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(`/${D}/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(`/${D}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ef.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${D}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return tf.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${D}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return rf.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${D}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return nf.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ff.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${D}/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(`/${D}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Oi.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${D}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Oi.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${D}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wu.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(`/${D}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Oi.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${D}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Oi.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wu.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${D}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return jp.record(jp.string(),jp.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${D}/quarantine`,{method:"GET"});return of.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${D}/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(`/${D}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${D}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return af.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${D}/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(`/${D}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return sf.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${D}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${D}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return lf.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${D}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Wp(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(A.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),A.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return A.debug("Got auth info from API"),n}var rc=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Wo=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 bk,en as Tk}from"@faker-js/faker";var $o="v1",qo=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 bk({locale:Tk}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${$o}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof er?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${$o}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${$o}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${$o}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${$o}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${$o}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as vk}from"zod";var qn=class extends Tr{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Ag.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${D}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Sa,...e},signal:t.abortSignal});return vg.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${D}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return vk.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(`/${D}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Uh.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(`/${D}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Tu.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return kh.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return Dh.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(`/${D}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Tu.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${D}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Nh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${D}/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(`/${D}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Nc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${D}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Fh.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${D}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Oc.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return tg.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${D}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Bc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${D}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Ng.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Jm.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return eg.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Zm.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${D}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Am.parse(n)}};var Ko=class extends Tr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${D}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Rm.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function fA(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var nc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await fA(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 Yo=class extends Tr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return kg.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Bg.parse(o)}};function oc({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new ys:new $p(r,e,t,n)}var $p=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=vu(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&Iu({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await wn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import ic from"path";function Ak(r){let e=new SA,t=ic.join(r,"metadata.json"),n=Li.parse(JSON.parse(qp.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of qp.readdirSync(ic.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new SA(ic.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(ic.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function ac(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!qp.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new nc(e);try{let{runGroupId:i,buffer:a}=Ak(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;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 Rk from"adm-zip";import yt from"fs";import rr from"path";var ya=class r{constructor(e){this.filePath=e;yt.rmSync(this.filePath,{recursive:!0,force:!0}),yt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(rr.join(this.filePath,e))}mkdir(e){yt.mkdirSync(rr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=rr.join(this.filePath,e);if(yt.existsSync(t))return yt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.filePath,t);try{yt.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Kp(rr.join(this.filePath,"runs"),e)}},Kp=class{constructor(e,t){this.filePath=e;this.tempPath=rr.join(e,`.${t}`),this.finalPath=rr.join(e,`${t}.zip`),yt.rmSync(this.tempPath,{recursive:!0,force:!0}),yt.rmSync(this.finalPath,{recursive:!0,force:!0}),yt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=rr.join(this.tempPath,e);if(yt.existsSync(t))return yt.readFileSync(t)}mkdir(e){yt.mkdirSync(rr.join(this.tempPath,e),{recursive:!0})}cd(e){return new ya(rr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.tempPath,t);yt.writeFileSync(o,n)}close(){let e=new Rk;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();yt.writeFileSync(this.finalPath,t),yt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import gc from"fs";import IA from"body-parser";import Hk from"cors";import Vk from"dedent";import{Router as _k}from"express";import Et from"fs";import{globSync as Mk}from"glob";import tt from"path";import Xp from"fs";import wk from"path";var Ck=new Rl(30,60*1e3),Zp="https://api.momentic.ai",Jp,EA=r=>{Zp=r},em=()=>Zp,tm=()=>Jp;var Xo,Qp,yA,bA=async r=>{if(Jp&&Xo&&yA)return Xo;let e=new tr({baseUrl:Zp,apiKey:r,logger:A});Jp=e;try{let t=await e.getAuthInfo();return Xo=t.orgId,Qp=t.userId,yA=r,Xo}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Ea=()=>{if(!Xo)throw new Error("Your organization ID is invalid.");return Xo},sc=()=>{if(!Qp)throw new Error("Your user ID is invalid.");return Qp};var rm,Yp,TA=(r,e)=>{rm=r,Yp?.abort(),Yp=new AbortController;let t=Yp.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=wk.resolve(r.rootDir,o.envFile);try{if(Xp.lstatSync(i).isSymbolicLink())return;Xp.existsSync(i)&&n.push(i)}catch(a){A.warn({err:a},`Failed to check if env file ${i} exists`)}});try{xk({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){A.error({err:o},"Failed to start config file watchers")}},Xe=()=>rm;function xk({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Xp.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(Ck.increment("setLocalProject")&&A.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.`),rm=e(n.configFilePath))})})}function Je(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ta=_k();function ba(r){let e=Xe(),t=tt.dirname(e.configFilePath);return tt.join(t,...r)}function Ik(r){let e=Xe(),t=tt.dirname(e.configFilePath),n=tt.relative(t,r);return n?n.split(tt.sep):[]}function Pk(r,e){let t=Et.statSync(r),n=Ik(r);return hu.parse({name:e,absolutePath:r,relativePath:n.join(tt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ta.post("/",Je(async(r,e,t)=>{let n;try{n=bh.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ba(n);if(!Et.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(tt.sep)}`});return}if(!Et.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}let a=Xe(),l=Array.from(a.config.exclude??[]).concat(ds),s=Mk("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=tt.join(o,d);return Pk(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Ta.put("/",Je(async(r,e,t)=>{let n;try{n=Th.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ba(n);if(Et.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(tt.sep)}`,pathSegments:n});return}Et.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(tt.sep)}`,pathSegments:n};e.status(201).json(i)}));Ta.patch("/",Je(async(r,e,t)=>{let n,o;try{let s=vh.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=ba(n),a=ba(o);if(!Et.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(tt.sep)}`});return}if(Et.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(tt.sep)}`});return}let l=tt.dirname(a);Et.existsSync(l)||Et.mkdirSync(l,{recursive:!0}),Et.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(tt.sep)} to ${o.join(tt.sep)}`,pathSegments:o};e.status(200).json(c)}));Ta.delete("/",Je(async(r,e,t)=>{let n,o=!0;try{let c=Ah.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=ba(n);if(!Et.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(tt.sep)}`,pathSegments:n});return}if(!Et.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}if(o)Et.rmSync(i,{recursive:!0,force:!0});else{if(Et.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Et.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var nm=Ta;import jk from"events";import PA,{Router as Wk}from"express";import $k from"http";import qk from"path";var lc=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 vA=new lc;import{Router as Nk}from"express";import{existsSync as Dk}from"fs";import kk from"path";import{hostname as Ok}from"os";var Lk="0.0.19",bt=Hl({app:"mobile-desktop-server",hostname:Ok(),disableConsoleLogs:!0}).child({cliVersion:Lk});(async()=>{try{let r=await Fp(bt);r.gitBranchName&&bt.addBinding("branch",r.gitBranchName)}catch{}})();var om=Nk();om.get("/",Je(async(r,e)=>{let t=tm();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));om.post("/upload-url",Je(async(r,e)=>{let t;try{t=_h.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=tm();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=kk.resolve(t.filePath);if(!Dk(o)){e.status(400).json({error:`File not found: ${o}`});return}await xa({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:bt}),e.sendStatus(204)}));var AA=om;import{Router as Uk}from"express";var RA=Uk();RA.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),l={labels:i,modules:[],tests:a};e.status(200).json(l)}));var wA=RA;import{Router as Fk}from"express";var CA=Fk();CA.get("/",(r,e)=>{e.status(200).json({userId:sc(),orgId:Ea()})});var xA=CA;import{Router as Bk}from"express";var cc=Bk();async function zk(r){return(await uA(r,bt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){A.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)}cc.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=await zk(n);e.status(200).json(o)}));cc.get("/:moduleId",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Zt(Xe()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await zp(n,t,A);e.json(o)}catch(o){e.status(400).json({err:o})}}));cc.patch("/:moduleId/metadata",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Mh.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Xe(),o=Zt(n);cA({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:A,project:n}),e.status(201).json({message:"ok"})}));var _A=cc;import{Router as Gk}from"express";import im from"path";var uc=Gk();uc.patch("/:testPath",Je(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=xh.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=Xe(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=Zt(o);await pA({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));uc.post("/",Je((r,e)=>{let t;try{t=Ch.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Jc(n)}catch(m){e.status(400).json({error:m.message});return}let l=Xe(),c=im.join(l.rootDir,...a),{fullPath:s,testId:u}=dA({name:n,description:o,steps:[],settings:i,folder:c}),d=im.basename(s),p=im.relative(l.rootDir,s),g={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(g)}));uc.get("/:fileName",Je(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=Xe(),i=Zt(o),l=await tc(n,bt,i);e.status(200).json(l)}));var MA=uc;var dc=class extends Wo{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Xe();return Xl(t,o,A)}};var OA="10mb";async function LA(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,logLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&EA(n),await bA(t);let s=Ea(),u=sc(),d=r.logger.child({orgId:s,userId:u});TA(i,w=>ha({configFilePath:w}));let p=PA();p.use(Hk()),p.use(IA.json({limit:OA})),p.use(IA.urlencoded({extended:!1,limit:OA}));let g=Wk();if(g.use("/folders",nm),g.use("/entities",wA),g.use("/identify",xA),g.use("/mobile-tests",MA),g.use("/mobile-modules",_A),g.use("/assets",AA),p.use("/api",g),p.use((w,T,x)=>{A.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"),T.on("close",()=>{T.statusCode>=400&&(A.error({url:w.url,method:w.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"),bt.error({url:w.url,method:w.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"))}),x()}),p.use((w,T,x,N)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){x.status(400).send("Client disconnected");return}A.error({stack:w.stack,msg:w.message,err:w,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),bt.error({stack:w.stack,msg:w.message,err:w,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),x.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=PA.static(o,{setHeaders:T=>{T.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(w),p.use("*",(T,x)=>{x.sendFile(qk.join(o,"index.html"))})}let m=$k.createServer(p),h=`http://localhost:${e}`;await new Promise(w=>{try{m.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),w()})}catch(T){T.message.includes("EADDRINUSE")?Kk(e):A.error(`An unexpected error occurred while starting the server: ${T.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:em(),apiKey:t,logger:d},b=new tr(E),{dispose:v}=Dv({baseServer:m,logger:d,authorization:E,globalStateManager:vA,getOrgId:()=>Ea(),androidDriverFactory:async({socket:w,logger:T,creationOpts:x})=>{let N=Math.floor(Math.random()*1e4)+4e4,k=await Yl(N,"appium");return Ca({logger:T,logLevel:a,apiClient:b,creationOpts:x,socket:w,appiumPort:k,onStatusUpdate:q=>{w.emit("connectionStatusUpdate",{message:q})}})},mobileGeneratorFactory:async w=>new Yo({baseUrl:em(),apiKey:t,logger:d}),browserGeneratorFactory:async w=>new qn({},E),browserEnricherFactory:async w=>new Ko(E,new qn({},E)),storageFactory:async w=>new dc(b,w),cacheStorageFactory:async w=>{let T=Xe(),x=await Ql(d,b,T);return oc({orgId:w,client:b,gitMetadata:x,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new qo({httpClient:b,fakerSeed:void 0}),keepSessionAlive:w=>b.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:Xe().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await v(),await Mt.flush()}catch(w){A.error({err:w},"Error during session dispose on SIGUSR2")}try{m.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{A.info("SIGTERM in Momentic mobile app received");try{await v(),await Mt.flush()}finally{m.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{A.info("SIGINT in Momentic mobile app received");try{await v(),await Mt.flush()}finally{m.close(()=>process.exit(0))}})}jk.setMaxListeners(50);process.on("warning",r=>{bt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{bt.error({err:r},"Uncaught exception on mobile-desktop-server"),A.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{bt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),A.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Kk(r){A.error(Vk`Port ${r} is already in use by another process. Please close the other process and try again.
3965
+ `),globalThis.console=e}}var Cp=" ".repeat(6);import{hostname as JD}from"os";var Ct=zl({app:"cli",hostname:JD(),disableConsoleLogs:!0}).child({cliVersion:"0.0.20"});function xp(r){if(!r)return;r=r.toLowerCase();let e=ds.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function Vv({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),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return Hv(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var da=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Ho.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Ho.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Ho.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Ho.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Ho.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Ho.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),QD||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var r0=!1,jv=(()=>{try{return t0("/.dockerenv"),!0}catch{return!1}})();async function Wl(r,e){return ca||r0||jv?!0:(R.flush(),Ct.flush(),await new Promise(n=>setTimeout(n,500)),await ZD({message:r}))}async function Wv(r,e){return ca||jv?e:(await e0({message:r,default:e})).trim()||e}import n0 from"fs";import{tmpdir as o0}from"os";import i0 from"path";import{registry as pa}from"playwright-core/lib/server";import $v from"proper-lockfile";var qv=i0.join(o0(),"momenticBrowserInstallation");var _p=["chrome","chromium","chrome-for-testing"],a0={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Kv={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Yv(r){let e=Kv[a0[r]??""]??"",t=pa.findExecutable(e);return!t||t.installType==="none"?!1:Mp(t)}function Mp(r){let e=r.executablePath();return n0.existsSync(e)}function s0(r,e){let t=Kv[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=pa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Mp(n)))return n}async function l0({browser:r,force:e}){let t=s0(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await pa.installDeps([t],!1),await pa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=pa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Mp(o);)R.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function $l({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?_p:Array.from(new Set(r));try{await $v.lock(qv,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await l0({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await $v.unlock(qv,{realpath:!1})}if(o)throw o}import{createServer as c0}from"http";async function ql(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await u0(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function u0(r){return new Promise((e,t)=>{let n=c0();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import{randomUUID as sU}from"crypto";import{diff as Pye}from"deep-object-diff";import Hye from"yaml";import{z as jye}from"zod";import{execSync as d0}from"child_process";function Gn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,R.debug({postSaveCommand:n},"Executing post-save hook command");try{d0(n,{encoding:"utf-8"})}catch(o){R.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as lye}from"deep-object-diff";import{cloneDeep as uye}from"lodash-es";import{v4 as vye}from"uuid";import Rye from"yaml";import p0 from"@dotenvx/dotenvx";import m0 from"fs";import Xv from"path";function g0(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function h0(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=g0(i);l&&(n[o]=l);continue}let a;try{a=m0.readFileSync(Xv.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&R.debug(n,"Set environment variables with interpolation from project configuration"),n}function f0(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=p0.config({path:Xv.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Kl(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=h0({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=f0({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as M0,readFileSync as I0,readdirSync as P0,writeFileSync as O0}from"fs";import{globSync as L0}from"glob";import Hn,{dirname as eA}from"path";import{cwd as Np}from"process";import tA from"yaml";import{z as be}from"zod";import Jv from"fs";import{globSync as S0}from"glob";import ma from"path";import y0 from"yaml";import{z as Ip}from"zod";var Qv=!1,Pp=["**/*.test.yaml","**/*.module.yaml"],Op=Ip.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Lp=50,E0=Ip.object({fileType:Ip.nativeEnum(ye)});function Zt(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Pp,o=Array.from(r.config.exclude??[]).concat(cs),i=S0(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Lp,nodir:!0});for(let a of i){let l=b0(r.rootDir,a,t,e?bn:R);l&&(t.duplicateEntities[l.id]=l.paths)}return Qv=!0,t}function b0(r,e,t,n){let o=ma.join(r,e),i=T0(o,n);if(!i)return;let a=v0(i,o,n);if(!a)return;let l=E0.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=A0(o,n);if(!s)return;let u=R0(e,o,s);switch(c){case ye.TEST:try{return w0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ye.MODULE:try{return C0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case ye.MOBILE_TEST:try{return _0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case ye.MOBILE_MODULE:try{return x0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function T0(r,e){try{return Jv.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function v0(r,e,t){try{let n=y0.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function A0(r,e){try{return Jv.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function R0(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ma.sep,fullPathSegments:e.split(ma.sep),relativePathSegments:r.split(ma.sep),fileName:ma.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function w0(r,e,t,n,o){let i=uo.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:ye.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function C0(r,e,t,n,o){let i=Nt.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:ye.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!Qv&&zr(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function x0(r,e,t,n,o){let i=Ri.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let l=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:ye.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function _0(r,e,t,n,o){let i=ar.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:ye.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Vo="momentic.config.yaml",Zv="momentic.workspace.yaml",N0=be.object({projects:be.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),D0=be.union([be.string(),be.object({fromFile:be.string(),json:be.boolean().optional()})]),k0=be.object({name:Op,baseUrl:be.string().optional().describe("Optional for mobile tests"),envFile:be.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:be.record(be.string(),D0).optional(),inheritFromShell:be.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:dn.optional().describe("deprecated: use project-level configuration only")}),U0=be.object({postSave:be.string().optional()}),F0=be.object({name:Op,include:be.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:be.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:be.string().optional(),reporterDir:be.string().optional(),outputDir:be.string().optional(),retries:be.number().optional().describe("number of retries per test"),parallel:be.number().optional().describe("degree of parallelism"),environments:be.array(k0).optional(),gitMainBranch:be.string().optional(),gitProtectedBranches:be.string().array().optional(),ai:fu.optional(),browser:dn.optional(),emulator:au.optional(),advanced:Su.optional(),hooks:U0.optional()});function rA(r,e){let t;try{t=I0(r,"utf-8")}catch(o){R.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=tA.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){R.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Dp(r){let e=rA(r,"project configuration");if(e!==void 0)try{return F0.parse(e)}catch(t){R.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function B0(r){let e=rA(r,"workspace configuration");if(e!==void 0)try{return N0.parse(e)}catch(t){R.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function z0(){let r=[],e=Np(),t=Hn.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Hn.basename(e);if(ls.includes(i))return R.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of P0(e))if(a.endsWith(Vo)){let l=Hn.join(e,a),c=Dp(l);c&&r.push({configFilePath:l,config:c,rootDir:eA(l)})}if(r.length)return r;if(e=Hn.dirname(e),e===t)break}return r}function ga(r={}){let{configFilePath:e,nameFilter:t}=r,n=H0(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
3966
+ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function G0(r){let e=B0(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Vo}`)),n=L0(t,{absolute:!1,cwd:Np(),dotRelative:!1,maxDepth:Lp,nodir:!0}),o=[];for(let i of n){let a=Hn.join(Np(),i),l=Dp(a);l&&o.push({configFilePath:a,config:l,rootDir:eA(a)})}return o}function H0(r){if(r){r=Hn.resolve(r);let t=Dp(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Hn.dirname(r)}]}if(M0(Zv)){let t=G0(Zv);if(t)return t}return z0()}function nA(r,e){let t=tA.stringify(r);O0(e,t)}import{z as kp}from"zod";var oA="test-results";var _Ee=kp.object({width:kp.number(),height:kp.number()});import{execFile as V0}from"node:child_process";import{promisify as j0}from"node:util";import W0 from"simple-git";var Te=W0(),iA=j0(V0);async function $0(r){let e=await ve(r,Te.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
3967
+ `)){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 q0(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 iA("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await iA("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function K0(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return q0(r,e,t);if(o)return}catch{}}function Yl(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 ve(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function Y0(){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 X0(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.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{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 J0(r){let[e,t,n]=await Promise.all([ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]);return{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 Q0(r){let[e,t,n,o]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Yl(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function Z0(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Yl(o):void 0;return{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?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function ek(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Yl(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function tk(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([ve(r,Te.revparse(["HEAD"])),ve(r,Te.revparse(["--short","HEAD"])),ve(r,Te.revparse(["--abbrev-ref","HEAD"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"])),e?ve(r,Te.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),$0(r)]),d=s?await ve(r,Te.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Yl(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await K0(r,i,u)??E??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function rk(){let r=process.env._HEAD_REPO_URL;return{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 nk(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Up(r,e){let t=Y0();if(!t)return tk(r,e);switch(t){case"GithubActions":return X0(r);case"GitlabCI":return J0(r);case"CircleCI":return Q0(r);case"Buildkite":return Z0(r);case"AzureDevOps":return ek(r);case"GCPCloudBuild":return rk()}}async function ok(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 ik(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 ak(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await ik(r,e,n,o,t)}else if(t.gitlabProjectPath)return await ok(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Xl(r,e,t){let n=await nk(t),o=await Up(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 ak(r,e,i);return{...n,...o,...a}}import{diff as aA}from"deep-object-diff";import Vn from"fs";import{cloneDeep as sk}from"lodash-es";import Fp from"path";import{v4 as YEe}from"uuid";import Jl from"yaml";function sA({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"),l=Jl.parse(a),c={...r,schemaVersion:e},s=Tn({fileType:ye.MOBILE_MODULE,...Ri.parse(c),steps:Yt.array().parse(r.steps)}),u=aA(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=Jl.stringify(s);Vn.writeFileSync(i,d,"utf-8"),Gn(i,n.config)}function lA({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=ha(i,o),l={...a,...e},c=Tn({fileType:ye.MOBILE_MODULE,...Za.parse(l)}),s=aA(c,a);if(s&&Object.keys(s).length===0)return;let u=Jl.stringify(c);Vn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${zr(e.name)}.module.yaml`;if(d=Fp.join(Fp.dirname(i),p),Vn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Vn.renameSync(i,d)}Gn(d||i,n.config)}function ha(r,e){let t=Vn.readFileSync(r,"utf-8"),n=Jl.parse(t);try{return{...Za.parse(n),name:Fp.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 Bp(r,e,t,n){let o=ha(r.fullFilePath,t),{resolvedSteps:i}=await Ts({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async l=>{let c=e.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${l}`);return ha(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=sk(a)),a}async function cA(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Bp(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as lk}from"crypto";import jn from"fs";import zp from"path";import Ql from"yaml";function uA({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${zr(r)}.test.yaml`,l=zp.join(o,a);if(jn.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:ye.MOBILE_TEST,id:lk(),description:e,schemaVersion:Ic,settings:n,steps:t},s=Ql.stringify(c);return jn.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function ck(r){if(!jn.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=jn.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
3968
+ `),t=Ql.parse(e),n=rs.parse(t);if(n.fileType!==ye.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function Zl(r,e,t){let n=ck(r),o;try{o=ar.parse(n)}catch(l){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedStepLists:i}=await jf({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async l=>{let c=t.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Mobile module ${l} not found`);return ha(c,e)}});return{...o,steps:i.steps}}async function dA({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=zp.isAbsolute(r)?r:zp.join(n,r);if(!jn.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=jn.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
3969
+ `),c=Ql.parse(l),s=rs.parse(c);if(s.fileType!==ye.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await Rn({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Ql.stringify(rs.parse(d));for(let m of u?.moduleUpdates??[])sA({content:m,schemaVersion:Ic,momenticFiles:i,project:o});jn.writeFileSync(a,p,"utf-8"),Gn(a,o.config)}import{randomUUID as uk}from"crypto";import Pr from"fs";import Wn from"path";var pA={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 dk(r,e,t){if(pA[t]){let i=pA[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 mA=new Set([".DS_Store","__MACOSX"]);function gA(r,e,t){let n=uk(),o=r.child({runGroupId:n});Pr.rmSync(e,{recursive:!0,force:!0});let i=Pr.readdirSync(t).filter(s=>!mA.has(s)).map(s=>Wn.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Pr.mkdirSync(e,{recursive:!0});let a=Wn.join(i[0],"metadata.json"),l={...Oi.parse(JSON.parse(Pr.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=Wn.join(s,"runs");if(!Pr.existsSync(u))continue;let d=Pr.readdirSync(u);for(let g of d){if(mA.has(g))continue;let h=Wn.join(u,g),f=Wn.join(e,"runs",g);Pr.cpSync(h,f,{recursive:!0})}let p=Wn.join(s,"metadata.json"),m=Oi.parse(JSON.parse(Pr.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=dk(l,m,h)}}let c=Wn.join(e,"metadata.json");Pr.writeFileSync(c,JSON.stringify(l,null,2))}import fA from"adm-zip";import $p from"fs";import{z as Vp}from"zod";var D="v1",Gp="mobile-cli",fa="0.0.20";var pk=9e4,mk=3,gk=1500,hk=15e3,er=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function fk(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Hp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return fa&&(e[Ph]=fa),Gp&&(e[Oh]=Gp),e}async sendRequest(e,t){let{retries:n=mk,requestTimeoutMs:o=pk,initialRetryDelayMs:i=gk,maxRetryDelayMs:a=hk}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof er&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new qr),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await fk(s);throw new er(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Tr=class extends Hp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var tr=class extends Tr{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${D}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return Xh.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${D}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $h.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${D}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Bh.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${D}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Gh.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${D}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Hh.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${D}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Fh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${D}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Yh.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${D}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Jh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${D}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return pf.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${D}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${D}/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(`/${D}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Qh.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${D}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return fg.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${D}/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(`/${D}/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(`/${D}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Zh.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${D}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ef.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${D}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return tf.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${D}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return hf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${D}/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(`/${D}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${D}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${D}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Au.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(`/${D}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Pi.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${D}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Au.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${D}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Vp.record(Vp.string(),Vp.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${D}/quarantine`,{method:"GET"});return nf.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${D}/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(`/${D}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${D}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return of.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${D}/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(`/${D}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return af.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${D}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${D}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return sf.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${D}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function jp(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var ec=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var jo=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 Sk,en as yk}from"@faker-js/faker";var Wo="v1",$o=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 Sk({locale:yk}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Wo}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof er?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as Ek}from"zod";var $n=class extends Tr{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Tg.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${D}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:fa,...e},signal:t.abortSignal});return bg.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${D}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Ek.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(`/${D}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return kh.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(`/${D}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Eu.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Dh.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return Nh.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(`/${D}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Eu.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${D}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Lh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${D}/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(`/${D}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Lc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${D}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Uh.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${D}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Pc.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Zm.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${D}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Fc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${D}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Og.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ym.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Qm.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Jm.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${D}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return vm.parse(n)}};var qo=class extends Tr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${D}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Am.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function hA(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var tc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await hA(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 Ko=class extends Tr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ng.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ug.parse(o)}};function rc({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new fs:new Wp(r,e,t,n)}var Wp=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=bu(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&_u({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Rn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import nc from"path";function bk(r){let e=new fA,t=nc.join(r,"metadata.json"),n=Oi.parse(JSON.parse($p.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of $p.readdirSync(nc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new fA(nc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(nc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function oc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!$p.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new tc(e);try{let{runGroupId:i,buffer:a}=bk(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;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 Tk from"adm-zip";import yt from"fs";import rr from"path";var Sa=class r{constructor(e){this.filePath=e;yt.rmSync(this.filePath,{recursive:!0,force:!0}),yt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(rr.join(this.filePath,e))}mkdir(e){yt.mkdirSync(rr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=rr.join(this.filePath,e);if(yt.existsSync(t))return yt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.filePath,t);try{yt.writeFileSync(o,n)}catch{}}createRunArchive(e){return new qp(rr.join(this.filePath,"runs"),e)}},qp=class{constructor(e,t){this.filePath=e;this.tempPath=rr.join(e,`.${t}`),this.finalPath=rr.join(e,`${t}.zip`),yt.rmSync(this.tempPath,{recursive:!0,force:!0}),yt.rmSync(this.finalPath,{recursive:!0,force:!0}),yt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=rr.join(this.tempPath,e);if(yt.existsSync(t))return yt.readFileSync(t)}mkdir(e){yt.mkdirSync(rr.join(this.tempPath,e),{recursive:!0})}cd(e){return new Sa(rr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.tempPath,t);yt.writeFileSync(o,n)}close(){let e=new Tk;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();yt.writeFileSync(this.finalPath,t),yt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import pc from"fs";import MA from"body-parser";import Bk from"cors";import zk from"dedent";import{Router as wk}from"express";import Et from"fs";import{globSync as Ck}from"glob";import tt from"path";import Yp from"fs";import vk from"path";var Ak=new Al(30,60*1e3),Qp="https://api.momentic.ai",Xp,yA=r=>{Qp=r},Zp=()=>Qp,em=()=>Xp;var Yo,Jp,SA,EA=async r=>{if(Xp&&Yo&&SA)return Yo;let e=new tr({baseUrl:Qp,apiKey:r,logger:R});Xp=e;try{let t=await e.getAuthInfo();return Yo=t.orgId,Jp=t.userId,SA=r,Yo}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ya=()=>{if(!Yo)throw new Error("Your organization ID is invalid.");return Yo},ic=()=>{if(!Jp)throw new Error("Your user ID is invalid.");return Jp};var tm,Kp,bA=(r,e)=>{tm=r,Kp?.abort(),Kp=new AbortController;let t=Kp.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=vk.resolve(r.rootDir,o.envFile);try{if(Yp.lstatSync(i).isSymbolicLink())return;Yp.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Rk({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},Xe=()=>tm;function Rk({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Yp.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(Ak.increment("setLocalProject")&&R.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),tm=e(n.configFilePath))})})}function Je(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ba=wk();function Ea(r){let e=Xe(),t=tt.dirname(e.configFilePath);return tt.join(t,...r)}function xk(r){let e=Xe(),t=tt.dirname(e.configFilePath),n=tt.relative(t,r);return n?n.split(tt.sep):[]}function _k(r,e){let t=Et.statSync(r),n=xk(r);return mu.parse({name:e,absolutePath:r,relativePath:n.join(tt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ba.post("/",Je(async(r,e,t)=>{let n;try{n=Eh.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ea(n);if(!Et.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(tt.sep)}`});return}if(!Et.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}let a=Xe(),l=Array.from(a.config.exclude??[]).concat(cs),s=Ck("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=tt.join(o,d);return _k(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));ba.put("/",Je(async(r,e,t)=>{let n;try{n=bh.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ea(n);if(Et.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(tt.sep)}`,pathSegments:n});return}Et.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(tt.sep)}`,pathSegments:n};e.status(201).json(i)}));ba.patch("/",Je(async(r,e,t)=>{let n,o;try{let s=Th.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=Ea(n),a=Ea(o);if(!Et.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(tt.sep)}`});return}if(Et.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(tt.sep)}`});return}let l=tt.dirname(a);Et.existsSync(l)||Et.mkdirSync(l,{recursive:!0}),Et.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(tt.sep)} to ${o.join(tt.sep)}`,pathSegments:o};e.status(200).json(c)}));ba.delete("/",Je(async(r,e,t)=>{let n,o=!0;try{let c=vh.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=Ea(n);if(!Et.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(tt.sep)}`,pathSegments:n});return}if(!Et.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}if(o)Et.rmSync(i,{recursive:!0,force:!0});else{if(Et.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Et.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var rm=ba;import Gk from"events";import IA,{Router as Hk}from"express";import Vk from"http";import jk from"path";var ac=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 TA=new ac;import{Router as Pk}from"express";import{existsSync as Ok}from"fs";import Lk from"path";import{hostname as Mk}from"os";var Ik="0.0.20",bt=zl({app:"mobile-desktop-server",hostname:Mk(),disableConsoleLogs:!0}).child({cliVersion:Ik});(async()=>{try{let r=await Up(bt);r.gitBranchName&&bt.addBinding("branch",r.gitBranchName)}catch{}})();var nm=Pk();nm.get("/",Je(async(r,e)=>{let t=em();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));nm.post("/upload-url",Je(async(r,e)=>{let t;try{t=xh.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=em();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=Lk.resolve(t.filePath);if(!Ok(o)){e.status(400).json({error:`File not found: ${o}`});return}await Ca({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:bt}),e.sendStatus(204)}));var vA=nm;import{Router as Nk}from"express";var AA=Nk();AA.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),l={labels:i,modules:[],tests:a};e.status(200).json(l)}));var RA=AA;import{Router as Dk}from"express";var wA=Dk();wA.get("/",(r,e)=>{e.status(200).json({userId:ic(),orgId:ya()})});var CA=wA;import{Router as kk}from"express";var sc=kk();async function Uk(r){return(await cA(r,bt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}sc.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=await Uk(n);e.status(200).json(o)}));sc.get("/:moduleId",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Zt(Xe()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Bp(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));sc.patch("/:moduleId/metadata",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=_h.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Xe(),o=Zt(n);lA({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));var xA=sc;import{Router as Fk}from"express";import om from"path";var lc=Fk();lc.patch("/:testPath",Je(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Ch.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=Xe(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=Zt(o);await dA({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));lc.post("/",Je((r,e)=>{let t;try{t=wh.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Xc(n)}catch(g){e.status(400).json({error:g.message});return}let l=Xe(),c=om.join(l.rootDir,...a),{fullPath:s,testId:u}=uA({name:n,description:o,steps:[],settings:i,folder:c}),d=om.basename(s),p=om.relative(l.rootDir,s),m={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(m)}));lc.get("/:fileName",Je(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=Xe(),i=Zt(o),l=await Zl(n,bt,i);e.status(200).json(l)}));var _A=lc;var cc=class extends jo{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Xe();return Kl(t,o,R)}};var PA="10mb";async function OA(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,logLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&yA(n),await EA(t);let s=ya(),u=ic(),d=r.logger.child({orgId:s,userId:u});bA(i,A=>ga({configFilePath:A}));let p=IA();p.use(Bk()),p.use(MA.json({limit:PA})),p.use(MA.urlencoded({extended:!1,limit:PA}));let m=Hk();if(m.use("/folders",rm),m.use("/entities",RA),m.use("/identify",CA),m.use("/mobile-tests",_A),m.use("/mobile-modules",xA),m.use("/assets",vA),p.use("/api",m),p.use((A,T,x)=>{R.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),T.on("close",()=>{T.statusCode>=400&&(R.error({url:A.url,method:A.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"),bt.error({url:A.url,method:A.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"))}),x()}),p.use((A,T,x,N)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){x.status(400).send("Client disconnected");return}R.error({stack:A.stack,msg:A.message,err:A,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),bt.error({stack:A.stack,msg:A.message,err:A,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),x.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=IA.static(o,{setHeaders:T=>{T.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(A),p.use("*",(T,x)=>{x.sendFile(jk.join(o,"index.html"))})}let g=Vk.createServer(p),h=`http://localhost:${e}`;await new Promise(A=>{try{g.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),A()})}catch(T){T.message.includes("EADDRINUSE")?Wk(e):R.error(`An unexpected error occurred while starting the server: ${T.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:Zp(),apiKey:t,logger:d},b=new tr(E),{dispose:v}=Nv({baseServer:g,logger:d,authorization:E,globalStateManager:TA,getOrgId:()=>ya(),androidDriverFactory:async({socket:A,logger:T,creationOpts:x})=>{let N=Math.floor(Math.random()*1e4)+4e4,U=await ql(N,"appium");return wa({logger:T,logLevel:a,apiClient:b,creationOpts:x,socket:A,appiumPort:U,onStatusUpdate:Y=>{A.emit("connectionStatusUpdate",{message:Y})}})},mobileGeneratorFactory:async A=>new Ko({baseUrl:Zp(),apiKey:t,logger:d}),browserGeneratorFactory:async A=>new $n({},E),browserEnricherFactory:async A=>new qo(E,new $n({},E)),storageFactory:async A=>new cc(b,A),cacheStorageFactory:async A=>{let T=Xe(),x=await Xl(d,b,T);return rc({orgId:A,client:b,gitMetadata:x,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new $o({httpClient:b,fakerSeed:void 0}),keepSessionAlive:A=>b.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:Xe().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await v(),await Mt.flush()}catch(A){R.error({err:A},"Error during session dispose on SIGUSR2")}try{g.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await v(),await Mt.flush()}finally{g.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await v(),await Mt.flush()}finally{g.close(()=>process.exit(0))}})}Gk.setMaxListeners(50);process.on("warning",r=>{bt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{bt.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{bt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Wk(r){R.error(zk`Port ${r} is already in use by another process. Please close the other process and try again.
3970
3970
  Using Bash on MacOS or Linux:
3971
3971
  lsof -t -i :58888 | xargs kill -9
3972
3972
 
3973
3973
  Using Command Prompt on Windows:
3974
3974
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3975
- `)}import dU from"open";import hc from"path";import{fileURLToPath as pU}from"url";import{InvalidArgumentError as am,Option as Tt}from"@commander-js/extra-typings";import{z as Yk}from"zod";var NA=58890;function Xk(r){let e=parseInt(r,10);if(isNaN(e))throw new am("Not a number.");return e}var va=new Tt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new am("API key is required.");return r}).makeOptionMandatory(),sm=new Tt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Aa=new Tt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Yk.string().url().parse(r),r}catch{throw new am("Not a valid URL.")}}),lm=new Tt("-y, --yes","Skip all confirmation prompts.").env("CI"),cm=new Tt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches, which are specified in your momentic.config.yaml.").env("CI"),um=new Tt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),dm=new Tt("--tag <tag>","Tag identifier for the asset."),DA=new Tt("--channel <channel>","Channel name for the asset."),kA=new Tt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),UA=new Tt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),FA=new Tt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Xk),pm=new Tt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),BA=new Tt("--upload-results","Upload test results to Momentic Cloud.").default(!1),mm=new Tt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),zA=new Tt("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as iU}from"crypto";import{existsSync as aU}from"fs";import gm from"fs";import Ra from"path";import{cwd as Qk}from"process";async function GA({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>gm.existsSync(p)),d=Qk();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:
3975
+ `)}import lU from"open";import mc from"path";import{fileURLToPath as cU}from"url";import{InvalidArgumentError as im,Option as Tt}from"@commander-js/extra-typings";import{z as $k}from"zod";var LA=58890;function qk(r){let e=parseInt(r,10);if(isNaN(e))throw new im("Not a number.");return e}var Ta=new Tt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new im("API key is required.");return r}).makeOptionMandatory(),am=new Tt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),va=new Tt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return $k.string().url().parse(r),r}catch{throw new im("Not a valid URL.")}}),sm=new Tt("-y, --yes","Skip all confirmation prompts.").env("CI"),lm=new Tt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches, which are specified in your momentic.config.yaml.").env("CI"),cm=new Tt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),um=new Tt("--tag <tag>","Tag identifier for the asset."),NA=new Tt("--channel <channel>","Channel name for the asset."),DA=new Tt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),kA=new Tt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),UA=new Tt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(qk),dm=new Tt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),FA=new Tt("--upload-results","Upload test results to Momentic Cloud.").default(!1),pm=new Tt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),BA=new Tt("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as rU}from"crypto";import{existsSync as nU}from"fs";import mm from"fs";import Aa from"path";import{cwd as Yk}from"process";async function zA({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>mm.existsSync(p)),d=Yk();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:
3976
3976
  - ${r.join(`
3977
3977
  - `)}
3978
- `),r.forEach(p=>{if(!gm.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=gm.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Ra.resolve(p);Object.values(e.mobileTests).filter(f=>m?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await ql("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=Ra.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Ra.relative(t.rootDir,u),p=await tc(u,a,e),g=Ra.basename(u,Ra.extname(u));return{id:p.id,name:g,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!l[p.id],quarantinedReason:l[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as Zk}from"lodash-es";async function HA(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:Zk(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(d.loggerBindings||{}),g=1+(c.settings?.retries??1);try{for(let m=0;m<g;m++){let h=new Date,f=await eU({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:m,totalAttempts:g},fixtures:{...t,logger:p},inputs:e,options:o}),E=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:m+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(m!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:m+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{s?.pop()}}async function eU(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:l}=r,{attemptNumber:c,totalAttempts:s}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:v}=a,{alwaysSaveCache:w,noCache:T,logLevel:x}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let N={...a.project.config.emulator,...t.settings?.emulator},k=oc({orgId:u,client:p,gitMetadata:d,alwaysSaveCache:w,noCache:T}),q=new Wo(p,u),ke=new Yo(p),te={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g},ie=new qn({},te),ut=new Ko(te,ie),M=new qo({httpClient:p,fakerSeed:void 0}),V=Math.floor(Math.random()*1e4)+4e4,re=await Yl(V,"appium"),Me=await Ca({apiClient:p,logger:g,logLevel:x,creationOpts:{apkToInstall:f?{channel:f,tag:E}:void 0,region:N.region},onStatusUpdate:Zo=>{g.debug({status:Zo},"Limbar emulator status update")},appiumPort:re}),Ae=await e.startAttempt({emulatorName:Me.emulatorName}),xt=g.child(Ae.loggerBindings||{}),dt=v||t.settings?.defaultEnv,Re;dt&&(Re=Xl(dt,b,xt).variables);let We=new uo({variablesFromEnvironment:Re??{},envName:dt,testName:t.name}),an=await Bo.init({driver:Me.driver,generator:ke,logger:xt,orgId:u,adbPort:Me.adbTunnelPort,options:{emulator:N},fixtures:{storage:q,browserEnricher:ut,browserGenerator:ie,localCodeEvalTools:M,testContext:We}}),vr;try{vr=await Vl({containerName:"mobile-test",fixtures:{controller:an,logger:xt,cacheStorage:k,usageTracker:m},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Ae})}finally{await Me.cleanup()}return await Ae.finish({logger:xt,results:vr.results,status:vr.status}),vr}import{randomUUID as tU}from"crypto";import{debounce as rU}from"ts-debounce";var wa="0.0.19";var pc="assets";function nU(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 oU(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var hm=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.commandTracer=new So("command")}children=[];commandTracer;finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${pc}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${pc}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:oU(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}async startSubSteps(){let e=new Jo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Jo=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(`${pc}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new hm(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:nU(e.status),finishedAt:e.finishedAt}))))}},fm=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")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,l={...this.metadata,status:n,finishedAt:new Date,results:Wl(o,t),beforeResults:i?Wl(i,t):void 0,afterResults:a?Wl(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Jo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Jo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Jo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${pc}/${t}.jpeg`)}},Sm=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){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 t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=tU(),o={id:n,schemaVersion:un,runAttemptSchemaVersion:Af,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=rU(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new fm(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},mc=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 l={...i,id:t,trigger:Ut.CLI,startedAt:new Date,status:"RUNNING",cliVersion:wa,labels:a??[]},c=new ya(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,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:wa,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 Sm(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function VA(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 jA(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:l}=t,{orgId:c,runGroupId:s,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;aU(d)&&A.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await VA(l,a,e.ignoreQuarantine),m=Zt(i),h=await GA({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:A,quarantinedTestReasons:g}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),E=await mc.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],v=new Date,w=new Set,T=async()=>sU({runResults:b,startTime:v,ranTests:w,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],N=async()=>{A.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(x.map(te=>te())),process.exit(1)};process.once("SIGINT",N);let k={};for(let te=0;te<h.length;te++){let ie=Object.values(k);ie.length===p&&await Promise.race(ie.map(V=>V.promise));let ut=h[te],M=`test-${te}`;k[M]={done:!1,promise:(async({testDefinition:V})=>{w.add(M);let re=V.relativeFilePath.includes("..")?V.fullFilePath:V.relativeFilePath;pa({status:"START",testLogRef:re,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length});let Ce=setInterval(()=>pa({status:"RUN",testLogRef:re,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Me=iU(),Ae=f.child({testId:V.id,runId:Me}),xt=new _s({logger:Ae,reporter:new rc(a),runType:"mobile-test-run",runId:Me,testMetadata:V,suiteMetadata:void 0});try{let dt=await HA({metadata:{...o,runId:Me},fixtures:{...t,tracer:E,logger:Ae,usageTracker:xt},inputs:{...n,project:i,testDefinition:V,channel:n.channel??V.settings?.defaultChannel,tag:n.tag??V.settings?.defaultTag,logUpdate:(Re,We)=>pa({status:Re,testLogRef:re,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length,additionalText:We}),runSigIntHandlers:x},options:e});pa({status:dt.status,testLogRef:re,getRunningTestsCount:()=>w.size,getTotalTestsCount:()=>h.length}),b.push(dt)}catch(dt){let Re=`Encountered unexpected fatal error when running test '${V.name}': ${dt.message}`;A.error(Re),Ae.error(Re)}finally{clearInterval(Ce),k[M].done=!0,delete k[M]}await xt.flush(l)})({testDefinition:ut})}}await Promise.allSettled(Object.values(k).map(te=>te.promise));let ke=b.some(te=>te.status==="FAILED"&&!te.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ke}),process.off("SIGINT",N),T()}async function sU({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=jv({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${xp}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return A.log(""),o?(A.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await ac({client:n,consoleLogger:A,resultsPath:i})):A.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),l}async function ym(){Pf(),Xv("Chromium")||(ua?(await ql("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Kl({rawBrowsers:["chromium"],force:!1,all:!1})):(A.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)))}xb({serviceName:"mobile-cli"});Ct.setApp("mobile-cli");var on=new lU;on.name("momentic-mobile").description("Momentic Mobile CLI").version(wa);var mU=on.command("assets").description("Manage mobile testing assets");mU.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(va).addOption(Aa).addOption(dm).addOption(kA).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=hc.resolve(r);gc.existsSync(a)||(A.error(`File not found: ${a}`),process.exit(1));let l=new tr({baseUrl:n,apiKey:t,logger:A});/\.apk$/i.test(a)||(A.error(`File is not an APK file: ${a}`),process.exit(1)),await xa({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:A})});on.command("app").addOption(va).addOption(Aa).addOption(lm).addOption(sm).addOption(mm).addOption(cm).addOption(um).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=_p(r.logLevel);Ct.setApp("mobile-desktop-server");let l=new tr({baseUrl:t,apiKey:e,logger:Ct});await Wp({client:l,skipPrompts:n}),A.debug("API key check complete");let c=pU(import.meta.url),s=hc.dirname(c),u=hc.resolve(s,"..","static");await ym(),A.debug({appiumHome:Ni},"Resolved resource paths");let d=ha({configFilePath:r.config}),p=NA;await LA({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,logLevel:a,logger:Ct,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${p}`;A.info(`Local app started on: ${g}`),await dU(g)});var WA=on.command("results").description("Merge and upload test results.");WA.command("merge").description("Merge test results files.").addOption(pm).addArgument(new Em("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(A.error("Output directory is required."),process.exit(1)),gc.existsSync(r)||(A.warn("Results path does not exist, skipping merge."),process.exit(0)),gc.existsSync(t)&&A.warn(`Output directory ${t} already exists, removing before merging...`),hA(Ct,t,r),Qo(),process.exit(0)});var gU=new Em("<results>","Path to the results archive.").argRequired();WA.command("upload").description("Upload test results to Momentic cloud.").addOption(va).addOption(Aa).addArgument(gU).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ct,i=new tr({baseUrl:n,apiKey:t,logger:o});await ac({consoleLogger:A,resultsPath:r,client:i}),Qo(),process.exit(0)});var hU=on.command("run").alias("test").description("Run tests on the local machine");hU.addOption(va).addOption(Aa).addOption(sm).addOption(lm).addOption(FA).addOption(mm).addOption(cm).addOption(um).addOption(pm).addOption(BA).addOption(zA).addOption(dm).addOption(DA).addOption(UA).addArgument(new Em("<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,l=_p(e.logLevel);await ym(),A.debug({appiumHome:Ni},"Resolved resource paths");let c=ha({configFilePath:e.config}),s=a??c.config.outputDir??iA,u=e.parallel??c.config.parallel??1;A.debug("Checking API key and dependencies");let d=new tr({baseUrl:n,apiKey:t,logger:A}),{orgId:p,userId:g}=await Wp({client:d,skipPrompts:e.yes});A.debug("API key check and browser installation complete");let m=uU(),h=Ct.child({runGroupId:m,orgId:p,userId:g}),f=await Ql(Ct,d,c);h.debug(f,"Got local git metadata");try{let E=await jA({options:{...e,outputDir:s,parallel:u,logLevel:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:m,orgId:p}});Qo(),E.failed>0?process.exit(1):process.exit(0)}catch(E){A.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),A.error(E),Ct.error({err:E},"Failed to run tests locally"),Qo(),process.exit(1)}});on.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new cU("--name <name>","Name of the project")).action(async r=>{A.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
3979
- `),A.info("This wizard will help you bootstrap a new Momentic project."),gc.existsSync(jo)&&(A.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await $v("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Op};oA(t,jo),A.success(`Initialized Momentic project file at ${hc.resolve(jo)}`)});on.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${Mp.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(A.error("No browsers specified"),process.exit(1)),await Kl({rawBrowsers:r,force:e.force,all:e.all})});async function Qo(){try{await Mt.flush(),wv()}catch{}}async function fU(){try{await on.parseAsync(process.argv),Qo()}catch(r){Ct.error({err:r},"Uncaught error in CLI"),A.error(r),Qo(),process.exit(1)}}fU();
3978
+ `),r.forEach(p=>{if(!mm.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=mm.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Aa.resolve(p);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Wl("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=Aa.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Aa.relative(t.rootDir,u),p=await Zl(u,a,e),m=Aa.basename(u,Aa.extname(u));return{id:p.id,name:m,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!l[p.id],quarantinedReason:l[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as Xk}from"lodash-es";async function GA(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:Xk(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(d.loggerBindings||{}),m=1+(c.settings?.retries??1);try{for(let g=0;g<m;g++){let h=new Date,f=await Jk({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:g,totalAttempts:m},fixtures:{...t,logger:p},inputs:e,options:o}),E=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(g!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:g+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{s?.pop()}}async function Jk(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:l}=r,{attemptNumber:c,totalAttempts:s}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:m,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:v}=a,{alwaysSaveCache:A,noCache:T,logLevel:x}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let N={...a.project.config.emulator,...t.settings?.emulator},U=rc({orgId:u,client:p,gitMetadata:d,alwaysSaveCache:A,noCache:T}),Y=new jo(p,u),ke=new Ko(p),te={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m},ie=new $n({},te),ut=new qo(te,ie),M=new $o({httpClient:p,fakerSeed:void 0}),V=Math.floor(Math.random()*1e4)+4e4,re=await ql(V,"appium"),Me=await wa({apiClient:p,logger:m,logLevel:x,creationOpts:{apkToInstall:f?{channel:f,tag:E}:void 0,region:N.region},onStatusUpdate:Qo=>{m.debug({status:Qo},"Limbar emulator status update")},appiumPort:re}),Ae=await e.startAttempt({emulatorName:Me.emulatorName}),xt=m.child(Ae.loggerBindings||{}),dt=v||t.settings?.defaultEnv,Re;dt&&(Re=Kl(dt,b,xt).variables);let We=new co({variablesFromEnvironment:Re??{},envName:dt,testName:t.name}),an=await Fo.init({driver:Me.driver,generator:ke,logger:xt,orgId:u,adbPort:Me.adbTunnelPort,options:{emulator:N},fixtures:{storage:Y,browserEnricher:ut,browserGenerator:ie,localCodeEvalTools:M,testContext:We}}),vr;try{vr=await Gl({containerName:"mobile-test",fixtures:{controller:an,logger:xt,cacheStorage:U,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Ae})}finally{await Me.cleanup()}return await Ae.finish({logger:xt,results:vr.results,status:vr.status}),vr}import{randomUUID as Qk}from"crypto";import{debounce as Zk}from"ts-debounce";var Ra="0.0.20";var uc="assets";function eU(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 tU(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var gm=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.commandTracer=new fo("command")}children=[];commandTracer;finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${uc}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${uc}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:tU(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}async startSubSteps(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Xo=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(`${uc}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new gm(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:eU(e.status),finishedAt:e.finishedAt}))))}},hm=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")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,l={...this.metadata,status:n,finishedAt:new Date,results:Vl(o,t),beforeResults:i?Vl(i,t):void 0,afterResults:a?Vl(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${uc}/${t}.jpeg`)}},fm=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){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 t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=Qk(),o={id:n,schemaVersion:un,runAttemptSchemaVersion:vf,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Zk(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new hm(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},dc=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 l={...i,id:t,trigger:Ut.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Ra,labels:a??[]},c=new Sa(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,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:Ra,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 fm(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function HA(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 VA(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:l}=t,{orgId:c,runGroupId:s,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;nU(d)&&R.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await HA(l,a,e.ignoreQuarantine),g=Zt(i),h=await zA({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:R,quarantinedTestReasons:m}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),E=await dc.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],v=new Date,A=new Set,T=async()=>oU({runResults:b,startTime:v,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],N=async()=>{R.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(x.map(te=>te())),process.exit(1)};process.once("SIGINT",N);let U={};for(let te=0;te<h.length;te++){let ie=Object.values(U);ie.length===p&&await Promise.race(ie.map(V=>V.promise));let ut=h[te],M=`test-${te}`;U[M]={done:!1,promise:(async({testDefinition:V})=>{A.add(M);let re=V.relativeFilePath.includes("..")?V.fullFilePath:V.relativeFilePath;da({status:"START",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let Ce=setInterval(()=>da({status:"RUN",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Me=rU(),Ae=f.child({testId:V.id,runId:Me}),xt=new xs({logger:Ae,reporter:new ec(a),runType:"mobile-test-run",runId:Me,testMetadata:V,suiteMetadata:void 0});try{let dt=await GA({metadata:{...o,runId:Me},fixtures:{...t,tracer:E,logger:Ae,usageTracker:xt},inputs:{...n,project:i,testDefinition:V,channel:n.channel??V.settings?.defaultChannel,tag:n.tag??V.settings?.defaultTag,logUpdate:(Re,We)=>da({status:Re,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:We}),runSigIntHandlers:x},options:e});da({status:dt.status,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(dt)}catch(dt){let Re=`Encountered unexpected fatal error when running test '${V.name}': ${dt.message}`;R.error(Re),Ae.error(Re)}finally{clearInterval(Ce),U[M].done=!0,delete U[M]}await xt.flush(l)})({testDefinition:ut})}}await Promise.allSettled(Object.values(U).map(te=>te.promise));let ke=b.some(te=>te.status==="FAILED"&&!te.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ke}),process.off("SIGINT",N),T()}async function oU({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=Vv({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${Cp}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return R.log(""),o?(R.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await oc({client:n,consoleLogger:R,resultsPath:i})):R.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),l}async function Sm(){If(),Yv("Chromium")||(ca?(await Wl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await $l({rawBrowsers:["chromium"],force:!1,all:!1})):(R.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}Cb({serviceName:"mobile-cli"});Ct.setApp("mobile-cli");var on=new iU;on.name("momentic-mobile").description("Momentic Mobile CLI").version(Ra);var uU=on.command("assets").description("Manage mobile testing assets");uU.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ta).addOption(va).addOption(um).addOption(DA).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=mc.resolve(r);pc.existsSync(a)||(R.error(`File not found: ${a}`),process.exit(1));let l=new tr({baseUrl:n,apiKey:t,logger:R});/\.apk$/i.test(a)||(R.error(`File is not an APK file: ${a}`),process.exit(1)),await Ca({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:R})});on.command("app").addOption(Ta).addOption(va).addOption(sm).addOption(am).addOption(pm).addOption(lm).addOption(cm).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=xp(r.logLevel);Ct.setApp("mobile-desktop-server");let l=new tr({baseUrl:t,apiKey:e,logger:Ct});await jp({client:l,skipPrompts:n}),R.debug("API key check complete");let c=cU(import.meta.url),s=mc.dirname(c),u=mc.resolve(s,"..","static");await Sm(),R.debug({appiumHome:Li},"Resolved resource paths");let d=ga({configFilePath:r.config}),p=LA;await OA({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,logLevel:a,logger:Ct,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${p}`;R.info(`Local app started on: ${m}`),await lU(m)});var jA=on.command("results").description("Merge and upload test results.");jA.command("merge").description("Merge test results files.").addOption(dm).addArgument(new ym("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(R.error("Output directory is required."),process.exit(1)),pc.existsSync(r)||(R.warn("Results path does not exist, skipping merge."),process.exit(0)),pc.existsSync(t)&&R.warn(`Output directory ${t} already exists, removing before merging...`),gA(Ct,t,r),Jo(),process.exit(0)});var dU=new ym("<results>","Path to the results archive.").argRequired();jA.command("upload").description("Upload test results to Momentic cloud.").addOption(Ta).addOption(va).addArgument(dU).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ct,i=new tr({baseUrl:n,apiKey:t,logger:o});await oc({consoleLogger:R,resultsPath:r,client:i}),Jo(),process.exit(0)});var pU=on.command("run").alias("test").description("Run tests on the local machine");pU.addOption(Ta).addOption(va).addOption(am).addOption(sm).addOption(UA).addOption(pm).addOption(lm).addOption(cm).addOption(dm).addOption(FA).addOption(BA).addOption(um).addOption(NA).addOption(kA).addArgument(new ym("<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,l=xp(e.logLevel);await Sm(),R.debug({appiumHome:Li},"Resolved resource paths");let c=ga({configFilePath:e.config}),s=a??c.config.outputDir??oA,u=e.parallel??c.config.parallel??1;R.debug("Checking API key and dependencies");let d=new tr({baseUrl:n,apiKey:t,logger:R}),{orgId:p,userId:m}=await jp({client:d,skipPrompts:e.yes});R.debug("API key check and browser installation complete");let g=sU(),h=Ct.child({runGroupId:g,orgId:p,userId:m}),f=await Xl(Ct,d,c);h.debug(f,"Got local git metadata");try{let E=await VA({options:{...e,outputDir:s,parallel:u,logLevel:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});Jo(),E.failed>0?process.exit(1):process.exit(0)}catch(E){R.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),R.error(E),Ct.error({err:E},"Failed to run tests locally"),Jo(),process.exit(1)}});on.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new aU("--name <name>","Name of the project")).action(async r=>{R.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
3979
+ `),R.info("This wizard will help you bootstrap a new Momentic project."),pc.existsSync(Vo)&&(R.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await Wv("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Pp};nA(t,Vo),R.success(`Initialized Momentic project file at ${mc.resolve(Vo)}`)});on.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${_p.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(R.error("No browsers specified"),process.exit(1)),await $l({rawBrowsers:r,force:e.force,all:e.all})});async function Jo(){try{await Mt.flush(),Rv()}catch{}}async function mU(){try{await on.parseAsync(process.argv),Jo()}catch(r){Ct.error({err:r},"Uncaught error in CLI"),R.error(r),Jo(),process.exit(1)}}mU();
3980
3980
  //# sourceMappingURL=cli.js.map