momentic-mobile 0.0.17 → 0.0.19
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 +73 -124
- package/npm-shrinkwrap.json +184 -140
- package/package.json +1 -1
- package/static/assets/index-EHMi8Yfl.css +1 -0
- package/static/assets/{index-G56Gnrkd.js → index-HwmBhRzj.js} +171 -171
- package/static/index.html +2 -2
- package/static/assets/index-K7k0TIiO.css +0 -1
package/bin/cli.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var $v=Object.defineProperty;var Me=(r,e)=>()=>(r&&(e=r(r=0)),e);var qv=(r,e)=>{for(var t in e)$v(r,t,{get:e[t],enumerable:!0})};var af,sf=Me(()=>{"use strict";af=typeof globalThis=="object"?globalThis:global});var lf=Me(()=>{"use strict";sf()});var cf=Me(()=>{"use strict";lf()});var fr,nu=Me(()=>{"use strict";fr="1.9.0"});function r_(r){var e=new Set([r]),t=new Set,n=r.match(uf);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(uf);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 uf,df,mf=Me(()=>{"use strict";nu();uf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;df=r_(fr)});function io(r,e,t,n){var o;n===void 0&&(n=!1);var i=bi[Ti]=(o=bi[Ti])!==null&&o!==void 0?o:{version:fr};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!==fr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+fr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+fr+"."),!0}function Sr(r){var e,t,n=(e=bi[Ti])===null||e===void 0?void 0:e.version;if(!(!n||!df(n)))return(t=bi[Ti])===null||t===void 0?void 0:t[r]}function ao(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+fr+".");var t=bi[Ti];t&&delete t[r]}var n_,Ti,bi,vi=Me(()=>{"use strict";cf();nu();mf();n_=fr.split(".")[0],Ti=Symbol.for("opentelemetry.js.api."+n_),bi=af});function Ai(r,e,t){var n=Sr("diag");if(n)return t.unshift(e),n[r].apply(n,i_([],o_(t),!1))}var o_,i_,pf,gf=Me(()=>{"use strict";vi();o_=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(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))},pf=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 Ai("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ai("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ai("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ai("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ai("verbose",this._namespace,e)},r}()});var we,ts=Me(()=>{"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 hf(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 ff=Me(()=>{"use strict";ts()});var a_,s_,l_,rr,wi=Me(()=>{"use strict";gf();ff();ts();vi();a_=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},s_=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))},l_="diag",rr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Sr("diag");if(l)return l[o].apply(l,s_([],a_(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=Sr("diag"),d=hf((l=i.logLevel)!==null&&l!==void 0?l:we.INFO,o);if(u&&!i.suppressOverrideMessage){var m=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+m),d.warn("Current logger will overwrite one already registered from "+m)}return io("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ao(l_,t)},t.createComponentLogger=function(o){return new pf(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 Sf,Ef=Me(()=>{"use strict";Sf=Symbol("BaggageEntryMetadata")});function ou(r){return typeof r!="string"&&(c_.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:Sf,toString:function(){return r}}}var c_,yf=Me(()=>{"use strict";wi();Ef();c_=rr.instance()});function iu(r){return Symbol.for(r)}var u_,au,su=Me(()=>{"use strict";u_=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}(),au=new u_});function uu(){return cu}var mn,d_,rs,m_,p_,g_,h_,lu,f_,S_,E_,cu,y_,T_,b_,v_,A_,w_,R_,du=Me(()=>{"use strict";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)}}(),d_=function(){function r(){}return r.prototype.createGauge=function(e,t){return T_},r.prototype.createHistogram=function(e,t){return b_},r.prototype.createCounter=function(e,t){return y_},r.prototype.createUpDownCounter=function(e,t){return v_},r.prototype.createObservableGauge=function(e,t){return w_},r.prototype.createObservableCounter=function(e,t){return A_},r.prototype.createObservableUpDownCounter=function(e,t){return R_},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),rs=function(){function r(){}return r}(),m_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(rs),p_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(rs),g_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(rs),h_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(rs),lu=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),f_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(lu),S_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(lu),E_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(lu),cu=new d_,y_=new m_,T_=new g_,b_=new h_,v_=new p_,A_=new f_,w_=new S_,R_=new E_});var xt,Tf=Me(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(xt||(xt={}))});var C_,x_,bf,vf=Me(()=>{"use strict";su();C_=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},x_=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))},bf=function(){function r(){}return r.prototype.active=function(){return au},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,x_([n],C_(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var __,M_,mu,I_,Af,wf=Me(()=>{"use strict";vf();vi();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},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))},mu="context",I_=new bf,Af=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return io(mu,e,rr.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,M_([e,t,n],__(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Sr(mu)||I_},r.prototype.disable=function(){this._getContextManager().disable(),ao(mu,rr.instance())},r}()});var so,Rf=Me(()=>{"use strict";wf();so=Af.getInstance()});var F,Cf=Me(()=>{"use strict";wi();F=rr.instance()});var P_,xf,_f=Me(()=>{"use strict";du();P_=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return cu},r}(),xf=new P_});var pu,Mf,If=Me(()=>{"use strict";_f();vi();wi();pu="metrics",Mf=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return io(pu,e,rr.instance())},r.prototype.getMeterProvider=function(){return Sr(pu)||xf},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ao(pu,rr.instance())},r}()});var ns,Pf=Me(()=>{"use strict";If();ns=Mf.getInstance()});var he=Me(()=>{"use strict";yf();su();ts();du();Tf();Rf();Cf();Pf()});import{Argument as Hm,Command as z0,Option as G0}from"@commander-js/extra-typings";import Qv from"appium";import{remote as Zv}from"webdriverio";import{createInstanceClient as Kv}from"@limrun/api";import{execSync as Yv}from"child_process";import{hostname as Xv}from"os";import Jv from"path";async function Vm(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:Xv()}),m;try{Yv("adb --version"),m="adb"}catch{if(process.env.ANDROID_HOME)m=Jv.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 p=await Kv({adbUrl:c,endpointUrl:l,token:a,logLevel:i,adbPath:m}),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(T=>p.sendAsset(T))),o("Starting tunnel");let y=await p.startAdbTunnel();return{port:y.address.port,close:y.close,token:a,webRtcUrl:l,emulatorName:s}}async function la({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:m}=await rA({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),p=[()=>t.deleteAndroidEmulator(m),c],g=async()=>{for(let f=p.length-1;f>=0;f-=1)try{await p[f]()}catch(y){if(y instanceof Error&&y.message.includes("ECONNREFUSED"))return;n.warn({err:y},"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 eA({logger:n,logLevel:o,appiumPort:i,port:s,limbarStart:l,emulatorName:m,apiClient:t,onStatusUpdate:r,creationOpts:e});return p.push(f.appiumClose),p.push(async()=>f.driver.deleteSession()),await h(),{...f,emulatorName:m,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 eA({logger:r,logLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:l}=await tA({logger:r,logLevel:e,appiumPort:i}),c={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:newCommandTimeout":86400,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":3e5,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0},s={hostname:"localhost",port:i,logLevel:e,capabilities:c},u=Date.now(),d=await Zv(s);return await d.updateSettings({enableMultiWindows:!0}),r.info({timings:{limbarDuration:a-n,appiumDuration:u-a,wdioDuration:Date.now()-u},capabilities:c,emulatorName:o},"Started Appium driver"),{driver:d,appiumClose:l,appiumPort:i}}async function tA({logger:r,logLevel:e,appiumPort:t}){let n=await Qv.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e});return{close:async()=>{await n.close()}}}async function rA({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:l,emulatorName:c}=await Vm({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:l,emulatorName:c}}import jm from"crypto";import nA from"fs";async function ca({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await nA.promises.readFile(t),a=jm.createHash("md5").update(i).digest("base64"),l=jm.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 Wh}from"child_process";import{existsSync as Rx}from"fs";import{platform as $h}from"os";import{dirname as Cx,join as xx,resolve as _x}from"path";import{z as Wm}from"zod";var uk=Wm.object({input:Wm.string()});import{z as je}from"zod";var pk=je.object({srcs:je.array(je.string()),urls:je.array(je.string()),desiredSrc:je.string().optional(),desiredUrl:je.string().optional()}),$m=je.object({srcRegex:je.string().optional(),urlRegex:je.string().optional()}),qm=je.object({x:je.number(),y:je.number(),correlation:je.number()}),gk=je.object({searchImageBase64String:je.string(),pageImageBase64String:je.string(),id:je.string().uuid(),timeoutMs:je.number().max(1e4).min(0).optional()});import{z as P}from"zod";import*as L from"zod";import{extendZodWithOpenApi as oA}from"zod-openapi";oA(L);var Ar=(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))(Ar||{}),iA=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),ql=L.object({result:L.number(),traceId:L.string()}).array(),ua=L.object({type:L.literal("GCS_TRACES"),traces:ql}),Km=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()}),aA=L.object({selectors:L.string().array(),requirements:Km.optional()}),wr=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:Km.optional(),additionalElements:aA.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:iA.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Ar).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:ua.optional()}).openapi({ref:"ElementTargetCache"});function da(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function Ym(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 sA=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),lA=L.object({x:L.number(),y:L.number()}),cA=L.object({type:L.literal("coordinates"),pixels:lA}).openapi({ref:"CoordinatesTarget"});function Rr(r){return r.type==="description"}function Jt(r){return r.type==="coordinates"}var ot=L.discriminatedUnion("type",[sA,cA]).openapi({ref:"ElementTarget"});function Kl(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Xm(r){return ua.safeParse(r).success}import{v4 as ae}from"uuid";import*as E from"zod";import{extendZodWithOpenApi as SA}from"zod-openapi";import{z as X}from"zod";import{extendZodWithOpenApi as uA}from"zod-openapi";import{z as Nn}from"zod";var Yl=Nn.object({result:Nn.boolean(),traceId:Nn.string()}).array(),Xl=Nn.object({type:Nn.literal("GCS_TRACES"),traces:Yl}),Jl=Nn.object({memory:Xl.optional()});uA(X);var Jm=X.object({plan:X.string().optional(),evidence:X.string().optional(),thoughts:X.string(),result:X.boolean(),relevantElements:X.array(X.number()).optional(),updatedMemory:Yl.optional()}),Cr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Cr||{});var dA=X.object({type:X.literal("ELEMENT_NAME"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),value:X.string()}).openapi({ref:"ElementNameAssertion"}),mA=X.object({type:X.literal("ELEMENT_STYLE"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),property:X.string(),value:X.string()}).openapi({ref:"ElementStyleAssertion"}),pA=X.object({type:X.literal("ELEMENT_CONTENT"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),value:X.string()}).openapi({ref:"ElementContentAssertion"}),gA=X.object({type:X.literal("ELEMENT_ATTRIBUTE"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),attr:X.string(),value:X.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Dn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Dn||{}),hA=X.object({type:X.literal("ELEMENT_EXISTENCE"),negated:X.boolean().optional(),condition:X.nativeEnum(Dn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Qm=X.discriminatedUnion("type",[pA,gA,hA,dA,mA]).openapi({ref:"ManualElementAssertion"});var fA=X.object({type:X.literal("CONTENT"),negated:X.boolean().optional(),value:X.string()}).openapi({ref:"PageContentAssertion"}),Zm=X.discriminatedUnion("type",[fA]).openapi({ref:"ManualPageAssertion"});import ut from"zod";var Ql=ut.discriminatedUnion("type",[ut.object({type:ut.literal("SUBSTRING"),url:ut.string()}),ut.object({type:ut.literal("GLOB"),glob:ut.string()}),ut.object({type:ut.literal("REGEX"),regex:ut.string()}),ut.object({type:ut.literal("DOMAIN"),domain:ut.string()})]),zo=ut.object({urlMatcher:Ql,method:ut.string().optional()});import{z as ie}from"zod";var ma=ie.object({url:ie.string(),method:ie.union([ie.literal("GET"),ie.literal("POST"),ie.literal("PUT"),ie.literal("DELETE"),ie.literal("PATCH")]),headers:ie.record(ie.string(),ie.string()).optional(),params:ie.record(ie.string(),ie.string()).optional(),body:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),ep=ie.object({url:ie.string(),headers:ie.record(ie.string(),ie.string()).optional(),query:ie.string(),variables:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),pa=ie.object({code:ie.string(),fragment:ie.boolean().optional(),environment:ie.union([ie.literal("NODE"),ie.literal("BROWSER")]).optional().describe("default NODE"),timeout:ie.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Ze=(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))(Ze||{});SA(E);var G=E.object({thoughts:E.string().optional(),id:E.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=E.object({useSelector:E.boolean().optional(),force:E.boolean().optional(),disableCache:E.boolean().optional().describe("disable element caching for this step"),iframeUrl:E.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Mt=E.object({target:wr}).optional().openapi({ref:"SingleTargetCache"});function rp(r){return Mt.safeParse(r).success}var ha=E.object({loadTimeout:E.number().int().max(60).optional().describe("Max seconds for the page to load")}),EA=G.merge(ha).merge(E.object({type:E.literal("NAVIGATE"),url:E.string()})).openapi({ref:"NavigateCommand"}),fa=_t.merge(E.object({cache:Mt})),kn=G.merge(fa.merge(E.object({target:ot.optional(),type:E.literal("SCROLL_UP"),deltaY:E.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Un=G.merge(fa.merge(E.object({target:ot.optional(),type:E.literal("SCROLL_DOWN"),deltaY:E.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Fn=G.merge(fa.merge(E.object({target:ot.optional(),type:E.literal("SCROLL_LEFT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Bn=G.merge(fa.merge(E.object({target:ot.optional(),type:E.literal("SCROLL_RIGHT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollRightCommand"}),Bk=E.discriminatedUnion("type",[kn,Un,Fn,Bn]).openapi({ref:"AllScrollCommands"}),yA=G.merge(E.object({type:E.literal("DIALOG"),action:E.union([E.literal("ACCEPT"),E.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),TA=G.merge(E.object({type:E.literal("WAIT"),delay:E.number()})).openapi({ref:"WaitCommand"}),bA=E.object({caseInsensitive:E.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:E.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:E.number().int().optional().describe("Max seconds to wait for the URL to match")}),vA=G.extend({type:E.literal("WAIT_FOR_URL"),matcher:Ql}).merge(bA).openapi({ref:"WaitUrlCommand"}),AA=G.merge(ha).merge(E.object({type:E.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),wA=G.merge(E.object({type:E.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),RA=G.merge(E.object({type:E.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),CA=G.extend({type:E.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),xA=G.extend({type:E.literal("AUTH_LOAD"),storageState:E.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Zl=G.merge(_t).extend({type:E.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),_A=G.extend({type:E.literal("COPY"),value:E.string()}).openapi({ref:"CopyCommand"}),MA=G.extend({type:E.literal("PASTE")}).openapi({ref:"PasteCommand"}),IA=G.merge(pa).extend({type:E.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Go=G.merge(_t).extend({type:E.literal("CLICK"),target:ot,doubleClick:E.boolean().optional(),rightClick:E.boolean().optional(),waitForDownload:E.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:E.number().optional(),downloadTimeoutMs:E.number().optional(),cache:Mt,relativePosition:E.object({x:E.number(),y:E.number()}).optional()}).openapi({ref:"ClickCommand"}),np=E.object({fromTarget:wr.optional(),toTarget:wr.optional()}),Ho=G.merge(_t).merge(E.object({type:E.literal("DRAG"),fromTarget:ot,toTarget:ot,steps:E.number().optional(),hoverSeconds:E.number().optional().describe("Seconds to hover the object before dropping"),cache:np.optional()})).openapi({ref:"DragCommand"}),Vo=G.merge(_t).merge(E.object({type:E.literal("MOUSE_DRAG"),target:ot.optional(),deltaX:E.string().describe("pixels to move horizontally, can be template"),deltaY:E.string().describe("pixels to move vertically, can be template"),steps:E.number().optional(),cache:Mt})).openapi({ref:"MouseDragCommand"}),jo=G.merge(_t).merge(E.object({type:E.literal("HOVER"),target:ot,cache:Mt})).openapi({ref:"HoverCommand"}),Wo=G.merge(_t).merge(E.object({type:E.literal("FOCUS"),target:ot,cache:Mt})).openapi({ref:"FocusCommand"}),$o=G.merge(_t).extend({type:E.literal("BLUR"),target:ot.optional(),cache:Mt}).openapi({ref:"BlurCommand"}),PA=E.object({type:E.literal("URL"),url:E.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),OA=E.object({type:E.literal("USER_FILE"),name:E.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),LA=G.extend({type:E.literal("FILE_UPLOAD"),fileSource:E.discriminatedUnion("type",[PA,OA]),filename:E.string().optional()}).openapi({ref:"FileUploadCommand"}),NA=E.discriminatedUnion("type",[E.object({type:E.literal("VALUE"),value:E.string()}),E.object({type:E.literal("LABEL"),label:E.string()}),E.object({type:E.literal("INDEX"),index:E.coerce.string()})]),qo=G.merge(_t).extend({type:E.literal("SELECT_OPTION"),target:ot,cache:Mt,choice:NA.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),ec=E.union([E.literal("MULTIMODAL"),E.literal("VISION_ONLY")]),Sa=G.merge(E.object({type:E.literal("AI_ASSERTION"),assertion:E.string(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional(),contextChoice:ec.optional(),timeout:E.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Jl.optional()})).openapi({ref:"AIAssertionCommand"}),xr=5,tc=600,Ko=G.merge(_t).extend({type:E.literal("ELEMENT_CHECK"),target:ot,assertion:Qm,cache:Mt.or(Jl).optional(),timeout:E.number().int().min(0).max(tc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),DA=G.extend({type:E.literal("PAGE_CHECK"),assertion:Zm,iframeUrl:E.string().optional().describe("url or url regex for the iframe"),timeout:E.number().int().min(0).max(tc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),kA=G.merge(E.object({type:E.literal("AI_EXTRACT"),goal:E.string(),schema:E.string().optional(),envKey:E.string().optional(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional()})).openapi({ref:"AIExtractCommand"}),UA=E.object({clearContent:E.boolean().optional(),forceClearContent:E.boolean().optional(),delay:E.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:E.boolean().optional(),pressEnter:E.boolean().optional()}),op=25,Yo=G.merge(_t).merge(UA).extend({type:E.literal("TYPE"),target:ot.optional(),value:E.string(),cache:Mt}).openapi({ref:"TypeCommand"}),FA=G.merge(E.object({type:E.literal("PRESS"),value:E.string(),repeat:E.number().optional(),convertMeta:E.boolean().optional(),delayMs:E.number().optional()})).openapi({ref:"PressCommand"}),BA=G.merge(E.object({type:E.literal("KEY_DOWN"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyDownCommand"}),zA=G.merge(E.object({type:E.literal("KEY_UP"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyUpCommand"}),GA=E.object({type:E.literal("SUBSTRING"),substring:E.string()}),HA=E.object({type:E.literal("REGEX"),pattern:E.string()}),VA=E.object({type:E.literal("INDEX"),index:E.coerce.string()}),jA=E.discriminatedUnion("type",[GA,HA,VA]),WA=G.merge(ha).merge(E.object({type:E.literal("TAB"),action:jA})).openapi({ref:"TabCommand"}),$A=G.merge(ha).merge(E.object({type:E.literal("NEW_TAB"),url:E.string()})).openapi({ref:"NewTabCommand"}),qA=G.merge(E.object({type:E.literal("COOKIE"),value:E.string()})).openapi({ref:"CookieCommand"}),KA=G.merge(E.object({type:E.literal("LOCAL_STORAGE"),key:E.string(),value:E.string()})).openapi({ref:"LocalStorageCommand"}),YA=G.extend({type:E.literal("REQUEST")}).merge(ma).openapi({ref:"RequestCommand"}),XA=G.extend({type:E.literal("GRAPHQL_REQUEST")}).merge(ep).openapi({ref:"GraphQLRequestCommand"}),JA=G.merge(E.object({type:E.literal("SUCCESS"),condition:Sa.optional()})).openapi({ref:"SuccessCommand"}),QA=G.merge(E.object({type:E.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ZA=E.object({data:E.string().describe("location at which to find a jpg"),width:E.number(),height:E.number()}),Xo=G.merge(_t).merge(E.object({type:E.literal("VISUAL_DIFF"),threshold:E.number().optional().describe("default 0.1"),target:ot.optional(),screenshot:ZA.optional(),cache:Mt})).openapi({ref:"VisualDiffCommand"}),ew=G.merge(E.object({type:E.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:zo,key:E.string()})).openapi({ref:"RegisterRequestListenerCommand"}),tw=G.merge(E.object({type:E.literal("AWAIT_LISTENER"),key:E.string(),timeout:E.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),rw=G.merge(E.object({type:E.literal("RECORD_REQUESTS"),requestMatcher:zo,key:E.string()})).openapi({ref:"RecordRequestsCommand"}),nw=G.merge(E.object({type:E.literal("GET_RECORDED_REQUESTS"),key:E.string()})).openapi({ref:"GetRecordedRequestsCommand"}),ow=G.merge(E.object({type:E.literal("SET_HEADER"),name:E.string(),value:E.string(),requestMatcher:zo.optional()})).openapi({ref:"SetHeaderCommand"}),iw=G.merge(E.object({type:E.literal("MOCK_ROUTE"),requestMatcher:zo,responseGenerator:E.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:E.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:E.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(E.object({type:E.literal("REMOVE_ROUTE_MOCK"),key:E.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),sw=G.merge(E.object({type:E.literal("OFFLINE_MODE"),enable:E.boolean()})).openapi({ref:"OfflineModeCommand"}),ip=E.discriminatedUnion("type",[Go,Yo,FA,BA,zA,qo,EA,Un,kn,Sa,jo,TA,JA]),lw=E.discriminatedUnion("type",[kA,xA,CA,Zl,qA,_A,yA,Ho,Ko,LA,wA,RA,IA,KA,Vo,$A,DA,MA,AA,YA,XA,Fn,Bn,WA,Xo,Wo,$o,vA,ew,tw,rw,nw,ow,iw,aw,sw]),zn=E.discriminatedUnion("type",[...ip.options,...lw.options]).openapi({ref:"Command"}),Ea=E.discriminatedUnion("type",[...ip.options,QA]);function mr(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:ae(),type:r};break;case"AUTH_LOAD":{e={id:ae(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ae(),type:r,goal:""};break;case"DIALOG":e={id:ae(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ae(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ae(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ae(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ae(),type:r,delay:1};break;case"BLUR":e={id:ae(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ae(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ae(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ae(),type:r,value:""};break;case"SELECT_OPTION":e={id:ae(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ae(),type:r,url:""};case"TAB":e={id:ae(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ae(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ae(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ae(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ae(),type:r,code:""};break;case"AI_ASSERTION":e={id:ae(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ae(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ae(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ae(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ae(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ae(),type:r,key:""};break}case"SET_HEADER":{e={id:ae(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ae(),type:r};break}case"OFFLINE_MODE":{e={id:ae(),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 ap(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 jk=cw.discriminatedUnion("type",[$o,Zl,Go,Ho,Wo,jo,Vo,kn,Un,Fn,Bn,qo,Yo,Xo,Ko]);import{z as uw}from"zod";import{z as _r}from"zod";function Jo(r){return _r.object({key:_r.string(),testId:_r.string().optional(),moduleId:_r.string().optional(),organizationId:_r.string(),value:r})}function Qo(r){return Jo(r).extend({uniqueKey:_r.string()})}function ya(r){return _r.record(_r.string(),Qo(r))}var dt={type:!0,cache:!0},Gn=uw.discriminatedUnion("type",[Sa.pick(dt),$o.pick(dt),Go.pick(dt),Ho.pick(dt),Ko.pick(dt),Wo.pick(dt),jo.pick(dt),Vo.pick(dt),kn.pick(dt),Un.pick(dt),Fn.pick(dt),Bn.pick(dt),qo.pick(dt),Yo.pick(dt),Xo.pick(dt)]),rc=Object.values(Ze).filter(r=>Gn.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 sp(r){return rc.includes(r.type)}var lp=Jo(Gn),cp=Qo(Gn),Qk=ya(Gn);import{z as nc}from"zod";import{extendZodWithOpenApi as pw}from"zod-openapi";import{z as up}from"zod";import{extendZodWithOpenApi as dw}from"zod-openapi";import{z as Jr}from"zod";var It=Jr.object({index:Jr.number().optional().describe("global index within a test (in-order traversal)"),id:Jr.string(),skipped:Jr.boolean().optional(),envKey:Jr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Jr.boolean().optional(),retries:Jr.number().optional()});dw(up);var mw=It.extend({type:up.literal("PRESET_ACTION")}),Pt=mw.extend({command:zn}).openapi({ref:"PresetAction"});pw(nc);var Qr=It.extend({type:nc.literal("AI_ACTION"),text:nc.string(),steps:Pt.array().optional()}).openapi({ref:"AIAction"});import{z as mt}from"zod";import{z as Ta}from"zod";import{extendZodWithOpenApi as gw}from"zod-openapi";gw(Ta);var Hn=It.extend({type:Ta.literal("AI_ACTION_DYNAMIC"),text:Ta.string(),retries:Ta.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as dp}from"zod";var oc=It.extend({type:dp.literal("CONDITIONAL"),skipped:dp.boolean().optional()});import{z as re}from"zod";var hw=re.object({cacheKey:re.string(),cacheExpiryMs:re.number()}),ic=It.extend({id:re.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:re.record(re.string()).optional(),cacheConfig:hw.optional()}),pr=ic.extend({type:re.literal("MODULE"),moduleId:re.string().uuid()}),fw=re.union([pr.pick({type:!0,moduleId:!0}),re.record(re.unknown())]),Sw=re.object({type:re.literal("URL_REGEX"),regex:re.string()}),Ew=re.object({type:re.literal("PAGE_CHECK"),substring:re.string()}),ac=re.object({cacheInvalidation:re.discriminatedUnion("type",[Ew,Sw]).optional()}),Ot=re.object({moduleId:re.string().uuid(),name:re.string(),description:re.string().nullish(),enabled:re.boolean().nullish(),parameters:re.string().array().nullish(),defaultParameters:re.record(re.string(),re.string()).nullish(),parameterEnums:re.record(re.string(),re.string().array()).nullish(),defaultCacheKey:re.string().nullish(),defaultCacheTtl:re.number().nullish(),defaultCacheAllInvocations:re.boolean().nullish(),autoAuth:re.boolean().nullish(),advanced:ac.nullish()});import{z as Lt}from"zod";var mp=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(mp||{});var yw=Lt.discriminatedUnion("type",[Lt.object({type:Lt.literal("NAVIGATE_URL"),url:Lt.string().url()}),Lt.object({type:Lt.literal("GO_TO_SECTION_START")})]),Tw=Lt.object({trigger:Lt.nativeEnum(mp).optional(),attempts:Lt.number().int().optional(),restartBehavior:yw}),Zo=It.extend({type:Lt.literal("SECTION"),description:Lt.string().describe("user provided goal of what the section should accomplish"),plan:Lt.string().array().optional(),autohealingConfig:Tw.optional()});var pp=Ot.merge(ic).extend({type:mt.literal("RESOLVED_MODULE"),steps:mt.lazy(()=>$e.array())}),ei=Ot.extend({steps:mt.lazy(()=>$e.array())}),sc=Zo.extend({steps:mt.lazy(()=>pt.array())}),bw=Zo.extend({steps:mt.lazy(()=>$e.array())}),Vn=oc.extend({blocks:mt.object({assertion:mt.lazy(()=>Pt),steps:mt.lazy(()=>pt.array())}).array(),elseSteps:mt.lazy(()=>pt.array().optional())}),vw=oc.extend({blocks:mt.object({assertion:mt.lazy(()=>Pt),steps:mt.lazy(()=>$e.array())}).array(),elseSteps:mt.lazy(()=>$e.array().optional())}),pt=mt.discriminatedUnion("type",[Pt,Qr,Hn,pr,Vn,sc]),$e=mt.discriminatedUnion("type",[Pt,Qr,Hn,pp,vw,bw]);import{z as Nt}from"zod";var Aw=Nt.object({steps:pt.array(),beforeSteps:pt.array().nullish(),afterSteps:pt.array().nullish()}),jn=Nt.object({steps:$e.array(),beforeSteps:$e.array().nullish(),afterSteps:$e.array().nullish()}),Zr=Nt.object({steps:Nt.record(Nt.string(),Nt.unknown()).array(),beforeSteps:Nt.record(Nt.string(),Nt.unknown()).array().nullish(),afterSteps:Nt.record(Nt.string(),Nt.unknown()).array().nullish()});var Wn="1.0.21",ba="0.0.1";var gp=P.object({phrase:P.string()}),lc=P.object({thoughts:P.string().optional(),result:P.union([P.literal("NOT_FOUND"),P.string(),P.number(),P.array(P.unknown()),P.record(P.unknown(),P.unknown()),P.unknown()])}),UF=P.object({text:P.string()}),hp=P.object({attributes:P.array(P.string()).optional(),text:P.boolean().optional(),boundingBox:P.boolean().optional()}),ww=P.object({id:P.number().int(),requirements:hp}),Rw=ww.array(),fp=P.object({thoughts:P.string(),review:P.string().optional(),id:P.number().int(),updatedMemory:ql.optional(),requirements:hp.optional(),additionalElements:Rw.optional()});var cc=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(cc||{});var Sp=P.object({thoughts:P.string(),category:P.nativeEnum(cc)}),Cw=P.discriminatedUnion("op",[P.object({op:P.literal("replace"),path:P.string(),value:P.string()}),P.object({op:P.literal("add"),path:P.string(),value:P.string()}),P.object({op:P.literal("remove"),path:P.string()})]),FF=P.object({thoughts:P.string(),patches:Cw.array()}),xw=[P.literal("add"),P.literal("replace"),P.literal("remove")],_w=P.object({op:P.union(xw),path:P.string(),value:$e.optional()}),Ep=P.object({patches:_w.array(),thoughts:P.string()}),yp=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(yp||{}),Tp=P.object({thoughts:P.string(),scenario:P.nativeEnum(yp),instructions:P.string().nullish()}),bp=P.object({reasoning:P.string(),scenario:P.string(),patch:P.null().optional()}),BF=P.object({thoughts:P.string(),evaluation:P.number().min(0).max(10)}),zF=P.object({observations:P.string(),reasoning:P.string(),command:Ea});var uc=P.object({summary:P.string(),reasoning:P.string(),evaluation:P.discriminatedUnion("type",[P.object({type:P.literal("DONE")}),P.object({type:P.literal("RIGHT_TRACK")}),P.object({type:P.literal("WRONG_TRACK"),feedback:P.string()}),P.object({type:P.literal("IMPOSSIBLE")})])}),Mw=P.object({startId:P.number().int(),endId:P.number().int()}),vp=P.object({categoryThoughts:P.string(),category:P.string(),relevantSections:Mw.array()});import{z as M}from"zod";import*as J from"zod";var $F=J.object({thoughts:J.string().optional().describe("only provided if a description was provided"),target:wr.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")}),Ap=J.union([J.literal("ELEMENT_CHECK"),J.literal("NEGATED_CHECK"),J.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),J.literal("SELECT_OPTION"),J.literal("TYPE")]);function ti(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 ri=(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))(ri||{}),$n=J.object({matched:J.boolean(),reason:J.string().optional().describe("Human understandable description"),logs:J.string().array().optional().describe("Logs for debugging")}),Iw=$n.extend({type:J.literal("USER_SELECTOR")}),Pw=$n.extend({type:J.literal("CSS_SELECTOR"),selectors:J.string().array()}),Ow=$n.extend({type:J.literal("HYBRID_SELECTOR")}),Lw=$n.extend({type:J.literal("HTML_DISTANCE"),distance:J.number().optional(),closestElement:J.string().optional(),savedElement:J.string().optional()}),Nw=$n.extend({type:J.literal("TEMPLATE_MATCHING"),elementImageUrl:J.string().url()}),Dw=$n.extend({type:J.literal("AUTO_FRAME"),logs:J.string().array().optional()}),wp=J.discriminatedUnion("type",[Iw,Pw,Ow,Lw,Nw,Dw]);import{z as ai}from"zod";import{z as $w}from"zod";import*as z from"zod";import{extendZodWithOpenApi as Fw}from"zod-openapi";import{cloneDeep as nB}from"lodash-es";import iB from"truncate-json";import*as rn from"zod";import{extendZodWithOpenApi as kw}from"zod-openapi";import{z as it}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 Rp=1e4,Cp=6e4,en=dc.extend({pageLoadTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=Cp&&r>=-1,{message:`Page load timeout must be between 0 and ${Cp/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<=Rp&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${Rp/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 mc="BASE_URL";var tn="ENV_NAME",qn="TEST_NAME",QF={[mc]:"https://www.google.com"},xp=it.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),_p=it.object({name:it.string(),variables:it.record(it.string().describe("variable name"),it.string().describe("variable value"))}),Mp=it.object({name:it.string(),variables:it.record(it.string().describe("variable name"),it.unknown().describe("variable value")),browser:en.optional()});var ZF=it.object({name:it.string(),variables:it.record(it.string().describe("variable name"),it.unknown().describe("variable value"))});kw(rn);var pc=rn.object({env:rn.record(rn.unknown())}).openapi({ref:"TestContextSnapshot"});var et=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(et||{}),gc=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(gc||{});import{z as Qt}from"zod";import{extendZodWithOpenApi as Uw}from"zod-openapi";Uw(Qt);var ge=(m=>(m.AI_PROVIDER="AIProviderError",m.USER_INFRA="UserInfrastructureError",m.ACTION_FAILURE="ActionFailureError",m.ASSERTION_FAILURE="AssertionFailureError",m.CONFIG_ERROR="UserConfigurationError",m.SETUP_FAILURE="SetupFailureError",m.TEARDOWN_FAILURE="TeardownFailureError",m.WEB_AGENT_PLATFORM="InternalWebAgentError",m.UNKNOWN_PLATFORM="InternalPlatformError",m.JOB_TIMEOUT="JobTimeoutError",m.CONCURRENCY_ERROR="ConcurrencyError",m.UNKNOWN="UnknownError",m))(ge||{});var hc=Qt.object({reason:Qt.nativeEnum(ge),previousStepsDescription:Qt.array(Qt.string()).optional(),summary:Qt.string(),rootCause:Qt.string().optional()}).openapi({ref:"TestResultClassification"}),va=Qt.object({errorMessage:Qt.string(),errorStack:Qt.string().optional(),classification:hc.optional()}).openapi({ref:"TestFailureDetails"});Fw(z);var fc=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=fc.extend({viewport:z.object({height:z.number(),width:z.number()}).nullish(),status:z.nativeEnum(gc),message:z.string().optional(),elementInteracted:z.string().optional()}),nn=fc.extend({status:z.nativeEnum(et),message:z.string().optional(),data:z.unknown().optional(),beforeTestContext:pc.optional(),afterTestContext:pc.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"}),Ip=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(Ip||{}),Aa=nn.merge(Pt).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(()=>Ke.array()).optional(),failureRecoveryStatus:z.object({type:z.nativeEnum(Ip),message:z.string()}).optional()}),zw=nn.merge(Qr).extend({results:z.lazy(()=>Aa.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Gw=nn.merge(Hn).extend({results:z.lazy(()=>Aa.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Hw=nn.merge(pr).extend({moduleName:z.string().optional(),results:z.lazy(()=>Ke.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Vw=nn.merge(Vn).extend({assertion:Aa.optional(),results:z.lazy(()=>Ke.array()).describe("results for the block actually executed"),previousAttempts:z.lazy(()=>Ke.array()).optional()}),jw=nn.merge(Zo).extend({results:z.lazy(()=>Ke.array()),healingAttempts:z.lazy(()=>Ke.array().array()).optional(),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Ke=z.discriminatedUnion("type",[zw,Gw,Aa,Hw,Vw,jw]),wB=nn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Ww=fc.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)}),wa=Ww.extend({beforeScreenshot:z.string().optional(),afterScreenshot:z.string().optional()});var Sc=$w.object({results:Ke.array().describe("main results"),beforeResults:Ke.array().optional(),afterResults:Ke.array().optional()}),ni=Sc.partial();import{z as U}from"zod";import{extendZodWithOpenApi as Zw}from"zod-openapi";var Kn=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Kn||{});import{isValidCron as qw}from"cron-validator";import{z as Q}from"zod";import{z as Ec}from"zod";var Mr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Mr||{});var Ra=Ec.object({width:Ec.number().min(200).max(1e4),height:Ec.number().min(200).max(1e4)}),Pp={"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}},PB=Object.keys(Pp);var Ir=Pp["Desktop Large"],Op="en-us",Lp="America/Los_Angeles";var Np={latitude:37.7749,longitude:-122.4194};var Dp=["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 kp=2e3,Kw=en.extend({browserType:Q.nativeEnum(Mr).optional(),slowMoMs:Q.number().optional().refine(r=>r===void 0||r<=kp&&r>=-1,{message:`Slow motion must be between 0 and ${kp} 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(Dp).optional(),colorScheme:Q.enum(["light","dark"]).optional()});var yc=Q.object({useMemory:Q.boolean().optional(),failureRecovery:Q.boolean().optional().describe("undefined means inherit org settings")}),Yw=yc.extend({disableAICaching:Q.boolean().optional(),failureRecoveryInstructions:Q.string().optional()}),Xw=Q.object({viewport:Ra.optional()}),oi=Xw.merge(Yw).merge(Kw),Yn=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()}),Xn=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")}),Ca=Jw.array(),Qw=Q.object({name:Q.string(),value:Q.string()}),Up=Qw.array(),xa=Q.object({name:Q.string(),default:Q.boolean().optional(),fixtures:xp.array().optional()});Zw(U);var Dt={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||{}),_a=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(_a||{});var Be=U.string().pipe(U.coerce.date()).or(U.date()),ii=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(Kn).optional().default("WEB"),createdAt:Be,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Be.or(U.null()),startedAt:Be.or(U.null()),updatedAt:Be.nullish(),finishedAt:Be.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(_a).nullish(),status:U.nativeEnum(me),trigger:U.nativeEnum(Dt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(me),startedAt:Be.or(U.null()),finishedAt:Be.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(ge).nullish(),failureDetails:va.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"}),eR={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Ma=ii.pick({...eR,test:!0}),Fp=ii.omit({failureReason:!0,failureDetails:!0,test:!0}),Tc=ii.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:oi.nullish()}).nullish()}).merge(Sc);var tR=ai.object({id:ai.string().uuid(),startedAt:Be.or(ai.null()),finishedAt:Be.or(ai.null()),status:ai.nativeEnum(me)}).merge(ni),ZB=tR.array();import{z as ze}from"zod";var rR=ze.object({id:ze.string(),status:ze.nativeEnum(me),trigger:ze.nativeEnum(Dt),createdAt:Be,startedAt:Be.nullish(),finishedAt:Be.nullish(),gitCommitSha:ze.string().nullish(),gitCommitShaShort:ze.string().nullish(),gitCommitTimestamp:Be.nullish(),gitBranchName:ze.string().nullish(),gitOriginUrl:ze.string().nullish(),gitCommitMessage:ze.string().nullish(),gitCommitAuthorName:ze.string().nullish(),githubRepository:ze.string().nullish(),gitlabProjectPath:ze.string().nullish(),pipelineId:ze.string().nullish(),cliVersion:ze.string().nullish(),labels:ze.string().array().optional(),suite:ze.object({id:ze.string(),name:ze.string()}).nullish(),runs:ze.object({status:ze.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),Bp=rR.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Ma.array()});import{z as Ye}from"zod";var nR=Ye.object({type:Ye.literal("TARGETING"),name:Ye.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:wp.array(),pageState:Ye.string().optional(),targetSource:Ye.nativeEnum(Ar).optional(),targetUpdateTime:Ye.string().optional()}),oR=Ye.object({type:Ye.literal("AI_LOCATION"),matched:Ye.boolean(),pageState:Ye.string().optional(),ragUsed:Ye.boolean().optional(),thoughts:Ye.string().optional()}),iR=Ye.object({type:Ye.literal("ASSERTION"),relevantElementsSerialized:Ye.string().array().optional(),pageState:Ye.string().optional(),ragUsed:Ye.boolean().optional()}),aR=Ye.discriminatedUnion("type",[nR,oR,iR]);import{z as ke}from"zod";var sR=ke.object({id:ke.string(),name:ke.string()}),pz=sR.merge(ke.object({createdAt:Be,createdBy:ke.string(),schedule:Yn,notification:Xn,environment:ke.object({name:ke.string()}).nullish(),beforeTests:ke.object({id:ke.string()}).array().nullish(),afterTests:ke.object({id:ke.string()}).array().nullish()})),zp=ke.object({id:ke.string().uuid(),orgId:ke.string(),createdAt:Be,startedAt:Be.or(ke.null()),finishedAt:Be.or(ke.null()),status:ke.nativeEnum(me),trigger:ke.nativeEnum(Dt),suite:ke.object({id:ke.string(),name:ke.string()}).nullish(),runs:ii.array()}),gz=zp.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Gp=zp.extend({runs:Ma.array()});import{z as kt}from"zod";import{cloneDeep as Sz}from"lodash-es";import{z as se}from"zod";var Az=se.object({thoughts:se.string(),subGoals:se.object({instruction:se.string()}).array()}),wz=se.object({thoughts:se.string(),newPlanMarkdown:se.string()}),Rz=se.object({thoughts:se.string(),correct:se.boolean(),failedActionIndex:se.number().optional()}),lR=se.object({type:se.literal("PLANNING"),beforePlan:se.string(),goalDecision:se.string(),thoughts:se.string()}),cR=se.object({type:se.literal("RUNNING"),stepDisplayName:se.string(),status:se.nativeEnum(et),results:Ke.array()}),uR=se.object({type:se.literal("REVISING"),beforePlan:se.string(),afterPlan:se.string(),errString:se.string(),diffs:se.string(),thoughts:se.string()}),dR=se.object({type:se.literal("SYSTEM"),message:se.string()}),mR=se.discriminatedUnion("type",[lR,cR,uR,dR]),Hp=mR.array();var Iz=kt.object({id:kt.string(),scheduledAt:kt.coerce.date().nullable(),startedAt:kt.coerce.date().nullable(),finishedAt:kt.coerce.date().nullable(),status:kt.nativeEnum(me),history:Hp.nullable(),testPlan:kt.object({id:kt.string(),name:kt.string()}).nullable(),test:kt.object({id:kt.string(),name:kt.string()}).nullable()});import{z as gt}from"zod";var bc=gt.object({content:gt.string(),ids:gt.string().array(),tokenLength:gt.number()}),pR=gt.object({chunks:bc.array()}),qz=gt.object({ids:gt.string().array(),score:gt.number(),tokenLength:gt.number()}),Kz=pR.extend({description:gt.string().describe("Input to pass to RAG engine"),tokenLimit:gt.number()}),Vp=gt.object({ids:gt.number().array()}),jp=gt.object({indices:gt.number().array()});var ht=M.object({disableCache:M.boolean().optional(),useMemory:M.boolean().optional(),loggerTags:M.record(M.string(),M.string()).optional(),langfuseSessionId:M.string().optional(),agentConfigVersion:M.string().optional()}),r1=ht.extend({chunks:bc.array(),description:M.string().describe("Input to pass to AI"),type:M.union([M.literal("locator"),M.literal("assertion"),M.literal("ai-action")]),softTokenLimit:M.number(),hardTokenLimit:M.number()}),gR=M.object({screenshotBase64AfterCommand:M.string(),urlAfterCommand:M.string(),serializedCommand:M.string(),elementInteracted:M.string().optional(),thoughts:M.string().optional()}),Wp=M.object({goal:M.string(),browserState:M.string(),screenshot:M.string(),source:Ap.optional().catch(void 0),memory:M.discriminatedUnion("type",[ua,M.object({type:M.literal("RESOLVED_TRACES"),traces:M.unknown().array()})]).optional()}),$p=M.object({target:M.string().or(M.number()),browserState:M.string().optional(),screenshot:M.string().optional(),boundingBox:M.object({x:M.number(),y:M.number(),height:M.number(),width:M.number()}).optional()}),qp=M.object({goal:M.string(),browserState:M.string(),screenshot:M.string().optional(),returnSchema:M.string().optional()}),hR=M.literal("NEGATED_CHECK"),Kp=M.object({goal:M.string(),browserState:M.string(),screenshot:M.string(),url:M.string(),contextChoice:ec.optional(),memory:M.discriminatedUnion("type",[Xl,M.object({type:M.literal("RESOLVED_TRACES"),traces:M.unknown().array()})]).optional(),source:hR.optional()}),Yp=M.object({command:zn}),vc=M.object({goal:M.string(),browserState:M.string(),startingScreenshot:M.string().optional(),screenshot:M.string(),url:M.string(),history:gR.array(),actionHint:M.string().optional(),lastError:M.string().optional()}),Xp=M.object({results:wa.array(),errorMessage:M.string(),errorStack:M.string().optional()}),Jp=M.object({results:wa.array(),goal:M.string(),errorMessage:M.string()}),Qp=M.object({failedResults:wa.array(),nextStepsSerialized:M.string().array(),currentUrl:M.string(),currentPageState:M.string(),currentScreenshot:M.string(),customInstructions:M.string().optional(),testDescription:M.string().optional()}),n1=M.object({description:M.string(),type:M.union([M.literal("locator"),M.literal("assertion"),M.literal("ai-action")]),excerpt:M.string()}),Zp=M.object({type:M.string(),browserContext:M.string(),currentStep:M.string(),screenshot:M.string()});import{z as si}from"zod";var a1=si.object({goal:si.string()}),eg=si.object({keywords:si.array(si.string())});import{z as Ac}from"zod";var Ia=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Ia||{}),c1=Ac.nativeEnum(Ia),fR=Ac.enum(["v1","v2"]),u1=fR.or(Ac.string().describe("for people with special configurations"));import{z as Ie}from"zod";var tg=Ie.object({attributesRequired:Ie.array(Ie.string()).optional(),textRequired:Ie.boolean().optional(),boundsRequired:Ie.boolean().optional()}),rg=Ie.object({id:Ie.number(),thoughts:Ie.string(),requirements:tg.optional(),additionalElements:Ie.object({id:Ie.number(),requirements:tg}).array().optional()}),ng=Ie.object({description:Ie.string(),screenXml:Ie.string(),screenshot:Ie.string()}),og=Ie.object({assertion:Ie.string(),screenXml:Ie.string(),screenshot:Ie.string()}),ig=Ie.object({thoughts:Ie.string(),result:Ie.boolean(),relevantElements:Ie.array(Ie.number()).optional()});import{z as on}from"zod";var ag=on.object({id:on.string().uuid(),skipped:on.boolean().optional(),envKey:on.string().optional().describe("key in the environment to save the result of this step to")}),wc=ag.merge(ma).extend({type:on.literal("REQUEST")}),Rc=ag.merge(pa).extend({type:on.literal("JAVASCRIPT")}),Cc=on.discriminatedUnion("type",[Rc,wc]);import{z as Ut}from"zod";import{z as an}from"zod";var SR=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Jn=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 Pa=an.string().min(1).max(255).superRefine((r,e)=>{try{xc(r)}catch(t){return e.addIssue({code:an.ZodIssueCode.custom,message:t.message,fatal:!0}),an.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(SR))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Oa=an.preprocess(r=>r===null?"":r,an.union([an.string().url(),an.literal("")])).optional();var sg=Ut.object({id:Ut.string(),name:Pa,description:Ut.string().optional().nullish(),baseUrl:Oa.nullish(),schemaVersion:Ut.string(),advanced:Ut.unknown().optional(),retries:Ut.number(),envs:Ut.array(xa).nullish(),parameters:Ca.nullish()}),ER=Ut.object({createdAt:Ut.coerce.date(),updatedAt:Ut.coerce.date(),schedule:Yn.nullish(),notification:Xn.nullish(),createdBy:Ut.string(),organizationId:Ut.string()}),yR=sg.merge(ER),k1=yR.extend({steps:Cc.array()}),U1=sg.extend({steps:Cc.array()});import{z as At}from"zod";var lg=At.object({startedAt:At.coerce.date(),finishedAt:At.coerce.date(),status:At.nativeEnum(et),message:At.string().optional(),data:At.unknown().optional()}),TR=lg.merge(Rc).extend({type:At.literal("JAVASCRIPT")}),bR=lg.merge(wc).extend({type:At.literal("REQUEST")}),vR=At.discriminatedUnion("type",[TR,bR]),cg=At.object({startedAt:At.coerce.date(),finishedAt:At.coerce.date().nullish(),status:At.nativeEnum(me),results:vR.array(),failureReason:At.string().nullish(),failureDetails:va.nullish()});import{z as wt}from"zod";var AR=wt.object({id:wt.string(),organizationId:wt.string(),createdAt:wt.coerce.date(),updatedAt:wt.coerce.date(),createdBy:wt.string(),scheduledAt:wt.coerce.date().nullish(),startedAt:wt.coerce.date().nullish(),finishedAt:wt.coerce.date().nullish(),status:wt.nativeEnum(me),trigger:wt.nativeEnum(Dt),results:cg.array().nullish(),apiTestName:wt.string().nullish(),apiTestPath:wt.string().nullish(),apiTestId:wt.string().nullish()}),q1=AR.pick({status:!0,startedAt:!0,finishedAt:!0});var li=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(li||{}),ug=3;function wR(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function _c(r){if(!wR(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 Mc(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return ug;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 La=class{trackStepExecution(){}async flush(){}};import{parseString as RR,splitCookiesString as CR}from"set-cookie-parser";import{z as ue}from"zod";var Ic=ue.object({name:ue.string(),value:ue.string(),url:ue.string().optional(),domain:ue.string().optional(),path:ue.string().optional(),expires:ue.number().default(Date.now()/1e3+60*60*24*365),httpOnly:ue.boolean().optional(),secure:ue.boolean().default(!0),sameSite:ue.union([ue.literal("Strict"),ue.literal("Lax"),ue.literal("None")]).default("None")});function Na(r,e){let t=[],n=CR(r);for(let o of n){let i=RR(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=Ic.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,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:m})}}return t}var xR=ue.object({origin:ue.string(),localStorage:ue.array(ue.object({name:ue.string(),value:ue.string()}))}),_R=ue.object({entries:ue.record(ue.string(),ue.array(ue.tuple([ue.unknown(),ue.unknown()]))),version:ue.number().optional()}),dg=ue.object({cookies:Ic.array().optional(),origins:xR.array().optional(),idb:ue.record(ue.string(),_R).optional().describe("key is db name")});function mg(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Ic.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 BR from"zod";import{v4 as fG}from"uuid";import{z as le}from"zod";import*as Se from"zod";var pg=Se.object({requiredText:Se.string().optional(),requiredAttributes:Se.record(Se.string(),Se.string()).optional(),requiredBounds:Se.boolean().optional()}),MR=Se.object({xPath:Se.string(),requirements:pg.optional()}),IR=Se.object({type:Se.literal("NATIVE"),bounds:Se.number().array(),resolvedDescription:Se.string(),xPath:Se.string(),elementOnlySerializedXml:Se.string(),requirements:pg.optional(),requiredRelatedElements:MR.array().optional()}),PR=Se.object({type:Se.literal("WEBVIEW"),resolvedDescription:Se.string(),xPath:Se.string(),browserCache:wr.optional()}),gg=Se.discriminatedUnion("type",[IR,PR]);var sn=(s=>(s.AI_CHECK="AI_CHECK",s.TAP="TAP",s.TYPE="TYPE",s.PRESS="PRESS",s.OPEN_APP="OPEN_APP",s.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",s.JAVASCRIPT="JAVASCRIPT",s.ADB="ADB",s.STATE="STATE",s))(sn||{}),Pc=(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))(Pc||{}),hg=le.discriminatedUnion("type",[le.object({type:le.literal("description"),description:le.string()}),le.object({type:le.literal("coordinates"),xPercent:le.number(),yPercent:le.number()})]),gr=le.object({id:le.string().uuid(),disableCache:le.boolean().optional()}),OR=gr.extend({type:le.literal("STATE")}),fg=le.object({target:gg}),Oc=gr.extend({type:le.literal("TAP"),target:hg,cache:fg.optional()}),Lc=gr.extend({type:le.literal("TYPE"),target:hg.optional(),cache:fg.optional(),text:le.string()}),LR=gr.extend({type:le.literal("OPEN_NOTIFICATION_DRAWER")}),NR=gr.extend({type:le.literal("PRESS"),key:le.nativeEnum(Pc)}),DR=gr.extend({type:le.literal("OPEN_APP"),packageName:le.string(),activityName:le.string().optional()}),kR=gr.extend({type:le.literal("AI_CHECK"),assertion:le.string(),timeoutSecs:le.number().optional()}),UR=gr.extend({type:le.literal("JAVASCRIPT"),code:le.string(),timeout:le.number().int().max(60).optional().describe("Max seconds for the code to complete")}),FR=gr.extend({type:le.literal("ADB"),command:le.string()}),Sg=le.discriminatedUnion("type",[Oc,Lc,NR,DR,LR,kR,UR,FR,OR]);var Nc=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var Eg={type:!0,cache:!0},Pr=BR.discriminatedUnion("type",[Oc.pick(Eg),Lc.pick(Eg)]),zR=Object.values(sn).filter(r=>Pr.options.some(e=>e.shape.type.safeParse(r).success));function Da(r){return zR.includes(r.type)}var yg=Jo(Pr),Tg=Qo(Pr),wG=ya(Pr);import{cloneDeep as ci}from"lodash-es";import bg from"truncate-json";var GR="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",HR=[tn,qn],vg=[tn,qn],Qn=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[tn],o=e.env[qn],i={};for(let[l,c]of Object.entries(e.env))vg.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=ci(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){HR.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[tn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ci(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>vg.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,GR]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=bg(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=bg(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=ci(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(tn,e.envName),e.testName&&this.setMomenticSystemVariable(qn,e.testName)}getDynamicVariablesCopy(){return ci(this.env)}getVariablesFromEnvironmentCopy(){return ci(this.varsFromMomenticEnvironment)}};import Or from"zod";import ui from"zod";var VR=ui.object({id:ui.string().uuid(),envKey:ui.string().optional()}),hr=VR.extend({type:ui.literal("MOBILE_PRESET_STEP"),command:Sg}),OG=ui.discriminatedUnion("type",[hr]);import Pe from"zod";var Zn=Pe.object({startTime:Pe.number(),endTime:Pe.number().optional(),error:Pe.string().optional()});var Dc=Zn.extend({type:Pe.literal("SECTION"),name:Pe.string(),subSpans:Pe.lazy(()=>YR.array())}),jR=Zn.extend({type:Pe.literal("AI_LOCATOR_CALL"),result:Pe.object({serializedElement:Pe.string(),id:Pe.number(),thoughts:Pe.string()}).optional()}),WR=Zn.extend({type:Pe.literal("AI_ASSERTION_CALL"),result:Pe.object({thoughts:Pe.string(),result:Pe.boolean()}).optional()}),$R=Zn.extend({type:Pe.literal("WAIT_FOR_STABILITY"),reason:Pe.string().optional()}),qR=Zn.extend({type:Pe.literal("RESOLVE_TARGET_CACHE"),result:Pe.object({serializedElement:Pe.string()}).optional()}),KR=Zn.extend({type:Pe.literal("GET_EMULATOR_STATE")}),YR=Pe.discriminatedUnion("type",[Dc,jR,WR,$R,qR,KR]);var XR=Or.object({message:Or.string().optional(),startTime:Or.number(),endTime:Or.number(),status:Or.nativeEnum(et),trace:Dc.optional().catch(void 0),beforeSnapshot:Or.string().optional(),afterSnapshot:Or.string().optional()}),JR=hr.merge(XR).extend({data:Or.unknown().optional().describe("output data from the step")}),eo=JR;import Ge from"zod";import{z as Wt}from"zod";import{z as Ce}from"zod";var jt=Ce.object({id:Ce.string(),name:Pa,baseUrl:Oa,description:Ce.string().optional().nullish(),schemaVersion:Ce.string(),advanced:oi,retries:Ce.number(),envs:Ce.array(xa).nullish(),parameters:Ca.nullish(),disabled:Ce.boolean().optional(),labels:Ce.array(Ce.string()).optional().catch([])}),WG=Ce.enum(["INHERIT","ENABLED","DISABLED"]);var QR=oi.extend({failureRecovery:Ce.boolean().or(Ce.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Ce.boolean().or(Ce.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var $G=jt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:QR}),qG=jt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),ZR=Ce.object({labels:Ce.array(Ce.string()).optional(),outputs:Up.nullish()}),to=jt.merge(ZR),eC=Ce.object({createdAt:Ce.coerce.date(),updatedAt:Ce.coerce.date(),updatedBy:Ce.string().nullable(),schedule:Yn,notification:Xn,createdBy:Ce.string(),organizationId:Ce.string(),folderId:Ce.string().nullable().optional()}),tC=jt.merge(eC),KG=tC.merge(jn),ka=jt.merge(jn),YG=jt.merge(Zr);var Ag="test",wg="module",rC="mobile-test",Xe=(t=>(t.TEST=`${Ag}.yaml`,t.MODULE=`${wg}.yaml`,t))(Xe||{}),qe=(n=>(n.TEST=`momentic/${Ag}`,n.MODULE=`momentic/${wg}`,n.MOBILE_TEST=`momentic/${rC}`,n))(qe||{}),rH=jt.merge(Zr),Rg=Ot.extend({steps:Wt.array(Wt.record(Wt.string(),Wt.unknown())),schemaVersion:Wt.string()}),nH=Rg.extend({fileType:Wt.literal(qe.MODULE)}),oH=Wt.object({test:Wt.string().describe("YAML for the test, including metadata and steps"),modules:Wt.record(Wt.string(),Wt.string()).describe("Map of module name to YAML for the module")});var di=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(di||{});var nC=Ge.object({disableDefaultWebviewAccessibilityTree:Ge.boolean().optional(),autoGrantPermissions:Ge.boolean().optional()}),kc=nC.extend({region:Ge.nativeEnum(di).optional()}),mi=Ge.object({retries:Ge.number().optional().describe("number of retries to run"),defaultChannel:Ge.string().optional().describe("default channel to use"),defaultTag:Ge.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ge.string().optional(),emulator:kc.optional()}),ln=Ge.object({id:Ge.string().uuid(),description:Ge.string(),schemaVersion:Ge.string(),settings:mi.optional()}),oC=ln.merge(Ge.object({steps:Ge.array(hr)})),cn=Ge.object({fileType:Ge.literal(qe.MOBILE_TEST)}).merge(oC),dH=Ge.object({name:Ge.string(),steps:Ge.array(hr).optional(),settings:mi.optional()});var MH=new Set(Object.values(Ze));var iC={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"},IH={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:[]},PH={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."},OH={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},LH={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 button on the device or on the screen.",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."};import aC from"semver";import{z as sC}from"zod";var UH=sC.string().refine(r=>aC.valid(r),{message:"must be a valid semver string"});import{Faker as zH,en as GH}from"@faker-js/faker";import{z as O}from"zod";var VH=O.object({body:O.string(),to:O.string(),from:O.string()}),jH=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()}),WH=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),$H=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()}),qH=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 Ua=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Ua||{}),Cg=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),lC=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(),cC=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(),xg=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()}),KH=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:lC,response:cC,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(Ua).optional()}),Lr=15e3;import*as at from"zod";import{extendZodWithOpenApi as uC}from"zod-openapi";uC(at);var dC=at.object({url:at.string(),lineNumber:at.number(),columnNumber:at.number()}).openapi({ref:"CodeLocation"}),Fa=at.object({timestamp:at.number(),text:at.string(),type:at.string(),tabIndex:at.number(),args:at.unknown().array().optional(),url:at.string().optional(),location:dC.optional()}).openapi({ref:"ConsoleLog"}),_g=Fa.array(),mC=_g.array();import*as Uc from"zod";import{extendZodWithOpenApi as OC}from"zod-openapi";import{z as C}from"zod";var pC=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),gC=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),hC=C.object({onContentLoad:C.number().optional(),onLoad:C.number().optional(),comment:C.string().optional()}),Ig=C.object({startedDateTime:C.string(),id:C.string(),title:C.string().optional(),pageTimings:hC,comment:C.string().optional()}),fC=C.array(Ig),SC=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()}),Pg=C.array(SC),EC=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),Og=C.array(EC),yC=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),TC=C.array(yC),bC=C.object({name:C.string(),value:C.string().optional(),fileName:C.string().optional(),contentType:C.string().optional(),comment:C.string().optional()}),vC=C.array(bC),AC=C.object({mimeType:C.string(),params:vC,text:C.string(),comment:C.string().optional()}),wC=C.object({method:C.string(),url:C.string(),httpVersion:C.string().optional(),cookies:Pg,headers:Og,queryString:TC,postData:AC.optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional()}),RC=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()}),CC=C.object({status:C.number(),statusText:C.string(),httpVersion:C.string().optional(),cookies:Pg,headers:Og,content:RC,redirectURL:C.string().optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional(),_mocked:C.boolean().optional()}),Mg=C.object({expires:C.string().optional(),lastAccess:C.string(),eTag:C.string(),hitCount:C.number(),comment:C.string().optional()}),xC=C.object({beforeRequest:Mg.optional(),afterRequest:Mg.optional(),comment:C.string().optional()}),_C=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()}),Lg=C.object({pageref:C.string().optional(),startedDateTime:C.string(),time:C.number().optional(),request:wC,response:CC.optional(),cache:xC.optional(),timings:_C,serverIPAddress:C.string().optional(),connection:C.string().optional(),comment:C.string().optional(),_resourceType:C.string().optional()}),MC=C.array(Lg),IC=C.object({version:C.string().default("1.1"),creator:pC.optional(),browser:gC.optional(),pages:fC.optional(),entries:MC,comment:C.string().optional()}),PC=C.object({log:IC}),Ng=C.record(C.string(),Ig),Dg=C.record(C.string(),Lg);OC(Uc);var LC=Uc.object({logsPerPage:Fa.array().array(),harPages:Ng.optional(),harEntries:Dg.optional()}).openapi({ref:"DebugData"});var A=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}}},ro=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Nr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
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}
|
|
3
3
|
Decisions:
|
|
4
4
|
${this.decisions.map(e=>e.toString()).join(`
|
|
5
|
-
`)}`}};function kg(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Fc(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 Zt=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Ba=class extends Zt{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},za=class extends Zt{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function Ug(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function gi(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 Bc(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 pi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as NC}from"lodash-es";import{z as er}from"zod";var Ga=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.AiPageSummary="ai_page_summary",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(Ga||{});var Fg=er.union([er.string(),er.number(),er.boolean(),er.null(),er.record(er.string(),er.lazy(()=>Fg)),er.array(er.lazy(()=>Fg))]),zc=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=NC(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Ga).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")}},Gc=new zc({},{});var Hc={".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"},Bg=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],zV=Object.keys(Hc);import*as zg from"zod";var HV=zg.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as Dr}from"zod";var WV=Dr.object({id:Dr.string(),name:Dr.string(),createdAt:Dr.coerce.date(),createdBy:Dr.string(),updatedAt:Dr.coerce.date(),updatedBy:Dr.string().nullable(),organizationId:Dr.string()});import{z as I}from"zod";import kr from"zod";var no=kr.object({platformSep:kr.string(),fullPathSegments:kr.string().array(),relativePathSegments:kr.string().array(),relativePath:kr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:kr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:kr.coerce.date(),createdAt:kr.coerce.date()});var DC=I.array(no.extend({id:I.string(),name:I.string(),description:I.string().optional(),labels:I.string().array().optional()})),kC=I.array(no.extend({id:I.string(),name:I.string(),description:I.string().optional(),content:ei})),oj=I.object({tests:DC,modules:kC,labels:I.string().array()}),ij=ka.merge(to),aj=I.object({schemaVersion:I.string(),stepLists:jn}),sj=to.partial().merge(jt.pick({id:!0})),UC={name:I.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:I.string().optional(),baseUrl:I.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:I.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:I.nativeEnum(Mr).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ra.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:I.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},lj=I.object(UC),cj=ka.merge(I.object({relativeFilePath:I.string().describe("relative to project root")})),uj=I.object({name:I.string()}),dj=I.object({relativeFilePath:I.string()}),mj=I.object({name:I.string()}),pj=I.object({relativeFilePath:I.string()}),gj=I.object({name:I.string(),description:I.string(),enabled:I.boolean(),steps:I.lazy(()=>$e.array()),testFilePath:I.string().describe("relative to the project root"),folderPath:I.string().optional().describe("user selected folder path")}),hj=I.object({name:I.string(),description:I.string(),enabled:I.boolean()}).partial();var fj=I.array(Mp),Sj=I.object({defaultEnv:I.string().optional().describe("name of the default env, or undefined to unset")}),Ej=I.object({configFilePath:I.string().describe("full path on disk")}),yj=I.string().array(),Tj=I.object({message:I.string(),newRelativeTestPath:I.string().optional()}),Vc=I.object({name:I.string(),absolutePath:I.string(),relativePath:I.string(),pathSegments:I.array(I.string()),isDirectory:I.boolean(),size:I.number(),createdAt:I.coerce.date(),modifiedAt:I.coerce.date(),accessedAt:I.coerce.date()}),Gg=I.object({pathSegments:I.array(I.string())}),bj=I.object({absolutePath:I.string(),pathSegments:I.array(I.string()),contents:I.array(Vc)}),Hg=I.object({pathSegments:I.array(I.string())}),Vg=I.object({pathSegments:I.array(I.string()),newPathSegments:I.array(I.string())}),jg=I.object({pathSegments:I.array(I.string()),recursive:I.boolean().optional()}),vj=I.object({success:I.boolean(),message:I.string(),pathSegments:I.array(I.string()).optional()});var Ha=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Va=Ha.map(r=>`**/${r}/**`),Wg=!0,hi=!1;import tr from"chalk";import FC from"safe-stable-stringify";import BC from"truncate-json";import zC from"zod";var un=FC.configure({deterministic:!1});function $g(r){let e=un(r),{jsonString:t}=BC(e,1e4);return t}var GC=["app","version","env","namespace","host"];function de(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!GC.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Wa=zC.enum(["debug","info","warn","error"]);var fi={debug:20,info:30,warn:40,error:50},$a={20:"debug",30:"info",40:"warn",50:"error"},jc=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=fi[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=un(c,void 0,2),s=s.split(`
|
|
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(`
|
|
6
6
|
`).map((u,d)=>d>0?` ${u}`:u).join(`
|
|
7
|
-
`),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l
|
|
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 $a[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=fi[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,tr.reset,...e)}info(...e){this.logWithLevel(30,tr.white,...e)}debug(...e){this.logWithLevel(20,tr.dim,...e)}warn(...e){this.logWithLevel(40,tr.yellow,...e)}error(...e){this.logWithLevel(50,tr.red,...e)}success(...e){this.logWithLevel(1/0,tr.green,...e)}dimmed(...e){this.logWithLevel(30,tr.dim,...e)}underline(...e){this.logWithLevel(40,tr.underline,...e)}bold(...e){this.logWithLevel(40,tr.bold,...e)}grey(...e){this.logWithLevel(20,tr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Wc=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},Ij=new Wc,HC=typeof window>"u"&&typeof process<"u"&&Wa.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Wa.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,w=new jc(HC,{}),dn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>dn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},ja={},qa=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=ja[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},ja[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=ja[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete ja[e]},n)};import{z as pe}from"zod";var VC=pe.array(no.extend({id:pe.string(),name:pe.string(),description:pe.string().optional(),labels:pe.string().array().optional()})),jC=pe.array(no.extend({id:pe.string(),name:pe.string(),description:pe.string().optional(),content:ei})),qg=pe.object({name:pe.string(),description:pe.string().optional(),steps:pe.array(hr).optional(),settings:mi.optional(),pathSegments:pe.string().array()}),kj=pe.object({id:pe.string(),fileName:pe.string(),fullPath:pe.string(),relativeFilePath:pe.string().describe("relative to project root")});var Kg=pe.object({steps:pe.array(hr).optional(),settings:mi.optional()}),Uj=pe.object({message:pe.literal("ok")}),Yg=pe.object({tag:pe.string(),channel:pe.string(),filePath:pe.string()}),Fj=pe.object({tests:VC,modules:jC,labels:pe.string().array()});import{z as Ue}from"zod";var Xg=Ue.object({id:Ue.string(),createdAt:Ue.coerce.date(),createdBy:Ue.string(),organizationId:Ue.string(),name:Ue.string(),description:Ue.string().nullish(),enabled:Ue.boolean(),schemaVersion:Ue.string().describe("Schema version for steps"),parameters:Ue.string().array().nullish().describe("Parameter list"),parameterEnums:Ue.record(Ue.string(),Ue.string().array()).nullish(),defaultParameters:Ue.record(Ue.string(),Ue.string()).nullish(),defaultCacheKey:Ue.string().nullish(),defaultCacheTtl:Ue.number().nullish(),defaultCacheAllInvocations:Ue.boolean().nullish(),autoAuth:Ue.boolean().nullish(),advanced:ac.nullish()}),qj=Xg.extend({steps:Ue.lazy(()=>pt.array())}),Kj=5*60*1e3,WC=Ot.merge(Xg.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as Jj}from"date-fns-tz";import{z as Ee}from"zod";var $c=yc.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")}),qc=Ee.object({fakerConstantSeed:Ee.boolean().optional()}),nW=Ee.object({ai:$c.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:qc.optional()}),oW=Ee.object({globalOverrides:Ee.record(Ee.string()).optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional()}),iW=Ee.record(Ee.string(),Ee.string()).nullish();import*as S from"zod";import{z as Le}from"zod";var Kc=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Kc||{});var $C=Le.object({type:Le.literal("DESCRIPTION_UPDATE"),thoughts:Le.string()}),Ka=Le.discriminatedUnion("type",[$C]),qC=Le.object({testId:Le.string(),name:Le.string(),orgId:Le.string(),runId:Le.string(),steps:$e.array(),purpose:Le.nativeEnum(Kc),details:Ka.or(Ka.array()).optional()});var cW=qC.pick({name:!0,orgId:!0}),KC=Le.object({id:Le.string(),name:Le.string().nullish(),createdAt:Le.string().pipe(Le.coerce.date()).or(Le.date()),organizationId:Le.string(),schemaVersion:Le.string(),runId:Le.string().nullish(),purpose:Le.nativeEnum(Kc),details:Ka.or(Ka.array()).optional(),applied:Le.boolean().nullish(),appliedAt:Le.coerce.date().nullish()}),Jg=KC.extend({steps:$e.array()});var Qg="x-momentic-cli-version",Zg="x-momentic-cli-type",YC="x-momentic-main-branch-name",XC="x-momentic-branch-name",JC="x-momentic-commit-timestamp",QC="x-momentic-last-commit-on-main",ZC="x-momentic-last-commit-on-main-timestamp",ex="x-momentic-merged-branch-name",RW=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),CW=ht.merge(vc),eh=Ea,xW=ht.merge(vc);var _W=ht.merge(Kp).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Yc=Jm,MW=ht.merge(Yp),th=Sp,IW=ht.merge(Wp),rh=fp,PW=ht.merge($p),nh=gp,OW=ht.merge(qp);var LW=ht.merge(Zp),NW=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()}),oh=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var DW=S.string().array(),kW=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")})]),ih=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"))}),tx=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),UW=tx.array(),FW=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Zr);function Xc(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[YC]=encodeURIComponent(e)),t&&(a[XC]=encodeURIComponent(t)),n&&(a[JC]=n.toISOString()),o&&(a[QC]=encodeURIComponent(o)),i&&(a[ZC]=i.toISOString()),r.mergedGitBranchName&&(a[ex]=encodeURIComponent(r.mergedGitBranchName)),a}var BW=S.object({entries:S.array(lp),testId:S.string()}),zW=S.object({entries:S.array(yg),testId:S.string()}),GW=S.object({testId:S.string()});function ah(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 sh=ah(cp),lh=ah(Tg),ch=S.object({trigger:S.nativeEnum(Dt),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()}),HW=S.object({id:S.string()}),uh=S.object({status:S.nativeEnum(me),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),dh=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(Dt),schemaVersion:S.string().optional(),section:S.nativeEnum(_a).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),VW=S.object({id:S.string()}),rx=Tc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),mh=rx.array(),ph=Tc.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(),jW=S.object({id:S.string()}),gh=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()}),WW=S.object({screenshot:S.string()}),hh=S.object({key:S.string()}),fh=S.object({orgId:S.string(),userId:S.string()}),Sh=S.array(_p),$W=S.record(S.string(),S.union([S.string(),S.boolean()])),qW=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Eh=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),KW=S.object({suiteRunIds:S.string().array()}),YW=Gp.array(),XW=S.object({runGroupIds:S.string().array()}),nx=S.object({uploadUrl:S.string()}),JW=ht.merge(Xp),QW=ht.merge(Qp),ZW=ht.merge(Jp),ox=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()}),ix=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(li),properties:ox}),e$=ix.array(),yh=Jg.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),t$=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),Th=Fp.array(),r$=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),bh=nx.extend({id:S.string()}),n$=S.object({runGroupId:S.string().uuid().optional()}),vh=S.object({runGroupId:S.string().uuid()}),Ah=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),o$=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()}),i$=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),a$=ht.merge(ng),s$=ht.merge(og),l$=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(di).optional()}),wh=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),c$=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Rh=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Ch=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 ax=3,m$=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()})),xh=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(xh||{});var Jc=W.object({name:W.string(),description:W.string().nullish(),effect:W.nativeEnum(xh),labels:W.array(W.string()),githubRepository:W.string().nullish(),gitlabProjectPath:W.string().nullish(),gitBranchName:W.string().nullish()}),sx=W.object({type:W.literal("LAST_N_RUNS"),lastN:W.number().min(ax).max(10)}),lx=W.object({type:W.literal("LAST_N_HOURS"),lastN:W.number().min(1).max(24)}),cx=W.object({type:W.literal("LAST_N_DAYS"),lastN:W.number().min(1).max(7)}),Qc=W.discriminatedUnion("type",[sx,lx,cx]),ux=W.object({flakeRateThreshold:W.number().min(1).max(100),evaluationWindow:Qc}),dx=Jc.extend({type:W.literal("FLAKE_RATE"),config:ux}),mx=W.object({passRateThreshold:W.number().min(1).max(100),evaluationWindow:Qc}),px=Jc.extend({type:W.literal("PASS_RATE"),config:mx}),gx=W.object({failureCountThreshold:W.number().min(0),evaluationWindow:Qc}),hx=Jc.extend({type:W.literal("FAILURE_COUNT"),config:gx}),p$=W.discriminatedUnion("type",[dx,px,hx]);import{z as Fe}from"zod";var f$=Fe.object({repositoriesIndexed:Fe.boolean(),indexingInProgress:Fe.boolean(),indexesOutdated:Fe.boolean()}),_h=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(_h||{}),Mh=(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))(Mh||{}),S$=Fe.object({name:Fe.string(),status:Fe.nativeEnum(_h),conclusion:Fe.nativeEnum(Mh).nullable()}),Si=Fe.object({sha:Fe.string(),message:Fe.string(),author:Fe.object({name:Fe.string().optional(),email:Fe.string().optional(),date:Fe.coerce.date().optional()}),committer:Fe.object({name:Fe.string().optional(),email:Fe.string().optional(),date:Fe.coerce.date().optional()})}),Zc=Fe.object({mergedBranch:Fe.string().optional()});import{z as xe}from"zod";var Ih=xe.object({orgId:xe.string(),cacheKeys:xe.string().array()}),T$=xe.object({keyParams:Ih,clientMetadata:xe.string(),lockAcquisitionTimeoutMs:xe.number().optional()}),Ph=xe.object({acquired:xe.boolean(),acquiredByMetadata:xe.string(),keyPrefix:xe.string()}),b$=xe.object({keyPrefix:xe.string(),result:xe.string(),ttlMs:xe.number()}),v$=xe.union([xe.object({keyPrefix:xe.string()}),Ih]),fx=xe.object({remainingTtlMs:xe.number(),value:xe.string().nullish()}),A$=xe.object({results:xe.record(xe.string(),fx),activeLocks:xe.string().array()});var w$=5*60*1e3;var _$=90*24*60*60*1e3,M$=7*24*60*60*1e3;import{z as Oh}from"zod";var O$=Oh.object({quarantineNotifications:Oh.string().nullish()});import{z as tt}from"zod";var Sx=tt.object({version:tt.string(),json:tt.record(tt.unknown()),hash:tt.string()}),Lh=tt.record(tt.unknown()),k$=tt.object({newSvgs:tt.array(Sx),metadata:Lh.optional()}),Ex=tt.object({version:tt.string(),json:tt.record(tt.unknown()).nullish(),hash:tt.string(),description:tt.string().nullish(),metadata:Lh.nullish()}),Nh=tt.record(tt.string().describe("icon hash"),Ex);import{z as Oe}from"zod";var eu=Oe.object({assertion:Oe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),yx=Oe.object({instruction:Oe.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:eu.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.")}),Dh=yx.extend({subSteps:Oe.lazy(()=>Dh.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),kh=Oe.object({name:Oe.string().describe("Short name describing the test plan"),description:Oe.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Uh=kh.extend({id:Oe.string(),createdAt:Oe.coerce.date(),updatedAt:Oe.coerce.date(),updatedBy:Oe.string(),createdBy:Oe.string(),test:Oe.object({id:Oe.string(),name:Oe.string()}).nullish().transform(r=>r??void 0)}),z$=Uh.extend({testGenRuns:Oe.tuple([]).or(Oe.tuple([Oe.object({id:Oe.string(),startedAt:Oe.coerce.date(),status:Oe.nativeEnum(me)})]))}),Fh=Oe.object({preConditions:eu.array().nullish().transform(r=>r??[]),postConditions:eu.array().nullish().transform(r=>r??[]),steps:Dh.array().nullish().transform(r=>r??[])}),G$=Uh.extend({plan:Fh.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),Tx=kh.extend({plan:Fh.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),H$=Tx.array().nullish().transform(r=>r??[]);import{validator as bx}from"@exodus/schemasafe";function Bh(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{bx(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var zh=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Ya=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as iq}from"zod";var Xa=class{async resolveEntries(){}async saveEntries(){}};var oo=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 vx=j.object({step:$e,status:j.nativeEnum(et),startedAt:j.coerce.date(),finishedAt:j.coerce.date().optional(),healMetadata:j.object({healType:j.nativeEnum(ri).or(j.literal("AI")),healedAt:j.coerce.date()}).optional(),beforeSnapshotId:j.string().uuid().optional(),afterSnapshotId:j.string().uuid().optional(),message:j.string().optional()}),vq=vx.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),Hh="1.0.0",tu=gh.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()}),Vh=tu.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),Aq=tu.merge(ni),wq=Vh.merge(ni),jh=j.object({results:j.array(eo),beforeResults:j.array(eo).optional(),afterResults:j.array(eo).optional()}),Rq=tu.merge(jh),Cq=Vh.merge(jh),Ax=ph.merge(dh).extend({executionType:j.nativeEnum(Kn).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()}),xq=Ax.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),wx=ch.merge(uh).extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),cliVersion:j.string(),labels:j.string().array().optional().default([])}),Ei=wx.extend({updatedAt:j.coerce.date().optional().transform(r=>r??new Date),finishedAt:j.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as Mx}from"url";var qh,Ix=Mx(import.meta.url),Px=Cx(Ix);qh=_x(Px,"..");var yi=qh;w.info(`Setting APPIUM_HOME to ${yi}`);process.env.APPIUM_HOME=yi;var Ox="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.",Lx="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.",Nx="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Kh="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",Yh="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function Dx(){if(!process.env.JAVA_HOME)w.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)&&w.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)=>xx(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");Rx(e)||w.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{Wh("java --version",{stdio:"pipe",encoding:"utf-8"})||(w.error(`Could not find a Java installation. ${Ox}`),process.exit(1))}catch(r){w.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function kx(){process.env.ANDROID_HOME||(w.error(`The ANDROID_HOME environment variable is not set. ${Nx} ${$h()==="darwin"?Kh:Yh}`),process.exit(1))}function Ux(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{Wh(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(w.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${Lx} Finally, ensure that the 'adb' command is available in your shell. ${$h()==="darwin"?Kh:Yh}`),process.exit(1))}catch(e){w.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function Xh(){Dx(),kx(),Ux()}import{Server as yN}from"socket.io";import{randomUUID as Kx}from"crypto";import{faker as Fx}from"@faker-js/faker";import Bx from"assert";import zx from"axios";import*as Gx from"child_process";import Hx from"moment";import*as Vx from"otpauth";import jx from"pg";var Ur=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Jh=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(Jh(d));l=()=>s(Jh(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 Ur(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 Qh(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Na(n,e);t.push(...o)}),t}function Wx(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 $x(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 qx=Object.getPrototypeOf(async function(){}).constructor;async function Zh(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,R)=>{o[v]=R,s[v]=R},d={},m=(v,R)=>{o[v]=R,d[v]=R},p;n.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new qx("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(zx,Hx,c.fakerInstance??Fx,Bx,jx,p,g,Vx,Gx,Qh,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:m,R=>c.sms.send(R),R=>c.sms.fetchLatest(R),c.email,c.sms,c.ai,Wx(a,l),...Object.values(i??{}))),f=!0,y,T;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await $x(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof Ur?T=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:T=v instanceof Error?v.message:`${v}`}return{result:y,variableUpdates:s,persistentVariableUpdates:d,success:f,error:T}}async function ef({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Lr,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=Kx(),m=await Zh(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return w.debug(`[${d}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as Yx,randomUUID as Xx}from"crypto";import Jx from"fetch-retry";var Qx=Jx(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}}),tf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,rf=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function nf({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Lr,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!tf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!rf)throw new Error("Missing lambda auth secret.");let h=Yx("sha256",rf).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let y={id:Xx(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(m=await B(Qx(tf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);p=void 0;break}catch(T){p=T}}if(p)throw l.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=xg.parse(await m.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Fr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await nf(r);else if(r.localTools)e=await ef({...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 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:
|
|
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 Zx}from"lodash-es";async function ru(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Lr,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let m of u){if(m.length<2)continue;let p=m[1].trim(),g;try{g=await Fr({orgId:e,code:p,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 A("UserConfigurationError",`Template fragment '${p}' 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(m[0],h)}return d}async function Ja(r){return of(r)}async function of({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 ru({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 of({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Qa(r,e){for(let{path:t,original:n}of e)Zx(r,t,n)}import e_ from"fetch-retry";var mY=process.env.MAILINATOR_API_KEY,pY=e_(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 sN}from"crypto";import{diff as lN}from"deep-object-diff";import{mkdirSync as cN}from"fs";import{cloneDeep as uN}from"lodash-es";var Za=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function t_(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 es(r,e){let t=t_(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var Of="=",os=";",gu=",";var Lf=8192;var lo={};qv(lo,{getKeyPairs:()=>N_,parseKeyPairsIntoRecord:()=>D_,parsePairKeyValue:()=>Nf,serializeKeyPairs:()=>L_});he();var O_=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 L_(r){return r.reduce(function(e,t){var n=""+e+(e!==""?gu:"")+t;return n.length>Lf?e:n},"")}function N_(r){return r.getAllEntries().map(function(e){var t=O_(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=os+o.metadata.toString()),i})}function Nf(r){var e=r.split(os);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(Of);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=ou(e.join(os))),{key:o,value:i,metadata:a}}}}}function D_(r){return typeof r!="string"||r.length===0?{}:r.split(gu).map(function(e){return Nf(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 is;(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"})(is||(is={}));var k_=",",U_=["OTEL_SDK_DISABLED"];function F_(r){return U_.indexOf(r)>-1}var B_=["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 z_(r){return B_.indexOf(r)>-1}var G_=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function H_(r){return G_.indexOf(r)>-1}var hu=1/0,fu=128,V_=128,j_=128,Su={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:hu,OTEL_ATTRIBUTE_COUNT_LIMIT:fu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:hu,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:fu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:hu,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:fu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:V_,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:j_,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:is.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 W_(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function $_(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 q_(r,e,t,n){n===void 0&&(n=k_);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var K_={ALL:we.ALL,VERBOSE:we.VERBOSE,DEBUG:we.DEBUG,INFO:we.INFO,WARN:we.WARN,ERROR:we.ERROR,NONE:we.NONE};function Y_(r,e,t){var n=t[r];if(typeof n=="string"){var o=K_[n.toUpperCase()];o!=null&&(e[r]=o)}}function Df(r){var e={};for(var t in Su){var n=t;switch(n){case"OTEL_LOG_LEVEL":Y_(n,e,r);break;default:if(F_(n))W_(n,e,r);else if(z_(n))$_(n,e,r);else if(H_(n))q_(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function rt(){var r=Df(process.env);return Object.assign({},Su,r)}function kf(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function as(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=kf(r.charCodeAt(n)),i=kf(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var Uf="1.25.1";var X_="deployment.environment";var J_="process.runtime.name";var Q_="service.name";var Z_="service.instance.id";var eM="telemetry.sdk.name",tM="telemetry.sdk.language",rM="telemetry.sdk.version";var Ff=X_;var Bf=J_;var ss=Q_;var zf=Z_;var Ci=eM,xi=tM,_i=rM;var nM="nodejs";var Gf=nM;var co,ls=(co={},co[Ci]="opentelemetry",co[Bf]="node",co[xi]=Gf,co[_i]=Uf,co);var oM=9,iM=6,aM=Math.pow(10,iM),sM=Math.pow(10,oM);function Hf(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*aM);return[t,n]}function Vf(r){return r[0]*sM+r[1]}function Mi(r){return r[0]*1e6+r[1]/1e3}var pn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(pn||(pn={}));var jf=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 lM=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},cM=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))},Wf=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new jf}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,cM([this._that],lM(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 Ft;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Ft||(Ft={}));var st;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(st||(st={}));var uM=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 _5=function(r){uM(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function $f(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 Bt;(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"})(Bt||(Bt={}));var qf=function(){function r(){this.kind=Bt.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 dM=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 mM(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 Eu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=mM(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=$f(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 yu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Bt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Eu(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 Eu(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 Eu(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:st.HISTOGRAM,dataPoints:n.map(function(i){var a=dM(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 Tu=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},bu=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=function(){function r(e,t,n,o){e===void 0&&(e=new pM),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 pM=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,bu([n,this._counts.length-t],Tu(this._counts.slice(t)),!1)),o.splice.apply(o,bu([0,t],Tu(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(bu([],Tu(this._counts),!1))},r}();var Kf=52,gM=2146435072,hM=1048575,Au=1023,cs=-Au+1,us=Au,Ii=Math.pow(2,-1022);function ds(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&gM)>>20;return n-Au}function ms(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&hM)*Math.pow(2,32);return o+n}function Pi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Xf(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var fM=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)}}(),Br=function(r){fM(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Qf=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ii)return this._minNormalLowerBoundaryIndex();var t=ds(e),n=this._rightShift(ms(e)-1,Kf);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Br("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Br("overflow: "+e+" is > maximum lower boundary: "+n);return Pi(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=cs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return us>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Zf=function(){function r(e){this._scale=e,this._scaleFactor=Pi(Math.LOG2E,e),this._inverseFactor=Pi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ii)return this._minNormalLowerBoundaryIndex()-1;if(ms(e)===0){var t=ds(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 Br("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ii;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Br("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 cs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(us+1<<this._scale)-1},r}();var eS=-10,tS=20,SM=Array.from({length:31},function(r,e){return e>10?new Zf(e-10):new Qf(e-10)});function wu(r){if(r>tS||r<eS)throw new Br("expected scale >= "+eS+" && <= "+tS+", got: "+r);return SM[r+10]}var EM=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},ps=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}(),yM=20,TM=160,Ru=2,bM=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=TM),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 vu),u===void 0&&(u=new vu),d===void 0&&(d=wu(yM)),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<Ru&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ru),this._maxSize=Ru)}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=Xf(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=wu(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=ps.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=ps.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 ps(0,-1);var o=t-n;return new ps(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 rS=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Bt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new bM(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:st.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=EM(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 vM=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},Cu=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=Hf(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var nS=function(){function r(){this.kind=Bt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Cu(e)},r.prototype.merge=function(e,t){var n=Mi(t.sampleTime)>=Mi(e.sampleTime)?t:e;return new Cu(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Mi(t.sampleTime)>=Mi(e.sampleTime)?t:e;return new Cu(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.GAUGE,dataPoints:n.map(function(i){var a=vM(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var AM=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(){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 xu=function(){function r(e){this.monotonic=e,this.kind=Bt.SUM}return r.prototype.createAccumulation=function(e){return new Oi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Oi(t.startTime,this.monotonic,o,t.reset):new Oi(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 Oi(t.startTime,this.monotonic,o,!0):new Oi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.SUM,dataPoints:n.map(function(i){var a=AM(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var gn=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)}}(),nr=function(){function r(){}return r.Drop=function(){return dS},r.Sum=function(){return mS},r.LastValue=function(){return pS},r.Histogram=function(){return gS},r.ExponentialHistogram=function(){return wM},r.Default=function(){return RM},r}();var oS=function(r){gn(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 qf,e}(nr);var iS=function(r){gn(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 xu(!0),e.NON_MONOTONIC_INSTANCE=new xu(!1),e}(nr);var aS=function(r){gn(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 nS,e}(nr);var sS=function(r){gn(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 yu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(nr);var lS=function(r){gn(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 yu(this._boundaries,this._recordMinMax)},e}(nr);var cS=function(r){gn(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 rS(this._maxSize,this._recordMinMax)},e}(nr);var uS=function(r){gn(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 mS;case Z.GAUGE:case Z.OBSERVABLE_GAUGE:return pS;case Z.HISTOGRAM:return t.advice.explicitBucketBoundaries?new lS(t.advice.explicitBucketBoundaries):gS}return F.warn("Unable to recognize instrument type: "+t.type),dS},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(nr);var dS=new oS,mS=new iS,pS=new aS,gS=new sS,wM=new cS,RM=new uS;he();function gs(){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)},CM=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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())})},xM=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}}},_M=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},_u=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[ss]=gs(),e[xi]=ls[xi],e[Ci]=ls[Ci],e[_i]=ls[_i],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 CM(this,void 0,void 0,function(){return xM(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=_M(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 hn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(hn||(hn={}));he();var MM=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())})},IM=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}}},Mu=function(){return Ft.CUMULATIVE},hS=function(r){switch(r){case Z.COUNTER:case Z.OBSERVABLE_COUNTER:case Z.GAUGE:case Z.HISTOGRAM:case Z.OBSERVABLE_GAUGE:return Ft.DELTA;case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:return Ft.CUMULATIVE}},fS=function(r){switch(r){case Z.COUNTER:case Z.HISTOGRAM:return Ft.DELTA;case Z.GAUGE:case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:case Z.OBSERVABLE_COUNTER:case Z.OBSERVABLE_GAUGE:return Ft.CUMULATIVE}};function PM(){var r=rt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Mu:e==="delta"?hS:e==="lowmemory"?fS:(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."),Mu)}function OM(r){return r!=null?r===hn.DELTA?hS:r===hn.LOWMEMORY?fS:Mu:PM()}function LM(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return nr.Default()}}var SS=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=LM(t),this._aggregationTemporalitySelector=OM(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return MM(this,void 0,void 0,function(){return IM(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 NM=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},ES=1e4,yS=5,TS=1e3,bS=5e3,vS=1.5;function Li(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=NM(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 Iu(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Pu(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 Ou(r){return typeof r=="number"?r<=0?Lu(r,ES):r:DM()}function DM(){var r,e=Number((r=rt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:rt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Lu(e,ES):e}function Lu(r,e){return F.warn("Timeout must be greater than 0",r),e}function AS(r){var e=[429,502,503,504];return e.includes(r)}function wS(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 RS=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 Wf(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Ou(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:pn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:pn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:pn.SUCCESS})}).catch(function(n){t({code:pn.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 Nu from"url";import*as fs from"http";import*as Ss from"https";import*as CS from"zlib";import{Readable as UM}from"stream";var Gr;(function(r){r.NONE="none",r.GZIP="gzip"})(Gr||(Gr={}));var kM=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)}}(),uo=function(r){kM(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 hs=function(){return hs=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},hs.apply(this,arguments)};function Du(r,e,t,n,o){var i=r.timeoutMillis,a=new Nu.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 uo("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:hs({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?fs.request:Ss.request,g=function(h,f){switch(h===void 0&&(h=yS),f===void 0&&(f=TS),s=p(m,function(T){var v="";T.on("data",function(R){return v+=R}),T.on("aborted",function(){if(u){var R=new uo("Request Timeout");o(R)}}),T.on("end",function(){if(u===!1)if(T.statusCode&&T.statusCode<299)F.debug("statusCode: "+T.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(T.statusCode&&AS(T.statusCode)&&h>0){var R=void 0;f=vS*f,T.headers["retry-after"]?R=wS(T.headers["retry-after"]):R=Math.round(Math.random()*(bS-f)+f),c=setTimeout(function(){g(h-1,f)},R)}else{var b=new uo(T.statusMessage,T.statusCode,v);o(b),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(T){if(u){var v=new uo("Request Timeout",T.code);o(v)}else o(T);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var T=new uo("Request Timeout");o(T)}clearTimeout(d),clearTimeout(c)}),r.compression){case Gr.GZIP:{s.setHeader("Content-Encoding","gzip");var y=FM(e);y.on("error",o).pipe(CS.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function FM(r){var e=new UM;return e.push(r),e.push(null),e}function ku(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 Nu.URL(r.url),t=e.protocol==="http:"?fs.Agent:Ss.Agent;return new t(hs({keepAlive:!0},r.httpAgentOptions))}catch(n){F.error("collector exporter failed to create http agent. err: "+n.message);return}}function Uu(r){if(r)return r;var e=rt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||rt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Gr.GZIP?Gr.GZIP:Gr.NONE}he();var BM=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)}}(),Es=function(r){BM(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,Li(t.headers),lo.parseKeyPairsIntoRecord(rt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=ku(t),i.compression=Uu(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;Du(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}(RS);function _S(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function zM(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function MS(r){var e=_S(r);return zM(e)}function GM(r){var e=_S(r);return e.toString()}var HM=typeof BigInt<"u"?GM:Vf;function xS(r){return r}function IS(r){if(r!==void 0)return as(r)}var VM={encodeHrTime:MS,encodeSpanContext:as,encodeOptionalSpanContext:IS};function PS(r){var e,t;if(r===void 0)return VM;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?MS:HM,encodeSpanContext:o?xS:as,encodeOptionalSpanContext:o?xS:IS}}var 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};function OS(r){return{name:r.name,version:r.version}}function mo(r){return Object.keys(r).map(function(e){return LS(e,r[e])})}function LS(r,e){return{key:r,value:NS(e)}}function NS(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(NS)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=jM(t,2),o=n[0],i=n[1];return LS(o,i)})}}:{}}function DS(r){return{attributes:mo(r.attributes),droppedAttributesCount:0}}he();function US(r,e){var t=PS(e);return{resource:DS(r.resource),schemaUrl:void 0,scopeMetrics:WM(r.scopeMetrics,t)}}function WM(r,e){return Array.from(r.map(function(t){return{scope:OS(t.scope),metrics:t.metrics.map(function(n){return $M(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function $M(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=XM(r.aggregationTemporality);switch(r.dataPointType){case st.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:kS(r,e)};break;case st.GAUGE:t.gauge={dataPoints:kS(r,e)};break;case st.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:KM(r,e)};break;case st.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:YM(r,e)};break}return t}function qM(r,e,t){var n={attributes:mo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case xt.INT:n.asInt=r.value;break;case xt.DOUBLE:n.asDouble=r.value;break}return n}function kS(r,e){return r.dataPoints.map(function(t){return qM(t,r.descriptor.valueType,e)})}function KM(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:mo(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 YM(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:mo(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 XM(r){switch(r){case Ft.DELTA:return 1;case Ft.CUMULATIVE:return 2}}function FS(r,e){return{resourceMetrics:r.map(function(t){return US(t,e)})}}var Fu={serializeRequest:function(r){var e=FS(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 BS="0.52.1";var zS=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(){return po=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},po.apply(this,arguments)},GS="v1/metrics",JM="http://localhost:4318/"+GS,QM={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+BS},ZM=function(r){zS(e,r);function e(t){var n=r.call(this,t,Fu,"application/json")||this;return n.headers=po(po(po(po({},n.headers),QM),lo.parseKeyPairsIntoRecord(rt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Li(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:rt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Pu(rt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):rt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Iu(rt().OTEL_EXPORTER_OTLP_ENDPOINT,GS):JM},e}(Es),HS=function(r){zS(e,r);function e(t){return r.call(this,new ZM(t),t)||this}return e}(SS);var go;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(go||(go={}));var or;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(or||(or={}));he();var eI=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)}}(),VS=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())})},jS=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}}},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},rI=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))},nI=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 WS(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 $S(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Bu=function(r){eI(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Hr(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Bu("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function qS(r){return VS(this,void 0,void 0,function(){var e=this;return jS(this,function(t){return[2,Promise.all(r.map(function(n){return VS(e,void 0,void 0,function(){var o,i;return jS(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 KS(r){return r.status==="rejected"}function zu(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,rI([],tI(e(n)),!1))}),t}function YS(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=nI(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 XS(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 JS(r,e){return r.toLowerCase()===e.toLowerCase()}he();var zt;(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"})(zt||(zt={}));var Gu=function(){function r(){this.kind=zt.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 ne;(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"})(ne||(ne={}));function ir(r,e,t){var n,o,i,a;return iI(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:xt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function QS(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 ZS(r,e){return JS(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var oI=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function iI(r){return r.match(oI)!=null}var aI=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 sI(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 Ts=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=sI(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=XS(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 bs=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=zt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Ts(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 Ts(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 Ts(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:or.HISTOGRAM,dataPoints:n.map(function(i){var a=aI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ne.GAUGE||e.type===ne.UP_DOWN_COUNTER||e.type===ne.OBSERVABLE_GAUGE||e.type===ne.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 Hu=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},Vu=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))},ju=function(){function r(e,t,n,o){e===void 0&&(e=new lI),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 lI=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,Vu([n,this._counts.length-t],Hu(this._counts.slice(t)),!1)),o.splice.apply(o,Vu([0,t],Hu(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(Vu([],Hu(this._counts),!1))},r}();var eE=52,cI=2146435072,uI=1048575,Wu=1023,vs=-Wu+1,As=Wu,Ni=Math.pow(2,-1022);function ws(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&cI)>>20;return n-Wu}function Rs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&uI)*Math.pow(2,32);return o+n}function Di(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function rE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var dI=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)}}(),Vr=function(r){dI(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var oE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ni)return this._minNormalLowerBoundaryIndex();var t=ws(e),n=this._rightShift(Rs(e)-1,eE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Vr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Vr("overflow: "+e+" is > maximum lower boundary: "+n);return Di(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=vs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return As>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var iE=function(){function r(e){this._scale=e,this._scaleFactor=Di(Math.LOG2E,e),this._inverseFactor=Di(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ni)return this._minNormalLowerBoundaryIndex()-1;if(Rs(e)===0){var t=ws(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 Vr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ni;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Vr("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 vs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(As+1<<this._scale)-1},r}();var aE=-10,sE=20,mI=Array.from({length:31},function(r,e){return e>10?new iE(e-10):new oE(e-10)});function $u(r){if(r>sE||r<aE)throw new Vr("expected scale >= "+aE+" && <= "+sE+", got: "+r);return mI[r+10]}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},Cs=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}(),gI=20,hI=160,qu=2,lE=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=hI),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 ju),u===void 0&&(u=new ju),d===void 0&&(d=$u(gI)),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<qu&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+qu),this._maxSize=qu)}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=rE(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=$u(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Cs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Cs.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 Cs(0,-1);var o=t-n;return new Cs(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 Ku=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=zt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new lE(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:or.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=pI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ne.GAUGE||e.type===ne.UP_DOWN_COUNTER||e.type===ne.OBSERVABLE_GAUGE||e.type===ne.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 fI=iu("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function cE(r){return r.setValue(fI,!0)}he();function uE(){return function(r){F.error(SI(r))}}function SI(r){return typeof r=="string"?r:JSON.stringify(EI(r))}function EI(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 yI=uE();function xs(r){try{yI(r)}catch{}}var dE="1.30.1";var TI="process.runtime.name";var bI="service.name";var vI="telemetry.sdk.name",AI="telemetry.sdk.language",wI="telemetry.sdk.version";var mE=TI;var pE=bI;var ki=vI,Ui=AI,Fi=wI;var RI="nodejs";var gE=RI;var ho,fn=(ho={},ho[ki]="opentelemetry",ho[mE]="node",ho[Ui]=gE,ho[Fi]=dE,ho);function Bi(r){r.unref()}var OI=9,LI=6,NI=Math.pow(10,LI),OJ=Math.pow(10,OI);function Sn(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*NI);return[t,n]}function fo(r){return r[0]*1e6+r[1]/1e3}var zi;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(zi||(zi={}));he();function hE(r,e){return new Promise(function(t){so.with(cE(so.active()),function(){r.export(e,function(n){t(n)})})})}var fE={_export:hE};var DI=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},_s=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=Sn(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Yu=function(){function r(){this.kind=zt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new _s(e)},r.prototype.merge=function(e,t){var n=fo(t.sampleTime)>=fo(e.sampleTime)?t:e;return new _s(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=fo(t.sampleTime)>=fo(e.sampleTime)?t:e;return new _s(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.GAUGE,dataPoints:n.map(function(i){var a=DI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var kI=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},So=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 Ms=function(){function r(e){this.monotonic=e,this.kind=zt.SUM}return r.prototype.createAccumulation=function(e){return new So(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new So(t.startTime,this.monotonic,o,t.reset):new So(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 So(t.startTime,this.monotonic,o,!0):new So(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.SUM,dataPoints:n.map(function(i){var a=kI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var En=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)}}(),Gt=function(){function r(){}return r.Drop=function(){return AE},r.Sum=function(){return wE},r.LastValue=function(){return RE},r.Histogram=function(){return CE},r.ExponentialHistogram=function(){return UI},r.Default=function(){return FI},r}();var SE=function(r){En(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 Gu,e}(Gt);var EE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ne.COUNTER:case ne.OBSERVABLE_COUNTER:case ne.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ms(!0),e.NON_MONOTONIC_INSTANCE=new Ms(!1),e}(Gt);var yE=function(r){En(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 Yu,e}(Gt);var TE=function(r){En(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 bs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Gt);var Is=function(r){En(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 bs(this._boundaries,this._recordMinMax)},e}(Gt);var bE=function(r){En(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 Ku(this._maxSize,this._recordMinMax)},e}(Gt);var vE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ne.COUNTER:case ne.UP_DOWN_COUNTER:case ne.OBSERVABLE_COUNTER:case ne.OBSERVABLE_UP_DOWN_COUNTER:return wE;case ne.GAUGE:case ne.OBSERVABLE_GAUGE:return RE;case ne.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Is(t.advice.explicitBucketBoundaries):CE}return F.warn("Unable to recognize instrument type: "+t.type),AE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Gt);var AE=new SE,wE=new EE,RE=new yE,CE=new TE,UI=new bE,FI=new vE;var xE=function(r){return Gt.Default()},_E=function(r){return go.CUMULATIVE};var Xu=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())})},Ju=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}}},ME=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},BI=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))},IE=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:xE,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:_E,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 Xu(this,void 0,void 0,function(){var t,n,o,i,a,l;return Ju(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(BI([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],ME(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=ME.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(zu(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(zu(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return Xu(this,void 0,void 0,function(){return Ju(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,Hr(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Xu(this,void 0,void 0,function(){return Ju(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,Hr(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();he();var zI=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)}}(),Ps=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())})},Os=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}}},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},HI=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))},Qu=function(r){zI(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 Ps(this,void 0,void 0,function(){var t;return Os(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Hr(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Bu?(F.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(xs(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Ps(this,void 0,void 0,function(){var o,i,a,l,c,s;return Os(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,HI(["PeriodicExportingMetricReader: metrics collection errors"],GI(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),xs(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,fE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==zi.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),Bi(this._interval)},e.prototype.onForceFlush=function(){return Ps(this,void 0,void 0,function(){return Os(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 Ps(this,void 0,void 0,function(){return Os(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}(IE);he();he();function Ls(){return"unknown_service:"+process.argv0}var jr=function(){return jr=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},jr.apply(this,arguments)},VI=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())})},jI=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}}},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},Ns=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[pE]=Ls(),e[Ui]=fn[Ui],e[ki]=fn[ki],e[Fi]=fn[Fi],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 VI(this,void 0,void 0,function(){return jI(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=jr(jr({},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=WI(a,2),s=c[0],u=c[1];return jr(jr(jr(jr({},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 PE=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 yn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ds=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=so.active()),typeof e!="number"){F.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===xt.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,Sn(Date.now()))},r}();var OE=function(r){yn(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}(Ds);var LE=function(r){yn(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}(Ds);var NE=function(r){yn(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}(Ds);var DE=function(r){yn(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}(Ds);var ks=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 kE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ks);var UE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ks);var FE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ks);function Gi(r){return r instanceof ks}var BE=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=ir(e,ne.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new NE(o,n)},r.prototype.createHistogram=function(e,t){var n=ir(e,ne.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new DE(o,n)},r.prototype.createCounter=function(e,t){var n=ir(e,ne.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new LE(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=ir(e,ne.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new OE(o,n)},r.prototype.createObservableGauge=function(e,t){var n=ir(e,ne.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new UE(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=ir(e,ne.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new kE(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=ir(e,ne.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new FE(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 Us=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=ir(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var $I=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)}}(),zE=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}}},qI=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 zE(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 zE(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 $t=function(r){$I(e,r);function e(){return r.call(this,ys)||this}return e}(qI);var KI=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},Fs=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new $t,this._cumulativeMemoStorage=new $t,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=KI(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 m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,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 $t,e},r}();var Zu=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.")},GE=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},Bs=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===go.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=YI(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=Zu(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 $t,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Zu(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=GE(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,s);o.set(c,m,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=Zu(e.keys()),l=a.next();!l.done;l=a.next()){var c=GE(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function YI(r){return Array.from(r.entries())}var XI=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)}}(),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},HE=function(r){XI(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 Fs(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Bs(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new $t;Array.from(t.entries()).forEach(function(a){var l=JI(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}(Us);he();function ed(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 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+`'
|
|
13
14
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
14
15
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
15
16
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
16
|
-
`),t}function
|
|
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+`'
|
|
17
18
|
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
18
|
-
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function
|
|
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
20
|
`,`Details:
|
|
20
|
-
`,
|
|
21
|
-
To resolve the conflict:`,
|
|
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.
|
|
22
23
|
`,`Details:
|
|
23
|
-
`,
|
|
24
|
-
`,td(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 jE=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 WE=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new $t}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===xt.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 $E=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Gi(e)){var o=this._buffer.get(e);if(o==null&&(o=new $t,this._buffer.set(e,o)),typeof t!="number"){F.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===xt.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())})},od=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}}},qE=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},KE=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(){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(Gi));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(Gi)),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 od(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,qS(KE(KE([],qE(n),!1),qE(o),!1))];case 1:return i=l.sent(),a=i.filter(KS).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 od(this,function(s){switch(s.label){case 0:return l=new WE(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Hr(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 od(this,function(s){switch(s.label){case 0:return l=new $E,c=Promise.resolve(i(l)),t!=null&&(c=Hr(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(m){m.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&&YS(n.instruments,t)})},r}();var rP=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)}}(),XE=function(r){rP(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 Fs(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Bs(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}(Us);var JE=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)}}(),Eo=function(){function r(){}return r.Noop=function(){return oP},r}();var nP=function(r){JE(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Eo);var QE=function(r){JE(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}(Eo);var oP=new nP;var iP=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())})},aP=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}}},sP=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},ZE=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new VE,this.observableRegistry=new YE,this.meter=new BE(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,XE);return t.length===1?t[0]:new jE(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,HE);return t},r.prototype.collect=function(e,t,n){return iP(this,void 0,void 0,function(){var o,i,a;return aP(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(WS),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=QS(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),m=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=sP(c,2),u=s[0],d=s[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var p=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,p,Eo.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var lP=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.")},ey=function(){function r(e){this.resource=e,this.viewRegistry=new PE,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=$S(e),n=this.meterSharedStates.get(t);return n==null&&(n=new ZE(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=lP(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 zs=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())})},Gs=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}}},cP=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},uP=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))},ty=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return zs(this,void 0,void 0,function(){var t,n,o,i,a=this;return Gs(this,function(l){switch(l.label){case 0:return t=Sn(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return zs(a,void 0,void 0,function(){var s;return Gs(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,uP([],cP(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 zs(this,void 0,void 0,function(){return Gs(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 zs(this,void 0,void 0,function(){return Gs(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 ry=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())})},ny=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}}},oy=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 dP(r,e){var t=e??Ns.empty();return r?Ns.default().merge(t):t}var id=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new ey(dP((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=oy(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(p){t={error:p}}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=oy(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(p){o={error:p}}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"),uu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new ty(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return ry(this,void 0,void 0,function(){return ny(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 ry(this,void 0,void 0,function(){return ny(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 mP=/[\^$\\.+?()[\]{}|]/g,Hs=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(mP,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var yo=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 iy=function(){function r(e){var t;this._nameFilter=new Hs((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new yo(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 ay=function(){function r(e){this._nameFilter=new yo(e?.name),this._versionFilter=new yo(e?.version),this._schemaUrlFilter=new yo(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 pP(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var ad=function(){function r(e){var t;if(pP(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Hs.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 QE(e.attributeKeys):this.attributesProcessor=Eo.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Gt.Default(),this.instrumentSelector=new iy({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new ay({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var mQ=process.env.APP||"unknown";he();import{v4 as gP}from"uuid";function hP(){return new HS({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:hn.DELTA})}var fP=[new ad({instrumentName:"test_operation_duration_ms",instrumentType:ne.HISTOGRAM,aggregation:new Is([100,500,1e3,5e3,1e4,2e4])})],Vs=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 _u({[ss]:e.serviceName,[Ff]:t,[zf]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:gP()}),o=hP(),i=new Qu({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new id({resource:n,readers:[i],views:fP}),ns.setGlobalMeterProvider(this.provider),this.meter=ns.getMeter("momentic-serverless")}increment(e,t,n){try{let o=es(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=es(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 nt=new Za;function sy(r){r.disabled||(nt=new Vs(r))}import{tmpdir as dN}from"os";import Xd from"path";import{diff as h9}from"deep-object-diff";import{cloneDeep as QQ}from"lodash-es";import{v4 as u9}from"uuid";function cy({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(m,p)=>{try{let g=Pr.parse(p.value);if(g.type!==m.type){o.warn({parsedCacheEntry:g,command:m},"Not using step cache due to type mismatch"),l.push(p.key);return}m.cache=g.cache,a.push(p.key),c.push(p.uniqueKey)}catch(g){l.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},d=(m,p)=>{let g=yP(m.id,p),h=g.find(f=>!!n[f]);if(h)u(m,n[h]);else{if(m.type==="AI_CHECK")return;l.push(g[0])}};for(let m of r)switch(m.type){case"MOBILE_PRESET_STEP":{if(!Da(m.command)||m.command.type==="TYPE"&&!m.command.target||"cache"in m.command&&m.command.cache)continue;s++,d(m.command,i);break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m.type)}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 EP(r,e){return e?`${e}:${r}`:r}function yP(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 sd(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
25
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:EP(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"&&sp(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function js(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 ft(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var bn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},vn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},uy={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},dy={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var q9={CONTENT:"The page"};function my(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 py(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: ${Nc(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Nc(r.target)}`:""}`;case"PRESS":return`Press ${r.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")}}}import{cloneDeep as TP}from"lodash-es";import{v4 as gy}from"uuid";async function To(r){let e=new Map,t=new Set,n=TP(r.steps),o=await bP({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave}}async function bP({steps:r,...e}){let{cacheCreationParams:t,moduleIdParents:n,moduleStepParents:o,createNewCacheIds:i}=e,a={cachesToSave:[],stepsToSave:[]};for(let l of r)switch(l.id=i?gy():l.id,l.type){case"MOBILE_PRESET_STEP":{let s=l.command;s.id=i?gy():s.id,"cache"in s&&s.cache&&(t&&(a.cachesToSave=a.cachesToSave.concat(sd({id:s.id,orgId:t.orgId,testId:t.testId,value:Pr.parse(s),moduleIdParents:n,moduleStepParents:o}))),delete s.cache),a.stepsToSave.push({...l,command:s});break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(l.type)}return a}import{cloneDeep as f7}from"lodash-es";import E7 from"truncate-json";import{v4 as x7}from"uuid";import{cloneDeep as a7,unset as s7}from"lodash-es";import{cloneDeep as O7}from"lodash-es";import{cloneDeep as tee}from"lodash-es";import vZ from"diff-lines";import cd,{gte as wZ}from"semver";var hy={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 fy={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 vP=["target","fromTarget","toTarget"];function Sy(r){for(let e of vP){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var Ey={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 Sy(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Sy(n);return e}default:return e}})};import{v4 as AP}from"uuid";var yy={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=AP()),e;default:return e}})};import{v4 as Ty}from"uuid";var by={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??Ty(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Ty()}})),delete e.commands),e;default:return e}})};var vy={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 wP}from"uuid";var Ay={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=wP()),e))};import{v4 as wy}from"uuid";var Ry={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=wy())}return e.id=wy(),e})};var Cy={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 RP}from"uuid";var xy={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=RP()),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 _y={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 My={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&&Iy(t),e})};function Iy(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Iy(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 Py={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 Oy={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 Ly={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 Ny={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 Dy={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 ky={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 Ws=new Set(["CLICK","TYPE","SELECT_OPTION"]),Uy={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||Ws.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||Ws.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||Ws.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,p=d?.type;(m!==void 0||Ws.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var Fy={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 By={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 $s=[ky,Fy,By,Uy,hy,fy,Ey,yy,by,vy,Ay,Ry,Cy,xy,_y,My,Py,Oy,Ly,Ny,Dy];if(Wn!==$s[$s.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");$s.forEach((r,e)=>{if(!cd.valid(r.toVersion)||!cd.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!cd.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if($s[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{cloneDeep as See}from"lodash-es";import{stringify as Mee}from"yaml";async function q(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 ud({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 An({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 ud({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function qs(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 CP from"picomatch";var Ks=(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||CP(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},Ys=(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}},bo=r=>{try{return new URL(r),!0}catch{return!1}},zy=r=>!r.toLowerCase().startsWith("http"),vo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function wn(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 Gy}from"uuid";function dd(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:dd({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(e.type==="MOBILE_PRESET_STEP"){this.creditsUsedV2+=1;return}let t=_c(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Mc(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:Gy(),properties:dd({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:Gy(),properties:dd({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import jy from"fontoxpath";import{DOMParser as xP,XMLSerializer as _P}from"slimdom";function md(r){return r.toLowerCase().endsWith("webview")}function MP(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 IP=new Set(["index","package","a11y-important"]),PP=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"]),OP=new Set(["live-region","drawing-order"]),LP=new Set(["displayed","enabled"]);function NP(r,e){let t={};for(let[n,o]of Object.entries(e))IP.has(n)||n==="class"&&r===o||PP.has(n)&&o==="false"||n==="text"&&o===""||LP.has(n)&&o==="true"||OP.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function Hy(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 m of e.attributes){let p=m.name,g=m.value;g!=null&&(s[p]=String(g))}let u=NP(e.tagName,s);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),md(e.tagName)&&l?.disallowAccessibilityBridgeForWebviews){for(;t.firstChild;)t.removeChild(t.firstChild);let m=l.injectedWebviewContent??"";m.trim().length>0&&t.appendChild(n.createTextNode(m));return}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m,h=n.createElement(MP(g.tagName));Hy(r,g,h),t.appendChild(h)}}}function DP(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;Hy(a,e,l);let c=new _P().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function Vy(r,e){let t=new xP,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}=DP(t,i,o,e);return{xml:c,originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function kP(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 Js(r,e){let t=r.idToElement.get(e);if(t)return kP(t)}function pd(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 Qs(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 gd(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function $y({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=Qs(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Js(t.graph,r.id)??"",a=pd(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=gd(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:p,requirements:g})=>{let h=t.graph.idToElement.get(p);if(!h)return;let f=Js(t.graph,p);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:gd(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(p=>!!p));let m;return md(n.tagName)?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},m}var Wy=(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=Qs(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 qy(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=jy.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=jy.evaluateXPathToFirstNode(g.xPath,l);if(!h)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);Wy(h,g.requirements)}let s=Qs(c);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Wy(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,m=e.xPath;return u!==void 0&&(d=pd(a,u)??d,m=Js(a,u)??m),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:d,xPath:m}}}function hd(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Da(e)&&(e[t]={...e[t],[n]:o})}function Ky(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}import{execSync as Pb}from"child_process";import{_android as iN,chromium as aN}from"playwright";var Yy={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
|
+
`,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
|
|
26
26
|
var momenticConstants = {
|
|
27
27
|
bannedClassSubstrings: [
|
|
28
28
|
"relative",
|
|
@@ -1457,9 +1457,6 @@ function addAddIdsScript() {
|
|
|
1457
1457
|
customWindow.nextAvailableMomenticId ?? 0,
|
|
1458
1458
|
currentId
|
|
1459
1459
|
);
|
|
1460
|
-
if (!customWindow.idMaintainer) {
|
|
1461
|
-
customWindow.addIdMaintainer?.();
|
|
1462
|
-
}
|
|
1463
1460
|
return currentId;
|
|
1464
1461
|
};
|
|
1465
1462
|
}
|
|
@@ -1482,83 +1479,6 @@ function addGetNextElementScript() {
|
|
|
1482
1479
|
return null;
|
|
1483
1480
|
};
|
|
1484
1481
|
}
|
|
1485
|
-
function addIdMaintainerScript() {
|
|
1486
|
-
const customWindow = window;
|
|
1487
|
-
if (customWindow.addIdMaintainer || customWindow.idMaintainer) {
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
const callback = (mutationList) => {
|
|
1491
|
-
if (!customWindow.addIdsToElement || !customWindow.nextAvailableMomenticId) {
|
|
1492
|
-
return;
|
|
1493
|
-
}
|
|
1494
|
-
for (const mutation of mutationList) {
|
|
1495
|
-
if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
|
|
1496
|
-
for (const nodeRef of mutation.addedNodes) {
|
|
1497
|
-
if (nodeRef.nodeType !== Node.ELEMENT_NODE) {
|
|
1498
|
-
continue;
|
|
1499
|
-
}
|
|
1500
|
-
const node = nodeRef;
|
|
1501
|
-
if (node.getAttribute("data-momentic-id")) {
|
|
1502
|
-
continue;
|
|
1503
|
-
}
|
|
1504
|
-
const nodeBefore = node.previousElementSibling ?? node.parentElement;
|
|
1505
|
-
if (!nodeBefore) {
|
|
1506
|
-
continue;
|
|
1507
|
-
}
|
|
1508
|
-
const nodeAfter = customWindow.getNextElement?.(node);
|
|
1509
|
-
if (!nodeAfter) {
|
|
1510
|
-
continue;
|
|
1511
|
-
}
|
|
1512
|
-
const beforeId = nodeBefore.getAttribute("data-momentic-id");
|
|
1513
|
-
const afterId = nodeAfter.getAttribute("data-momentic-id");
|
|
1514
|
-
if (beforeId === null || afterId === null) {
|
|
1515
|
-
continue;
|
|
1516
|
-
}
|
|
1517
|
-
const beforeIdNum = parseInt(beforeId);
|
|
1518
|
-
const afterIdNum = parseInt(afterId);
|
|
1519
|
-
if (beforeIdNum >= afterIdNum - 1) {
|
|
1520
|
-
continue;
|
|
1521
|
-
}
|
|
1522
|
-
customWindow.addIdsToElement?.(node, beforeIdNum + 1, afterIdNum);
|
|
1523
|
-
}
|
|
1524
|
-
} else if (mutation.type === "attributes") {
|
|
1525
|
-
const target = mutation.target;
|
|
1526
|
-
if (target.nodeType !== Node.ELEMENT_NODE) {
|
|
1527
|
-
continue;
|
|
1528
|
-
}
|
|
1529
|
-
const ele = target;
|
|
1530
|
-
try {
|
|
1531
|
-
const oldId = parseInt(mutation.oldValue ?? "");
|
|
1532
|
-
const newAttr = ele.getAttribute("data-momentic-id");
|
|
1533
|
-
if (!newAttr) {
|
|
1534
|
-
ele.setAttribute("data-momentic-id", \`\${oldId}\`);
|
|
1535
|
-
ele.setAttribute("aria-keyshortcuts", \`\${oldId}\`);
|
|
1536
|
-
}
|
|
1537
|
-
} catch (err) {
|
|
1538
|
-
console.error(\`[MOMENTIC] Failed to update ID in maintainer: \${err}\`);
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
};
|
|
1543
|
-
customWindow.addIdMaintainer = () => {
|
|
1544
|
-
if (customWindow.idMaintainer) {
|
|
1545
|
-
return;
|
|
1546
|
-
}
|
|
1547
|
-
try {
|
|
1548
|
-
const observer = new MutationObserver(callback);
|
|
1549
|
-
customWindow.idMaintainer = observer;
|
|
1550
|
-
observer.observe(document.body, {
|
|
1551
|
-
attributeFilter: ["data-momentic-id"],
|
|
1552
|
-
attributeOldValue: true
|
|
1553
|
-
});
|
|
1554
|
-
} catch (_err) {
|
|
1555
|
-
window.setTimeout(() => {
|
|
1556
|
-
customWindow.addIdMaintainer?.();
|
|
1557
|
-
}, 1e3);
|
|
1558
|
-
return;
|
|
1559
|
-
}
|
|
1560
|
-
};
|
|
1561
|
-
}
|
|
1562
1482
|
|
|
1563
1483
|
// src/html/element-location.ts
|
|
1564
1484
|
function addFindElementInBodyOrShadowDomScript() {
|
|
@@ -3293,6 +3213,36 @@ function addMPathScripts() {
|
|
|
3293
3213
|
customWindow.getMPathSelector = getMPathSelector;
|
|
3294
3214
|
}
|
|
3295
3215
|
|
|
3216
|
+
// src/html/performance-observer.ts
|
|
3217
|
+
function addPerformanceObserver() {
|
|
3218
|
+
const customWindow = window;
|
|
3219
|
+
if (customWindow.performanceObserver) {
|
|
3220
|
+
return;
|
|
3221
|
+
}
|
|
3222
|
+
const obs = new PerformanceObserver((list) => {
|
|
3223
|
+
for (const e of list.getEntriesByType("longtask")) {
|
|
3224
|
+
try {
|
|
3225
|
+
console.warn("[MOMENTIC] Long-running task detected", {
|
|
3226
|
+
start: e.startTime.toFixed(1),
|
|
3227
|
+
dur: e.duration.toFixed(1),
|
|
3228
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming/attribution
|
|
3229
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3230
|
+
attribution: e.attribution?.map((a) => ({
|
|
3231
|
+
name: a.name,
|
|
3232
|
+
entryType: a.entryType,
|
|
3233
|
+
containerType: a.containerType,
|
|
3234
|
+
containerSrc: a.containerSrc,
|
|
3235
|
+
scriptUrl: a.containerSrc || a.name
|
|
3236
|
+
}))
|
|
3237
|
+
});
|
|
3238
|
+
} catch (err) {
|
|
3239
|
+
console.error(\`[MOMENTIC] Failed to log long task: \${err}\`);
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
});
|
|
3243
|
+
obs.observe({ entryTypes: ["longtask"] });
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3296
3246
|
// src/html/recording-listeners.ts
|
|
3297
3247
|
function addResolveRecordingTarget() {
|
|
3298
3248
|
const customWindow = window;
|
|
@@ -3960,10 +3910,10 @@ function addTargetRedirectionScript() {
|
|
|
3960
3910
|
|
|
3961
3911
|
// src/html/registration.ts
|
|
3962
3912
|
function registerAllMomenticListeners() {
|
|
3913
|
+
addPerformanceObserver();
|
|
3963
3914
|
addMd5Hash();
|
|
3964
3915
|
addAddIdsScript();
|
|
3965
3916
|
addGetNextElementScript();
|
|
3966
|
-
addIdMaintainerScript();
|
|
3967
3917
|
addMPathScripts();
|
|
3968
3918
|
addIndexDbScripts();
|
|
3969
3919
|
addMomenticConstantsToWindow();
|
|
@@ -3986,46 +3936,45 @@ function registerAllMomenticListeners() {
|
|
|
3986
3936
|
|
|
3987
3937
|
// src/html/index.ts
|
|
3988
3938
|
registerAllMomenticListeners();
|
|
3989
|
-
`};var
|
|
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(`
|
|
3990
3940
|
`,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
|
|
3991
3941
|
`;)c++,l--;return l>n&&r[l]===`
|
|
3992
|
-
`&&(i=l),r.slice(o,i)}function qt(r){let e=typeof r=="string"?r:r.toString();return`[${Er}="${e}"]`}import{execSync as hL}from"child_process";import{randomUUID as Hd}from"crypto";import{diff as Vd}from"deep-object-diff";import{existsSync as ul,mkdirSync as fL,readFileSync as SL,writeFileSync as EL}from"fs";import{Jimp as nb}from"jimp";import yL from"js-beautify";import{cloneDeep as Ro}from"lodash-es";import TL from"mime";import{homedir as Wd,hostname as bL,platform as vL}from"os";import{basename as AL,extname as wL,join as Co,resolve as RL}from"path";import{chromium as ib,devices as CL}from"playwright";import{addExtra as xL}from"playwright-extra";import _L from"puppeteer-extra-plugin-recaptcha";import{v4 as ML}from"uuid";import{rmSync as TT}from"fs";import{basename as dO,join as mO}from"path";import{errors as pO}from"playwright-core";var Zy=new Set(["about:blank","chrome-error://chromewebdata/"]);var fd=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Sd=1e4,Hi=500;import{mkdirSync as FP,rmSync as eT,statSync as BP}from"fs";import*as bd from"node:fs";import zP from"nodejs-file-downloader";import{tmpdir as GP}from"os";import Wr,{basename as HP,dirname as VP}from"path";var vd="file://",Td=Wr.join(GP(),"momentic","downloads"),yd=1e4,jP=50*1024*1024;async function tT(r){let{uri:e}=r;if(e.startsWith(vd))return $P(r);if(e.startsWith("http"))return KP(r);if(Wg)return qP(r);throw new A("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function WP(r,e){let t=Wr.join(Td,r,e.slice(vd.length)),n=Wr.join(Td,r),o=t.startsWith(n);if(!bd.existsSync(t)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function $P({uri:r,orgId:e}){let t=WP(e,r);return{filePath:t,cleanup:()=>{eT(VP(t),{recursive:!0,force:!0})}}}async function qP({uri:r}){let e=Wr.resolve(r);if(!bd.existsSync(e))throw new A("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 KP({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=HP(n.href),i=wd(o),a=Wr.extname(i);if(Bg.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Ad(t),c=new zP({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:yd}),{downloadStatus:s,filePath:u}=await B(c.download(),{milliseconds:yd,message:`Download timed out after ${yd}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 m=BP(u).size;if(m>jP)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:i},"Downloaded file to disk");let p;return{filePath:u,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>eT(l,{recursive:!0,force:!0}),10*60*1e3)}}}function rT(r,e){return`${vd}${r}/${e}`}function Ad(r){let e=Math.random().toString(36).substring(4),t=Wr.join(Td,r,e);return FP(t,{recursive:!0}),t}function wd(r){let e=Wr.extname(r),t=Wr.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function yr(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 el=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 nT(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 oT(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 iT(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 aT(r,e,t,n,o){try{await YP(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function YP(r,e,t,n){let o=n.text();o.length>Hi&&(o=o.slice(0,Hi)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Hi?i.push(c.slice(0,Hi)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Rd(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Rd(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>Sd&&(i[t]=i[t].slice(Math.floor(Sd/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 Vt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await ud({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import XP from"truncate-json";var JP="[redacted due to size]",sT=5e3,QP=5e3;async function cT(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 Cd(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await dT(e),url:n.toString(),method:e.method(),queryString:o,postData:await eO(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:mT(t).timings}}async function uT(r,e,t){await t.finished();let n={};try{n=await oO(t)}catch{}let o={...await dT(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}=mT(a);r.time=c,r.timings=l}function Vi(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function lT(r){try{return new Date(r).toISOString()}catch{return}}function ZP(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=ar(i),e.value=ar(a);continue}i==="Domain"&&(e.domain=ar(a)),i==="Expires"&&(e.expires=lT(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=lT(Date.now()+ +a*1e3)),i==="Path"&&(e.path=ar(a)),i==="Secure"&&(e.secure=!0)}return e}async function dT(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(ZP)??[];return{headers:Object.entries(e).map(([n,o])=>({name:ar(n),value:ar(o)})),cookies:t}}async function eO(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:ar(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:ar(i),value:a?ar(a):void 0})}return n}var tO=["text"],rO=["json","xml","html","javascript"];function nO(r){let[e,t]=r.split("/");return e?tO.includes(e)?!0:t?!!rO.some(n=>t?.includes(n)):!1:!1}async function oO(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&&nO(t)&&(n.text=ar(await r.text())),n}function ar(r){try{let e=JSON.parse(r),{jsonString:t}=XP(r,QP);return t}catch{return r.length>sT?r.slice(0,sT)+JP:r}}function Rn(r){return r<0?0:r}function mT(r){return{timings:{blocked:Rn(r.domainLookupStart),dns:Rn(r.domainLookupEnd-r.domainLookupStart),connect:Rn(r.connectEnd-r.connectStart),send:Rn(r.responseStart-r.requestStart),wait:0,receive:Rn(r.responseEnd-r.responseStart),ssl:Rn(r.connectEnd-r.secureConnectionStart)},total:Rn(r.responseEnd)}}function pT(){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 He({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 xd(){return window.lastCursorPos}import{errors as iO}from"playwright-core";async function Cn({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){let s=c;if(gi(s)){t.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[u]=await Promise.all([r(i),n.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return u}else if(s instanceof iO.TimeoutError)t.warn({err:s,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await aO(s,i.locator,n,t);else throw s}throw l instanceof A?l:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function aO(r,e,t,n){return r.message.includes("attempt #")?sO(r,e,t,n):lO(r)}async function sO(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(`
|
|
3993
|
-
`,";").replace(/\s+/g," ");let a="",l=await
|
|
3994
|
-
${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 A("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 A("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 lO(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 A("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 gT(r){try{return await cO(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function cO({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await yr(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(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[Zs],h=c.getAttribute(Er),f=!g&&h?qt(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,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 fT=["date","datetime-local","month","time","week"],hT={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 ST(r){try{await B(uO(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function uO({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await He({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!hT[i])return;hT[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 Rt}from"zod";var ET=Rt.object({doubleClick:Rt.boolean().optional(),rightClick:Rt.boolean().optional(),force:Rt.boolean().optional(),waitForDownload:Rt.boolean().optional(),delayMs:Rt.number().optional(),downloadTimeoutMs:Rt.number().optional(),relativePosition:Rt.object({x:Rt.number(),y:Rt.number()}).optional()}),une=Rt.object({repeat:Rt.number().optional(),convertMeta:Rt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Rt.number().optional()});async function tl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await _d(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let p=window.getComputedStyle(d,null).getPropertyValue("display");if(p==="none"||p==="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 _d(r,e=1e3){let t=await r.state.getRoot();await He({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 Md(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Cn({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>bT({...r,targetingResult:t,useVisualClick:e})})}async function gO(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await hO(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 hO(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"),bT({...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 fO(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 An({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new A("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:m}=await yO({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),p=ET.safeParse(i);t.info({frameCoordinates:c,position:o,options:p.success?p.data:void 0,clickLocation:{clickX:u,clickY:d,reason:m},duration:Date.now()-s},"Visual click")}async function SO(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 gT({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(bO(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..."),gO(s,{...r,targetingResult:{...i,locator:i}})}}async function bT(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 pO.TimeoutError?new A("ActionFailureError",`Download did not complete in ${c}ms`):new A("ActionFailureError",`Download failed: ${s.message}`)}})());try{await tl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await fO(r):await SO(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new A("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 TO(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function EO(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 A("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 yO({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,m]=await EO(r,n);i=d.x,a=d.y,l=m}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 TO(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=wd(r.suggestedFilename()),i=e();await r.saveAs(mO(i,o)),TT(n,{force:!0}),setTimeout(()=>{TT(i,{recursive:!0,force:!0})},5*60*1e3);let a=rT(dO(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function bO(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as vO}from"os";var AO={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 wO(){let r=vO();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function vT(r){return JSON.stringify(r.split("+").sort())}function rl(r){let e=wO(),t=vT(r);for(let n of Object.values(AO))if(Object.values(n).some(o=>vT(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function Id({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 He({root:r,fn:([d,m,p,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Ir,m=await He({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[p,g,h]=await He({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.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 y=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[T,v,R]=await B(e.evaluate(()=>{let b=document.activeElement;if(!b)return[void 0,void 0,void 0];let x=b.getBoundingClientRect();return[b.scrollTop,x.x,x.y]}),{milliseconds:1e3});if(y===m&&T===p&&v===g&&R===h)break;m=y,p=T,g=v,h=R,await q(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Pd(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 q(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as LO}from"crypto";import{cloneDeep as Ld}from"lodash-es";function $r(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as RO}from"crypto";var CO="v1";function nl(r,e){if(r.tagName.toLowerCase()==="svg"&&!_O(r))try{let t=AT(r,e),n=xO(JSON.stringify(t));return{version:CO,json:t,hash:n}}catch{return}}function xO(r){return RO("md5").update(r).digest("hex")}function AT(r,e){let t=r.tagName.toLowerCase(),n=MO(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=AT(a,e);l&&o.children.push(l)}}return o}function _O(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function MO(r){let e={},t=r.attributes;for(let n of Object.keys(t))Ht.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var xn={r:147,g:196,b:125,a:.55},RT={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:xn,paddingColor:xn,borderColor:xn,marginColor:xn,eventTargetColor:xn,shapeColor:xn,shapeMarginColor:xn,showInfo:!0,showAccessibilityInfo:!0};function CT({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=IO({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function IO({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,D)=>{u[N]=D});let d=s.styles,m=s.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],y=p.parentIndex??[],T=p.nodeName??[],v=p.nodeType??[],R=p.pseudoType??{index:[],value:[]},b=p.inputChecked??{index:[]},x=e[c.frameId];for(let N=0;N<h.length;N++){let D=h[N],$=v[N],De=f[N]??[],ee=y[N]!==void 0&&y[N]>=0?y[N]:void 0,oe=ee!==void 0?h[ee]:void 0,lt=oe!==void 0?a[oe]:void 0,_=R.index.indexOf(N),V=_!==-1?e[R.value[_]]:void 0,te=u[N],Re;te?Re=m[te]??[]:Re=[];let _e=T[N]!==void 0?e[T[N]]?.toLowerCase():void 0;if(!_e){l.warn({backendNodeId:D,frameId:x,frameIndex:o,nodeBounds:Re},"DOM node has no tag name");continue}let ve={backendNodeId:D,psuedoType:V,nodeType:$,frameIndex:o,parentFrameId:x,ownedFrameId:void 0,bounds:{x:Re[0]??null,y:Re[1]??null,width:Re[2]??null,height:Re[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:oe??null,tagName:_e,parent:lt??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};lt&<.childrenBackendIds.push(D);let Ct=g.index.indexOf(N);if(Ct!==-1){let Ae=g.value[Ct];i[Ae]=ve;let Ve=r[Ae]?.frameId;ve.ownedFrameId=Ve!==void 0?e[Ve]:void 0}for(let Ae of Object.keys(ve.bounds)){let Ve=Ae;ve.bounds[Ve]!==null&&(ve.bounds[Ve]/=n)}let ct=te!==void 0?d[te]??[]:[];for(let Ae=0;Ae<ct.length&&!(Ae>=t.length);Ae++){let Ve=ct[Ae];if(Ve===void 0||isNaN(Ve))continue;let Xr=e[Ve];if(Xr===void 0)continue;let dr=t[Ae];ve.computedStyles[dr]=Xr}for(let Ae=0;Ae<De.length;Ae+=2){let Ve=De[Ae],Xr=De[Ae+1];if(!Ve||!Xr)continue;let dr=e[Ve],Bo=e[Xr];!dr||!Bo||(ve.attributes[dr]=Bo)}b.index.includes(N)&&(ve.attributes.checked="true"),a[ve.backendNodeId]=ve}return a[h[0]]}function Od(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=`${Od(t,e)}${a}`}return r.mPathSelector=n,n}function wT(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var PO=["html","#document","#document-fragment"];function xT({node:r,domGraph:e}){let t=[],n=r,o=wT(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=wT(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++,PO.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],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else m?.nodeType===1&&!m.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 _T(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 MT(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=$r(o,Er);if(!i)throw new Error(`Could not find attribute ${Er} for object ${e}`);return i}function IT(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=OO({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function OO(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=nl(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 NO=["focusable","keyshortcuts","controls","live","relevant","orientation"],DO=["selected","readonly","modal","required","invalid"],kO=["id","name","role","content"],PT=["absolute","fixed","sticky"],UO=["i"],FO=["path"],BO=["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"],NT=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],DT=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],zO=["menulistpopup","statictext","inlinetextbox"],GO=80,OT=100,kT=50,kd=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],HO=["cite"],VO={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"]},jO={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},LT={indentLevel:0},Nd=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<kT?t:""),this.role=this.role||(e.domNode.attributes.role??""),KO(this.properties,e.domNode,e.importantProperties)}XO(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&&FO.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>DT.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>GT(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>HT(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&&UO.includes(this.domNode.tagName)||BO.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Ht.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>zT(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=LT){let t=Object.assign({},LT,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Ld(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",p=this.name;d==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(b=>!b.superseded&&b.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(b=>!b.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let b=h.attributeValue?.relatedNodes??[];b.length===1&&b[0].text&&b[0].text===p&&(p="")}let f=kd.includes(this.role)||HO.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${p}
|
|
3995
|
-
`;let
|
|
3996
|
-
`;else{let
|
|
3997
|
-
`)?
|
|
3998
|
-
`:
|
|
3999
|
-
${
|
|
4000
|
-
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let
|
|
4001
|
-
${
|
|
4002
|
-
${N||""}`}return y}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:Ld(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Ld(this.properties),e}},Dd=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 m=a(d);m&&(u.push(m),m.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 m of s){let p=n(m,l||u);p&&(d.push(p),p.parent=c,u=!0)}if(c.children=d,l||u)return c;if(kd.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 WO(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 $O(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?(qa({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?(qa({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 UT({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:m,cdpClient:p,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(_,V={})=>{},y=r.backendDOMNodeId,T=zO.includes(r.role?.value?.toLowerCase()??"");if(!T&&y===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let v=y?i.backendIdToNode[y]:void 0;if(!T&&!v)try{let _=await B(p.send({method:"DOM.describeNode",params:{backendNodeId:y}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(_&&_.node.nodeName.toLowerCase()==="slot"&&_.node.distributedNodes?.length)g.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:_},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:_}),[]}catch(_){return f("Filtering out node since it doesn't exist in the DOM",{err:_}),[]}if(v&&e&&s&&u&&r.backendDOMNodeId&&!$O(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 R=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",b=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",x=new Nd({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:R,nameSources:r.name?.sources,content:b,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(_=>NT.includes(_.name)||DT.includes(_.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+WO(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),N=n,D=a[t],$=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let _=n.childFrames.find(Re=>Re.frameId===v.ownedFrameId),V=o[_?.frameId??""]?.root,te=a[_?.frameId??""];if(_&&V&&te){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let Re=V;r.childIds=Re.childIds,N=_,D=te,$=_.frameId}}let De=v?.childrenBackendIds?.length??0,ee=(r.childIds??[]).filter(_=>!!D.get(parseInt(_))).length;if(De>ee){let _=r.childIds?.map(te=>D.get(parseInt(te))).filter(Boolean).map(te=>te?.backendDOMNodeId).filter(te=>te!==void 0)??[],V=0;for(let te of v?.childrenBackendIds??[]){if(_.includes(te)){V=(r.childIds?.findIndex(ct=>D.get(parseInt(ct))?.backendDOMNodeId===te)??0)+1;continue}let Re=i.backendIdToNode[te];if(!Re||Re?.tagName.toLowerCase()!=="svg")continue;let _e=Math.floor(-1*Math.random()*1e7),ve={nodeId:_e.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:te,frameId:$,role:{type:"string",value:"graphics-symbol"}};D.set(_e,ve),r.childIds||(r.childIds=[]),r.childIds.splice(V,0,_e.toString()),V++}}if(r.childIds?.length===1&&v){let _=D.get(parseInt(r.childIds[0])),V=_?.role?.value,te=v.childrenBackendIds;if(_&&V==="StaticText"&&te.length===1){let Re=i.backendIdToNode[te[0]];if(Re?.tagName?.toLowerCase()==="span"){let _e=Math.floor(-1*Math.random()*1e7).toString(),ve={nodeId:_e,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Re.backendNodeId,frameId:$,childIds:[_.nodeId]};_.parentId=_e,D.set(parseInt(_e),ve),r.childIds=[_e]}}}for(let _ of r.childIds??[]){if(!_)continue;let V=D.get(parseInt(_));if(!V)continue;let te=await UT({node:V,parent:x,domGraph:i,axGraph:o,frameId:$,frameContext:N,inputNodeMap:a,cdpClient:p,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:m,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});te.length&&(x.children=x.children.concat(te))}if(x.role==="StaticText"&&(x.children=[]),x.children.length===1&&x.children[0].role==="StaticText"){let _=x.name,V=x.children[0]?.name;(_===V||!V)&&(x.children=[])}let oe=[];for(let _=x.children.length-1;_>=0;_--){let V=x.children[_];if(V.role!=="StaticText"){oe.push(V);continue}if(_===0||x.children[_-1].role!=="StaticText"){oe.push(V);continue}x.children[_-1].name+=V.name}if(x.children=oe.reverse(),!x.isInteresting(m)&&r.parentId)return v&&(v.momenticIgnored=!0),x.children;for(let _ of x.children)_.parent=x;return YO(x),v&&d&&Od(v,i),[x]}function FT({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:kd.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 m=nl(d,i),p=m?c[m.hash]:void 0,g=p?p.description:void 0;p&&(r.properties["data-momentic-description"]=g)}for(let m of r.children)s=FT({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function BT({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:m}){let p=t??"root",g=r[p]?.root;if(!g)throw new Error("A11y tree has no root");let h=LO(),f=x=>{let N=x.allNodes.filter($=>!$.ignoredReasons?.find(ee=>NT.includes(ee.name))),D=new Map;return N.forEach($=>{D.set(parseInt($.nodeId),$)}),D},y={};Object.entries(r).forEach(([x,N])=>{y[x]=f(N)});let T=await UT({node:g,domGraph:e,parent:null,inputNodeMap:y,axGraph:r,frameId:p,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(T.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(T)}`);if(T.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},R={},b={};return FT({node:T[0],a11yIdNodeMap:v,dataMomenticIdMap:R,selectorToNodeMap:b,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:m}),new Dd(T[0],v,R,b)}function qO(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<kT&&!Ht.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(zT(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 KO(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||kO.includes(a);if((Ht.relevantElementAttributes.includes(a)||GT(a,t))&&!c){let u=qO(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&PT.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of PT)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],m=`${c}: ${d}`;o.includes(m)||o.push(m)}}o.length>0&&(r.style=o.join("; "))}function YO(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(ft(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 p=u.children.filter(g=>g.tagName==="th");if(p.length){if(i=p.map(g=>ft(g.name,100,!1)),i.length===p.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=d.length===i?.length;d.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=i[g])))})}}}function XO(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function zT(r,e){if(e&&HT(r,e))return!0;if(Ht.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Ht.alwaysInterestingClassNames.includes(r))return!0;for(let t of Ht.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function GT(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 HT(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 ol=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 A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await q(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 A("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 A("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 A("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 Ao="<empty>";function JO(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 jT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||JO(r.url)}async function QO(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 wo({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,m)=>{if(jT(d.frame))return null;try{return await WT({cdpClient:r,rawFrameTree:d,indices:[m],parent:n,warnings:o,logger:t})}catch(p){return o.push(`Failed to get child frame: ${p}`),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 WT({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await QO(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=$r(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},p=(e.childFrames??[]).map(async(g,h)=>{if(jT(g.frame))return null;try{return await WT({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(p)).filter(g=>g!==null),d}async function ZO(r){try{return await r.owner().count()===1}catch{return!1}}async function eL(r){try{return await r.count()===1}catch{return!1}}async function sr(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,Ao]){let m=o.frameLocator(d===Ao?"iframe":`iframe[${d}]`);if(await ZO(m)){u=!0,o=m,i.push(d);break}}if(!u)throw new A("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,Ao]){let u=o.locator(s===Ao?"iframe":`iframe[${s}]`);if(await eL(u)){a=u,i.push(s);break}}if(!a)throw new A("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 A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function VT(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 $T({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===Ao?l=l.length===1?l[0].childFrames:[]:l=l.filter(m=>m.locationData.attributeSelectors.includes(d)).map(m=>m.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===Ao?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 sr(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=VT(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 sr(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=VT(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 sr(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 sr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Nr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function il(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Ud(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function qT(r){let e=Ud(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 KT(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 YT({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await tL({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 tL({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await An({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 XT(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 nL}from"crypto";function JT(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function QT(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(p=>[p.name,p.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let p=await e.fetch();s={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let u=await rL(t,c,s),d={};u.headers.forEach((p,g)=>{d[g]=p});let m={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(m);try{n.response={status:m.status,statusText:u.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},Vi(o,n,i);for(let p of Object.values(a))p.onRequestComplete(i,n)}catch(p){p.message.includes("has been closed")||l.warn({err:p},"Failed to add response to HAR")}}async function rL(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 Fd(r){try{await oL(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function oL(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=nL(),s=await Cd(e,n);try{Vi(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=JT(n,l);u?await QT({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await iL({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function iL({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 uT(i,e,l),Vi(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 aL(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 sL(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 al(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 Bd(r){let e=r.request(),t=r.status(),n=r.headers(),o=await sL(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await aL(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var qr=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:Ks(t,this.requestMatcher.urlMatcher)}};function sl(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(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let m,p;if(s)try{let g=await n.frameElement();m=await B(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)p={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"),p={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as lr}from"crypto";import lL from"js-beautify";var cL=["Dead"],ll=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:lr(),type:"PRESET_ACTION",command:mr(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=mr(i);a={id:lr(),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=mr(i);a={id:lr(),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=mr(i);a={id:lr(),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:de(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=lL.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Qy(d,"data-momentic-interacted",4e4)}catch{}let m;try{m=(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,...de(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=l}let p=this.recordedSteps.get(u)?.step??a,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,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(cL.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=mr("TYPE");i={id:lr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=mr("PRESS");i={id:lr(),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,m=i.command.value;i={id:lr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${m}`:`${d}${m}`}},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:lr(),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=mr(s);u.deltaY=Math.abs(i);let d={id:lr(),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=mr(s);u.deltaX=Math.abs(i);let d={id:lr(),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 zd}from"zod";var _ie=zd.object({type:zd.literal("url"),url:zd.string()});var cl=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 m=d.split(":");if(m.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let p=m[0]?.trim(),g=m[1]?.trim();if(p===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(p)||this.computedStylesToFetch.push(p)}}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=Ud(e),{frame:o,mPathSelectorTokens:i}=await sr(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 wo({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await $T({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(il(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:il(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await YT({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await wo({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(sr(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 wo({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 Vt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new A("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Vt({fn:()=>wo({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 Vt({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 Vt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Vt({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 Vt({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(m=>m>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:dn,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=xT({node:o,domGraph:this.domGraph});return _T(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 MT(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 wo({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 A&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await q(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:il(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=$r(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 sr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await sr(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 A("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 BT({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 sr(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 He({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($r(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=$r(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(p){i.warn({err:p},"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 p=0;p<3;p++)try{s=await Vt({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),m=[];for(;d.length>0;){let p=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,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 ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}d.push(...p.childFrames);let g=async()=>{try{let h=await Vt({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,signal:a,logger:i});u[p.frameId]=h}catch(h){i.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}return await Promise.all(m),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 Vt({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 Vt({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 Vt({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 q(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new A("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 CT({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=qT(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 Gd(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var jd=Co(Wd(),"momentic","chromium"),IL=Co(Wd(),"video"),dl=process.env.TWO_CAPTCHA_KEY,ab=xL(ib);ab.use(_L({provider:{id:"2captcha",token:dl},visualFeedback:!0}));var Wi=class r{static USER_AGENT=CL["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:m,iconKnowledgeBase:p}){if(zh(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=m,d.recordVideo){let g=this.page.video();g&&this.videos.push(g)}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={[Zs]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Yy.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"&&vL()==="darwin"&&hL("system_profiler SPDisplaysDataType").toString().includes("Retina")?(w.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 ol.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new cl({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}){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 m={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},p={...l??{},geolocation:l?.geolocation||Np,locale:l?.locale||Op,timezoneId:l?.timezoneId||Lp,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??Ir},g=["--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"],h=null,f,y,T={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(T.isNewHeadless=!0,m.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&g.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(b=>b.startsWith("~")?Co(Wd(),b.slice(1)):b);if(v?.length){if(d===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let D of v){let $=Co(D,"manifest.json");if(!ul($))throw new A("UserConfigurationError",`Chrome extension path ${$} does not exist.`)}if(hi)throw new A("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=Co(jd,`momentic-session-${Date.now()}`);if(!ul(b))try{fL(b,{recursive:!0})}catch(D){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${jd} folder: ${D}`)}let x=[...g],N=v.map(D=>RL(D)).join(",");x.push(`--disable-extensions-except=${N}`),p?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&x.push(`--window-size=${p.viewport.width},${p.viewport.height}`),f=await ib.launchPersistentContext(Co(jd,`momentic-session-${Date.now()}`),{...m,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:e}),t.debug({sharedContextOptions:p,sharedBrowserOptions:m,userBrowserSettings:a,chromeArgs:x,flags:o.getAllFlags(),properties:T,baseUrl:e},"Browser initialization context args (persistent)"),y=f.pages()[0]}else{h=await ab.launch({...m,args:g});let b={...p,baseURL:e,recordVideo:c?{dir:IL}:void 0};f=await h.newContext(b),t.debug({contextArgs:b,sharedBrowserOptions:m,chromeArgs:g,userBrowserSettings:a,flags:o.getAllFlags(),properties:T,baseUrl:e},"Browser initialization context args (standard)"),y=await f.newPage()}hi&&await f.route("**",sl);let R=new r({browser:h,context:f,page:y,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:p.viewport||Ir,properties:T,clientCallbacks:u,iconKnowledgeBase:s});return await R.initialize({grantPermissions:!0,runInitScripts:!1}),R}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 Pd(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=Hd(),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()||!wn(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=Hd(),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=>{aT(e,o,this.debugData,a,this.logger)});let i=async()=>{await cT(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await Fd({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",XT(this.customHeaders,this.logger)),hi&&await e.route("**/*",sl),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=IT({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=de(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:bL()};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"||!wn(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},"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(_d(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 He({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 q(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),He({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 q(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 nb.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&&EL(n,c),this.lastScreenshotForRecording=c,!e)return c;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let y=await nb.fromBuffer(c),T=y.bitmap.width,v=y.bitmap.height;p=Math.max(0,Math.min(p,T-1)),g=Math.max(0,Math.min(g,v-1)),h=Math.max(1,Math.min(h,T-p)),f=Math.max(1,Math.min(f,v-g)),c=await y.crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${h}, ${f}): ${y}`)}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}){zy(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 q(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 A("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(Zy.has(l))throw new A("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 He({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 ST({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 q(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??op}),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 tl({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 iT(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 oT(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 nT(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 A("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Pd(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 Zt)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(!fd.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 A("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||Ht.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 A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new A("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,m,p;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let T=c.parentFrame,{cache:v,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(T);d=v,m=R,u=R.frame,p="auto iframe"}else c.parentFrame&&s?(m=s,u=await this.getActivePageOrFrame(),p="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),p="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:de(i),frameCache:d},f,y=!1;o||(m&&(i.info({frameConfigSource:p,frameConfig:KT(m)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(m),y=!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:m,frameConfigSource:p}}finally{y&&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 p,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){p=f,await q(500,a)}if(!g)throw p}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,m;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let p=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:p?i:dn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof pi)break;if(g instanceof Zt){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 q(500,a)}a?.throwIfAborted(),p&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await q(500,a)}}return m||(m=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=de(i),i.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=Ro(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(m){u=m,m instanceof Nr&&c.push(...m.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:Ro(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 Nr(`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 pi("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 He({fn:T=>window.evaluatePrimaryCaches(T),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 T={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(T),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let T=`${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:T,selectors:v}),n.debug({reason:T,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 Nr("Cache evaluation failed",d);let m,p,g,h=!1;if(this.userBrowserSettings.visualActions){let T=s.mPath;if(!T)throw new Error("Found element did not have an mPath despite using visual actions");let v=T.join(" > ");m=e.locator(v),p=this.stateManager.getNodeUsingMPathSelector(v)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),p=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(m=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):m=e.locator(qt(g));else throw new A("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=Ro(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let y=Vd(f,t);return y&&Object.keys(y).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=de(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:y},"Updated cache")),{a11yNode:p,displayString:s.serializedElement,locator:m,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 m=l.locator(n),p;try{return await m.waitFor({state:"attached",timeout:1e3}),p=await yr(m,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:m,displayString:p,decisions:d}}catch(g){let h=g.message;u=new A("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 q(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 He({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,m,p;if(d)m=this.stateManager.dataMomenticIdToNodeMap[d],p=e.locator(qt(d));else if(s.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),p=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 yr(p,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=Ro(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=Vd(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=de(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:p,a11yNode:m,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&&fd.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=ML(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:m,locator:p}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=m.boundingBox?.width,h=m.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=m.id,y=this.stateManager.a11yIdToNodeMap[f],T=Ro(n);await this.updateCacheWithNewNodeDetails({target:n,node:y,locator:p,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let v=Vd(T,n);return v&&Object.keys(v).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=de(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:v,templateMatch:d},"Updated cache after template matching resolution")),{locator:p,a11yNode:y,displayString:m.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=fT.some(a=>a===o.toLowerCase());return await Md({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 Md({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(),Ks(l,t,n)){a=!0;break}await q(500,this.abortSignal)}if(!a)throw new A("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${my(t)} in ${o}ms.
|
|
4003
|
-
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 A("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 q(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(xd);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 q(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Cn({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 Cn({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 He({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 Cn({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 Cn({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 A("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=rl(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=rl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Gd(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=rl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Gd(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 A("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await He({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=m=>{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 q(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 q(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(xd);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 q(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 T=0;T<l.length;T++)if(c[T]===e){d=s.indexOf(T);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,p=0,g=0,h=0]=u[d];m/=n,p/=n,g/=n,h/=n;let f=m+g/2,y=p+h/2;return{centerX:f,centerY:y}}async scrollVertical(e){return Id({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 Id({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 createRawCDPSession(e){let t=await B(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),t}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 q(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 A("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)}.
|
|
4004
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!wn(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=Na(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 q(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];wn(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 An({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 A("UserInfrastructureError",`The page with URL ${ft(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await An({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 yL.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 He({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 A("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 He({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Lr}){let i=pT(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("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 A("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),m=u+s,p=d+c;return this.getDomNodeFromPixelPosition(m,p)}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:RT,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[Er],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 yr(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:m,mPathSelector:p,error:g,serializedElement:h,point:f,force:y,logs:T}=await e.evaluate(R=>{let b=window;if(!b.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return b.performTargetRedirection(R)},void 0,{timeout:1e3}),v=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:v,force:y,logs:T},"Got error from target redirection with bounding box");return}else{if(m)return t.info({newDataMomenticId:m,serializedElement:h,duration:v,force:y,logs:T},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(qt(m)),hints:{clickableXY:f,force:y}};if(p)return t.info({newMPathSelector:p,serializedElement:h,duration:v,force:y,logs:T},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(p),hints:{clickableXY:f,force:y}};if(f)return t.info({point:f,serializedElement:h,duration:v,force:y,logs:T},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return t.info({serializedElement:h,duration:v,force:y,logs:T},"Forcing click on original element"),{locator:e,hints:{force:y}}}}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(Xy)?new Ba(l.error):l.error.startsWith(Jy)?new za(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,Rd(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!ul(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()||AL(e),o=SL(e),i=wL(e),a=Hc[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!ul(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:TL.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 m=atob(s),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);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??Hd();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return Ro(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}};import rN from"fetch-cookie";import{cloneDeep as Mb}from"lodash-es";import{CookieJar as nN}from"tough-cookie";async function Kr(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}async function cr({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 PL=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function sb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(PL.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 q(250),s++;let u=(await t.getOpenPages()).map(m=>m.url),d=t.url();if(u.length!==e.length)for(let m=u.length-1;m>=e.length;m--){let p=u[m];if(wn(p,o)&&p!==r&&p!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(m)});break}}}}var _n=3.1783027;function OL(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 Tr(r){return Math.ceil($d(r)/_n)}function $d(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
4005
|
-
`,""),t=t.replaceAll(" ","");let n=
|
|
4006
|
-
`),s=0,u=[],d=0,
|
|
4007
|
-
`),tokenLength:d}),u=[],d=0,
|
|
4008
|
-
`),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var
|
|
4009
|
-
${r}`;case"ELEMENT_CHECK":return`${
|
|
4010
|
-
${r}`;default:return r}}var $L=15;async function gl({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=$L}){if(!r.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=qs(c),u=0,d=Date.now(),m,p,g;try{await cr({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 q(s,n.abortSignal),h=Date.now();try{if(m=await cr({action:async()=>{let y=await Sb(l,t,n.abortSignal);return p&&p.serializedTree===y.serializedTree&&p.screenshotBuff.equals(y.screenshotBuff)?m:(p=y,Eb({command:r,state:y,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}),m?.updatedMemory&&js(r,m.updatedMemory,t),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("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(!m?.success)try{m=await cr({action:async()=>Eb({command:r,state:await Sb(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(!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:l.url()}}async function Sb(r,e,t){let[n,o]=await Promise.all([Kr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Eb({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:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,y=f.toString("base64"),T=u.url(),v=r.contextChoice??"MULTIMODAL",R=g;v!=="VISION_ONLY"&&(R=await Mn({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:s,orgId:t.orgId}}),R!==g&&(p.ragUsed=!0),p.pageState=R);let b={goal:r.assertion,url:T,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:y,contextChoice:v,source:c},N=await(v==="VISION_ONLY"?(D,$)=>d.getVisualAssertionResult(D,$):(D,$)=>d.getAssertionResult(D,$))(b,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:s,loggerTags:de(s)});return(N.result||i)&&N.relevantElements&&(p.relevantElementsSerialized=N.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await qL(N.relevantElements,u,s)),{success:N.result,thoughts:N.thoughts,afterScreenshotOverride:f,updatedMemory:o?N.updatedMemory:void 0}}async function qL(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 KL}from"lodash-es";async function Tb(r){let{command:e,timeoutMs:t,fixtures:n}=r,{logger:o,abortSignal:i}=n,a=rp(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 q(u,i),i?.throwIfAborted();let{result:m,updatedCache:p,elementWasFound:g}=await yb({cacheToUse:a,params:r});if(s=m,d=g,m.success){p?.target&&Tn({cmd:e,key:"target",newTarget:p?.target,logger:o});break}p?.target?.memory&&a?.target&&(a.target.memory=p.target.memory),u=Math.min(u*2,1e4)}if(!s)throw new A("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(i?.throwIfAborted(),!s.success&&a?.target&&da(a.target)){let m=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:p,updatedCache:g}=await yb({cacheToUse:m,params:r});s=p,p.success&&g?.target&&Tn({cmd:e,key:"target",newTarget:g.target,logger:o})}return s.success&&a?.target&&!d&&Ym(a.target),s}async function yb({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Rr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=XL(t.assertion),s,u=!1,d=KL(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>YL(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ti(t),targetName:"target"}});return s={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(l.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),s={...p,thoughts:g}),{result:s,elementWasFound:u,updatedCache:d}}catch(m){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u,updatedCache:d};if(!(m instanceof A)||m.reason!="ActionFailureError")throw m;return s={success:!1,err:m,data:void 0,thoughts:void 0},l.warn({err:m},"Element check did not find an element and failed"),{result:s,elementWasFound:u,updatedCache:d}}}async function YL(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:ft(c,500,!0)},!hl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,i=new A("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:ft(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 A("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!hl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,n.operation==="EXISTS"?i=new A("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new A("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(p=>setTimeout(p,250));let m=s.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},xr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:xr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:xr*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?uy[n.condition]:dy[n.condition];i=new A("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!hl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,i=new A("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(!hl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,n.operation==="EXISTS"?i=new A("AssertionFailureError",`The style property ${n.property} ${s}`):i=new A("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 hl(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 XL(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function bb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as JL}from"jimp";async function $i(r,e){let t=await r.screenshot(e),n=await JL.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as vb}from"jimp";import Yd from"jpeg-js";import QL from"pixelmatch";async function Ab({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Rr(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 ee=>$i(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await $i(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 De=`${s.width}x${s.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${De}) does not match saved screenshot dimensions (${ee}) - 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 vb.fromBuffer(s.buffer),m={width:s.width,height:s.height},p=await vb.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,y=g.width*g.height,T=Math.abs(m.height-g.height),v=Math.abs(m.width-g.width);if(f>y){let De=d.cover({w:g.width,h:g.height});s.buffer=await De.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(y>f){let De=p.cover({w:m.width,h:m.height});u.buffer=await De.getBuffer("image/jpeg"),h="saved"}let R={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},b=t.threshold??.1,N=QL(Yd.decode(u.buffer).data,Yd.decode(s.buffer).data,R.data,s.width,s.height,{threshold:b,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,D=N>b*100,$=`Visual diff of ${N.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${b*100}%.`;if(h&&($+=` The ${h} screenshot was cropped since it was taller by ${T} pixels and wider by ${v} pixels.`),D)throw new A("ActionFailureError",$);return{fail:D,thoughts:$,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Yd.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var ZL=3e4;async function wb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??ZL/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let l=a.toString(),c;if(bo(r.url)&&(c=r.url),t&&vo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new A("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 p=l?`${c}?${l}`:c;try{return await n(p,{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 A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let p;try{p=await u.text()}catch(g){p=`Failed to read response body: ${g}`}throw new A("ActionFailureError",`Fetch request failed with status ${u.status}: ${p}`)}let d={};u.headers.forEach((p,g)=>{d[g]=p});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var eN=5e3;async function xb({timeout:r=xr,...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 Rb(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 q(l,e.signal),l=Math.min(Math.floor(l*1.5),eN);else return i}return i=await Rb(e),i}async function Rb({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(Cb,{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(Cb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?bn.CONTAINS:vn.CONTAINS;a=new A("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new A("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 Cb({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 tN=3e4;async function _b({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??tN/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let l;if(bo(r.url)&&(l=r.url),t&&vo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new A("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 A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,m=await s.text();try{d=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${m}`)}let u={};return s.headers.forEach((d,m)=>{u[m]=d}),{status:s.status,headers:u,json:await s.json()}}var fl=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([Kr(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 Mn({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}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...de(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([Kr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Mn({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}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...de(a)},langfuseSessionId:l})}catch(g){throw new A("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Kr(this.browser,e)}async locateElement(e){return await Kd({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return cr({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 m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await l(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}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 A("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 cr({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&&Fc(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&gi(i)){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Bc(i)&&t.warn({err:i},"Invalid backend node id error, retrying element targeting command"),i instanceof Zt&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof A?n:new A("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 A("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 q(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:m,source:p}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,y=!1,T=Mb(e.cache);if((!T||s)&&!Kl(o))throw new A("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"),y=!0,T=void 0),T&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&T.targetSource==="HEURISTIC_HEALED"&&(y=!0,T=void 0),T?.inputDescription&&!fb(o.elementDescriptor,T.inputDescription)&&(g.warn({old:T.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,T=void 0);let v=b=>!!b&&da(b),R=!0;if(!v(T)){R=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:y,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),y&&await q(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let b;try{b=await Kd({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:p,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof ro&&D.updatedLocatorMemory){let $={id:-1,...i,memory:D.updatedLocatorMemory};Tn({cmd:c,key:d,newTarget:$,logger:g})}throw new A("ActionFailureError",D.message)}b.frameConfig&&this.browser.setActiveFrameConfig(b.frameConfig);let x=l.disableGlobalLocatorRedirect?{locator:b.resolution.locator}:await this.attemptLocatorRedirect(b.resolution.locator,g),N=await a(x);return Tn({cmd:c,key:d,newTarget:b.target,logger:g}),m&&(n.heal({healType:"AI"}),b.target.targetSource="AI_HEALED",b.target.targetUpdateTime=new Date().toUTCString(),b.target.targetUpdateLoggerTags=de(g)),{result:N,elementInteractedDisplayString:b.resolution.displayString,thoughts:b.thoughts}}try{let b=await this.browser.resolveTarget(t,T,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(b.locator);let x=l.disableGlobalLocatorRedirect?{locator:b.locator}:await this.attemptLocatorRedirect(b.locator,g),N=await a(x);if(nt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!T.requirements}`,`hasAdditionalElements:${!!T.additionalElements}`]),Tn({cmd:c,key:d,newTarget:T,logger:g}),R){let D=b.decisions.filter($=>$.matched);if(D.length!==1)g.warn({decisions:b.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let $=D[0].type;n.heal({healType:$})}}return{result:N,elementInteractedDisplayString:b.displayString}}catch(b){this.throwIfClosed(),nt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!T.requirements}`,`hasAdditionalElements:${!!T.additionalElements}`]);let x=!1;if((b instanceof Zt||Fc(b)||gi(b)||Bc(b)||kg(b)||Ug(b))&&(x=!0),b instanceof A&&!x)throw g.error({err:b},"Failed to execute action with cached target (fatal)"),b;if(f>0&&o){g.info({err:b},"Failed to execute action with cached target, retrying with AI");let N;return T.memory&&Xm(T.memory)&&(N=T.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 A("ActionFailureError",b.message,{errOptions:{cause:b}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return $i(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(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 A("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&&ap(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 sb({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{Qa(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Ad(e)}}async resolveCommandTemplateStrings(e,t){return Ja({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()?gl({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 A("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return gl({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Bh(n.schema);if(f)throw new A("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:de(a)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let y=f.message;throw y.includes("MaxGenerationLengthExceededError")?new A("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."):y.includes("AIProviderError")&&y.includes("time")?new A("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(!bo(n.url)&&!vo(n.url,this.browser.baseUrl))throw new A("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&&Jt(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=T,h=v}let f=this.browser.getViewport()?.height??Ir.height,y=this.browser.getViewport()?.width??Ir.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??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new A("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 A("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await q(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Jt(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:y}=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}}),T={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:y,data:f};return Ys(g,T.urlAfterCommand)&&(T.succeedImmediately=!0,T.succeedImmediatelyReason="URL changed"),T}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(Jt(n.fromTarget)&&Jt(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Jt(n.fromTarget)||Jt(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,y)=>this.browser.dragAndDrop(f.locator,y.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 A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Jt(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let y,T,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,result:b,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}});y=b,T=R,v=x}return await this.browser.mouseDrag(g,h,f,y,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:T,thoughts:v}}case"SELECT_OPTION":{if(!Rr(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:T=>this.browser.selectOption(T,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ti(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}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 Fr({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 A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new A("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&&Jt(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,y=Mb(n.target);if(y){let{elementInteractedDisplayString:v,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:y,cache:n.cache?.target,action:b=>this.browser.typeIntoTarget(n.value,b,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:ti(n)}});h=v,f=R}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let T={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Ys(g,T.urlAfterCommand)&&(T.succeedImmediately=!0,T.succeedImmediatelyReason="URL changed"),T}case"HOVER":{if(Jt(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(!Rr(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&&!Rr(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 m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Ys(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new nN,h=rN(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await wb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:mg(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await _b({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Ab({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 tT({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 A("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 Fr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=dg.optional().parse(g)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??xr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(bb(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let y={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 T=await gl({command:y,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: ${T.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:T.afterScreenshotOverride}}finally{y.cache?.memory&&js(n,y.cache?.memory.traces,a)}}let f=await Tb({command:n,tracer:t,timeoutMs:g,targetingWrapper:y=>this.wrapElementTargetingCommand(y),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 cr({action:async()=>xb({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 qr(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Bd(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 A("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 qr(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=al(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=al(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new A("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 qr(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 qr(n.requestMatcher),async(h,f)=>{let y=await Fr({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"}),T=Cg.parse(y);return new Response(T.body,{status:T.status,headers:T.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:de(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 ll({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:de(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:de(this.logger)})}};import{z as Ne}from"zod";var Ib=Ne.array(Ne.object({proc:Ne.string(),webview:Ne.string(),info:Ne.object({"Android-Package":Ne.string(),Browser:Ne.string(),"Protocol-Version":Ne.string(),"User-Agent":Ne.string(),"V8-Version":Ne.string(),"WebKit-Version":Ne.string(),webSocketDebuggerUrl:Ne.string()}),pages:Ne.array(Ne.object({description:Ne.string(),devtoolsFrontendUrl:Ne.string(),id:Ne.string(),title:Ne.string(),type:Ne.string(),url:Ne.string(),webSocketDebuggerUrl:Ne.string()})),webviewName:Ne.string()}));var Sl=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 iN.devices()).filter(p=>p._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 q(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 Vy(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=Pb(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(),Ib.parse(e)}async createBrowserController({context:e}){let t=await Wi.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},storage:this.fixtures.storage,flagStore:Gc,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,flagStore:Gc,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Ya})}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 aN.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=Pb(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 xo=class r{stateManager;generator;driver;logger;fixtures;options;aborter;appsWithGrantedPermissions=new Set;orgId;adbPort;constructor({driver:e,generator:t,stateManager:n,logger:o,fixtures:i,options:a,aborter:l,orgId:c,adbPort:s}){this.driver=e,this.generator=t,this.stateManager=n,this.logger=o,this.fixtures=i,this.options=a??{},this.aborter=l,this.orgId=c,this.adbPort=s}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 Sl.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 ${Xd.resolve(e)}`)}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}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,m=uN(s),p;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,m=void 0),l&&(d=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({cache:m,description:n},"Cache description mismatch, clearing it automatically"),d=!0,m=void 0),!m){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 p=h.thoughts,hd({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget}),{result:await t(h.resolvedTarget),thoughts:p}}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(y){this.logger.warn({err:y},"Failed to refresh webviews, continuing...")}return await this.stateManager.getDomState()});let h=await c.startAsyncSpan("RESOLVE_TARGET_CACHE",async y=>{let{resolvedTarget:T}=await qy({target:m,domState:g,stateManager:this.stateManager,logger:this.logger}),v=Ky(T),R=lN(m,v);return this.logger.info({cacheDiffs:R},"Successfully resolved and updated target"),hd({command:o,cacheKey:i,targetName:a,updatedCache:v}),y.result={serializedElement:T.type==="WEBVIEW"?T.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":T.elementOnlySerializedXml},T});return m.type!=="WEBVIEW"&&nt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`]),{result:await t(h),thoughts:"Successfully executed preset action with cache."}}catch(h){if(m.type!=="WEBVIEW"&&nt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.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})}}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:de(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=$y({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 executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Ja({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{Qa(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":{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.driver.tap({x:i,y:a}),{success:!0,message:`Tapped at ${i}, ${a}`}}let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{if("type"in o&&o.type==="NATIVE"){let[i,a,l,c]=o.bounds,s=i+(l-i)/2,u=a+(c-a)/2;await this.driver.tap({x:s,y:u})}else{let{controller:i}=o;await i.browser.click(o.resolution,{createIsolatedFolder:()=>{let a=Math.random().toString(36).substring(4),l=Xd.join(dN(),"momentic","downloads"),c=Xd.join(l,this.orgId,a);return cN(c,{recursive:!0}),c}})}},description:e.target.description});return{success:!0,message:n}}case"TYPE":{let n;if(e.target){let o={type:"TAP",id:sN(),target:e.target,cache:e.cache};try{n=(await this.executeCommand({command:o,tracer:t})).message}finally{e.cache=o.cache}}return await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for keyboard to appear before typing"}),await this.driver.keys(e.text),{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=qs(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 q(i,this.aborter.controller?.signal),c=Date.now();try{let d="",m="";await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{d=(await this.stateManager.getDomState({includeWebviews:!0})).graph.xml,m=await this.stateManager.getCurrentScreenshot()});let p=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:de(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(p.result)return{success:p.result,message:p.thoughts};{let g=`AssertionFailureError: ${p.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 Fr({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(`
|
|
4011
|
-
`).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":switch(e.key){case"HOME":await this.driver.pressKeyCode(3);break;case"BACK":await this.driver.pressKeyCode(4);break;case"APP_SWITCHER":await this.driver.pressKeyCode(187);break;case"POWER":await this.driver.pressKeyCode(26);break;case"SEARCH":await this.driver.pressKeyCode(84);break;case"VOLUME_UP":await this.driver.pressKeyCode(24);break;case"VOLUME_DOWN":await this.driver.pressKeyCode(25);break;case"VOLUME_MUTE":await this.driver.pressKeyCode(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"};default:{let n=e;return{success:!0}}}}async initializeSettings(){}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}};async function Ob({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,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?.endsWith(Xe.TEST)?p.slice(0,-Xe.TEST.length):p,h=ln.parse(JSON.parse(m??"")),f=h.id,y=h.settings?.defaultChannel,T=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let b={...(await u(v,e)).emulator,...h.settings?.emulator},x=Date.now(),{driver:N,cleanup:D,limbarToken:$,limbarUrl:De,emulatorName:ee,adbTunnelPort:oe}=await t({socket:r,logger:e,creationOpts:{region:b.region,apkToInstall:y?{channel:y,tag:T}:void 0}});e.info({adbTunnelPort:oe,apkChannel:y,apkTag:T,duration:Date.now()-x,emulatorName:ee},"Android emulator session initiated"),e=e.child({emulator:ee});let lt=await o(v,e),_=await i(v,e),V=await a(v,e),te=await l(v),Re=c?await c(v):void 0,_e={};h.settings?.defaultEnv&&(_e=(await te.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let ve=new Qn({variablesFromEnvironment:_e,envName:h.settings?.defaultEnv,testName:g}),Ct=await xo.init({driver:N,generator:lt,logger:e,options:{emulator:b},fixtures:{storage:te,browserEnricher:V,browserGenerator:_,localCodeEvalTools:Re,testContext:ve},orgId:v,adbPort:oe,abortController:new AbortController});if(!r.connected)throw await D(),new Error("Socket not connected anymore, not proceeding with Android session setup");let ct=mN({socket:r,testContext:ve}),Ae=async()=>{clearInterval(ct);try{await D()}catch(Ve){e.warn({err:Ve},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:Ct,cleanup:Ae,emulatorName:ee}),r.emit("session",{testId:f,sessionId:d,limbarUrl:De,limbarToken:$}),{sessionId:d,testId:f,orgId:v,emulatorName:ee,logger:e}}function mN({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function Lb({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var pN=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},Nb={event:"cancel",createHandler:pN};import{diff as gN}from"deep-object-diff";import{cloneDeep as hN}from"lodash-es";import{randomUUID as Db}from"crypto";async function kb({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 m=Db(),p=await a.screenshot();d.afterSnapshot=m,n.attachAfterScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(p,"base64")})}catch(m){i.warn({err:m},"Failed to take after screenshot")}if(l){let m=Db();d.beforeSnapshot=m,n.attachBeforeScreenshot({logger:i,snapshotId:m,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 Ub({fixtures:r,inputs:e,tracer:t}){let{logger:n,controller:o,usageTracker:i}=r,a=[],l,c="SUCCESS",{fromStep:s,toStep:u}=e,d=!!s;for(let m=0;m<e.steps.length;m++){let p=e.steps[m];if(n.info({step:p},`Executing step ${m+1} of ${e.steps.length}: ${py(p.command)}`),d&&s){let f=JSON.stringify([]);if(p.id===s.fromStepId&&f===JSON.stringify(s.parentStepIdChain))d=!1;else continue}let g=await t.startStep({logger:n,step:p,attempt:1,parentStepIdChain:[]});i.trackStepExecution(p);let h=await kb({fixtures:r,inputs:e,step:p,stepTracer:g});if(a.push(h),await g.finish({parentStepIdChain:[],result:h}),h.status!=="SUCCESS"){c=h.status,l=h;break}if(p.envKey&&o.context.setVariable(p.envKey,h.data),u){let f=JSON.stringify([]);if(p.id===u.toStepId&&f===JSON.stringify(u.parentStepIdChain))break}}return{results:a,status:c,terminalResult:l}}async function yl(r){let{tracer:e}=r,{steps:t,testMetadata:n}=r.inputs,{cacheStorage:o,logger:i}=r.fixtures;await o.resolveEntries({logger:i,testId:n.id,stepLists:{steps:t}});let a=hN(t);i.info({testMetadata:ln.parse(n)},"Starting mobile test execution");let l=await e.startMainStepList(),{status:c,results:s}=await Ub({...r,tracer:l});if(c==="SUCCESS"){let u=gN(a,t);if(u&&Object.keys(u).length>0){i.debug({diffs:u},"Saving mobile step cache entries post-success");let{cachesToSave:d}=await To({steps:t,cacheCreationParams:{orgId:r.inputs.orgId,testId:n.id}});await o.saveEntries({logger:i,testId:n.id,entries:d})}return{status:"PASSED",results:s}}return c==="CANCELLED"?{status:"CANCELLED",results:s}:{status:"FAILED",results:s}}var Jd=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 oo("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}async startSubSteps(){return new _o({parentStep:this.step,socket:this.socket,parentTracer:this})}},_o=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new Jd({step:e.step,parentTracer:this,socket:this.socket})}},Tl=class{constructor(e){this.socket=e}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}};var fN=({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 Tl(n),d=await yl({fixtures:{controller:s,logger:e,cacheStorage:c,usageTracker:new La},inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:u});await u.finish();let m={results:d.results,status:d.status},p=JSON.parse(un(m));a?.(p)},Fb={event:"execute",createHandler:fN};import{debounce as SN}from"ts-debounce";var EN=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=SN(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)}},Bb={event:"keepalive",createHandler:EN};var zb=[Fb,Nb,Bb];function Gb(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new yN(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 Lb({socket:l,globalStateManager:n,logger:e})});let c;try{c=await Ob({...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}zb.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 m=p=>{c.logger.error({event:l.event,err:p instanceof Error?p:new Error(`${p}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:p instanceof Error?p.message:`${p}`})};try{let p=s.apply(this,d);p&&typeof p.catch=="function"&&p.catch(m)}catch(p){m(p)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{cloneDeep as TN}from"lodash-es";import bN from"truncate-json";var Hb=1e3,Vb=3e6;function vN(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=bN(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":AN(n);break;default:return(()=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})()}}}function AN(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function jb(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 bl(r,e){let t=TN(r);if(vN(t,e),t.length>Hb)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Hb);let n=jb(t,e);if(n.length>Vb)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Vb;)t.pop(),n=jb(t,e);try{return eo.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}var qi=!!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 DN,input as kN}from"@inquirer/prompts";import{existsSync as Zpe,mkdirSync as ege,statSync as UN}from"fs";import Mo,{supportsColor as NN}from"chalk";import{Console as Wb}from"console";import{format as Ki}from"util";var Qd=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}},vl=class r extends Wb{_buffer=[];_groupDepth=0;Console=Wb;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Qd(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
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(`
|
|
3947
|
+
`)?E+=`>${x}</${p}>
|
|
3948
|
+
`:E+=`>
|
|
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||""}
|
|
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(`
|
|
4012
3962
|
`).slice(o).filter(Boolean).join(`
|
|
4013
|
-
`);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",
|
|
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(`
|
|
4014
3964
|
`);process.stderr.write(`${o}
|
|
4015
|
-
`),globalThis.console=e}}var Zd=" ".repeat(6);import wN from"fetch-retry";import RN from"os";import qb,{multistream as CN}from"pino";import xN from"pino-pretty";import _N from"pino-std-serializers";var Yi=new Map,MN=!0,Kb="Log throttle exceeded",IN=100,PN=5e3,ON=wN(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}}),em=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??RN.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=MN?qb(a):qb(a,CN([{stream:xN({colorize:!0})}]))}getLevel(){return $a[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 ON(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:un(e)});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===Kb)return!0;let t=Date.now();return t-this.lastWindowStart>PN&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Kb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<IN?(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(fi[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=_N.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:$g({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,Yi.set("app",this),Yi.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=$a[e]):(this.minLevelValue=fi[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Al=({app:r,hostname:e,disableConsoleLogs:t})=>(Yi.has(r)||Yi.set(r,new em({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Yi.get(r));import{hostname as LN}from"os";var St=Al({app:"cli",hostname:LN(),disableConsoleLogs:!0}).child({cliVersion:"0.0.17"});function tm(r){if(!r)return;r=r.toLowerCase();let e=Wa.safeParse(r);if(e.success)return w.setMinLevel(e.data),e.data}function Yb({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),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 $b(()=>{if(c.forEach(u=>{w.log(""),o(u)}),c.length){w.log("");let u=c.length===1?"":"s";w.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{w.dimmed(n(d))})}if(s.length){w.log("");let u=s.length===1?"":"s";w.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{w.dimmed(n(d))})}if(a.length){w.log("");let u=a.length===1?"":"s";w.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{w.dimmed(n(d))})}if(l.length){w.log("");let u=l.length===1?"":"s";w.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{w.dimmed(n(d))})}if(i.length){w.log("");let u=i.length===1?"":"s";w.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{w.dimmed(n(d))})}w.log(""),w.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 Xi=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Mo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Mo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Mo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Mo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Mo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Mo.bgMagenta.white("RUNNING"),a=0):(w.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),NN||(i=`${i}`),w.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var FN=!1,Xb=(()=>{try{return UN("/.dockerenv"),!0}catch{return!1}})();async function wl(r,e){return qi||FN||Xb?!0:(w.flush(),St.flush(),await new Promise(n=>setTimeout(n,500)),await DN({message:r}))}async function Jb(r,e){return qi||Xb?e:(await kN({message:r,default:e})).trim()||e}import BN from"fs";import{tmpdir as zN}from"os";import GN from"path";import{registry as Ji}from"playwright-core/lib/server";import Qb from"proper-lockfile";var Zb=GN.join(zN(),"momenticBrowserInstallation");var rm=["chrome","chromium","chrome-for-testing"],HN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},ev={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function tv(r){let e=ev[HN[r]??""]??"",t=Ji.findExecutable(e);return!t||t.installType==="none"?!1:nm(t)}function nm(r){let e=r.executablePath();return BN.existsSync(e)}function VN(r,e){let t=ev[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Ji.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&nm(n)))return n}async function jN({browser:r,force:e}){let t=VN(r,e);if(!t){w.info(`Browser '${r}' is already installed, skipping...`);return}w.info(`Installing browser '${r}'...`);try{await Ji.installDeps([t],!1),await Ji.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){w.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Ji.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!nm(o);)w.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function Rl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?rm:Array.from(new Set(r));try{await Qb.lock(Zb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){w.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 jN({browser:i,force:e})}catch(a){o=a,w.error(`Failed to install the ${i} browser: ${a}`)}}finally{await Qb.unlock(Zb,{realpath:!1})}if(o)throw o}import{createServer as WN}from"http";async function Cl(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await $N(o))return o}w.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function $N(r){return new Promise((e,t)=>{let n=WN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(w.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 H0}from"crypto";import{diff as ehe}from"deep-object-diff";import dhe from"yaml";import{z as phe}from"zod";import{diff as Pge}from"deep-object-diff";import{cloneDeep as Lge}from"lodash-es";import{v4 as Wge}from"uuid";import qge from"yaml";import YN from"@dotenvx/dotenvx";import XN from"fs";import rv from"path";function JN(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 QN(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=JN(i);l&&(n[o]=l);continue}let a;try{a=XN.readFileSync(rv.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&&w.debug(n,"Set environment variables with interpolation from project configuration"),n}function ZN(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=YN.config({path:rv.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=QN({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=ZN({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 dD,readFileSync as mD,readdirSync as pD,writeFileSync as gD}from"fs";import{globSync as hD}from"glob";import In,{dirname as av}from"path";import{cwd as lm}from"process";import sv from"yaml";import{z as ye}from"zod";import nv from"fs";import{globSync as eD}from"glob";import Qi from"path";import tD from"yaml";import{z as om}from"zod";var ov=!1,im=[`**/*.${Xe.TEST}`,`**/*.${Xe.MODULE}`],am=om.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),sm=50,rD=om.object({fileType:om.nativeEnum(qe)});function _l(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},n=r.config.include??im,o=Array.from(r.config.exclude??[]).concat(Va),i=eD(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:sm,nodir:!0});for(let a of i){let l=nD(r.rootDir,a,t,e?dn:w);l&&(t.duplicateEntities[l.id]=l.paths)}return ov=!0,t}function nD(r,e,t,n){let o=Qi.join(r,e),i=oD(o,n);if(!i)return;let a=iD(i,o,n);if(!a)return;let l=rD.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=aD(o,n);if(!s)return;let u=sD(e,o,s);switch(c){case qe.TEST:try{return lD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case qe.MODULE:try{return cD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case qe.MOBILE_TEST:try{return uD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}default:{let d=c;return}}}function oD(r,e){try{return nv.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function iD(r,e,t){try{let n=tD.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 aD(r,e){try{return nv.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function sD(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:Qi.sep,fullPathSegments:e.split(Qi.sep),relativePathSegments:r.split(Qi.sep),fileName:Qi.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function lD(r,e,t,n,o){let i=to.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:qe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function cD(r,e,t,n,o){let i=Ot.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:qe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(`.${Xe.MODULE}`,"");return!ov&&Jn(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 uD(r,e,t,n,o){let i=ln.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(`.${Xe.TEST}`,"");return e.mobileTests[i.id]={type:qe.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Io="momentic.config.yaml",iv="momentic.workspace.yaml",fD=ye.object({projects:ye.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),SD=ye.union([ye.string(),ye.object({fromFile:ye.string(),json:ye.boolean().optional()})]),ED=ye.object({name:am,baseUrl:ye.string().optional().describe("Optional for mobile tests"),envFile:ye.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ye.record(ye.string(),SD).optional(),inheritFromShell:ye.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:en.optional().describe("deprecated: use project-level configuration only")}),yD=ye.object({postSave:ye.string().optional()}),TD=ye.object({name:am,include:ye.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ye.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ye.string().optional(),reporterDir:ye.string().optional(),outputDir:ye.string().optional(),retries:ye.number().optional().describe("number of retries per test"),parallel:ye.number().optional().describe("degree of parallelism"),environments:ye.array(ED).optional(),gitMainBranch:ye.string().optional(),gitProtectedBranches:ye.string().array().optional(),ai:$c.optional(),browser:en.optional(),emulator:kc.optional(),advanced:qc.optional(),hooks:yD.optional()});function lv(r,e){let t;try{t=mD(r,"utf-8")}catch(o){w.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=sv.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){w.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function cm(r){let e=lv(r,"project configuration");if(e!==void 0)try{return TD.parse(e)}catch(t){w.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function bD(r){let e=lv(r,"workspace configuration");if(e!==void 0)try{return fD.parse(e)}catch(t){w.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function vD(){let r=[],e=lm(),t=In.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=In.basename(e);if(Ha.includes(i))return w.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of pD(e))if(a.endsWith(Io)){let l=In.join(e,a),c=cm(l);c&&r.push({configFilePath:l,config:c,rootDir:av(l)})}if(r.length)return r;if(e=In.dirname(e),e===t)break}return r}function Zi(r={}){let{configFilePath:e,nameFilter:t}=r,n=wD(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:
|
|
4016
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return
|
|
4017
|
-
`)){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 MD(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 dv("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 dv("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function ID(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return MD(r,e,t);if(o)return}catch{}}function Ml(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 be(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function PD(){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 OD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(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 LD(r){let[e,t,n]=await Promise.all([be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["-s","--pretty=%B"])),be(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 ND(r){let[e,t,n,o]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Ml(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 DD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Ml(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 kD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Ml(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 UD(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([be(r,Te.revparse(["HEAD"])),be(r,Te.revparse(["--short","HEAD"])),be(r,Te.revparse(["--abbrev-ref","HEAD"])),be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"])),e?be(r,Te.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),_D(r)]),d=s?await be(r,Te.show(["--no-patch","--format=%ci",s])):void 0,m=i?.includes("github.com"),p=i?.includes("gitlab.com"),g=i?Ml(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,y=u["user.username"]||void 0,T=await ID(r,i,u)??y??void 0;return r.debug({userUsername:T,gitLocalUserLogin:y,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:T,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function FD(){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 BD(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function zD(r,e){let t=PD();if(!t)return UD(r,e);switch(t){case"GithubActions":return OD(r);case"GitlabCI":return LD(r);case"CircleCI":return ND(r);case"Buildkite":return DD(r);case"AzureDevOps":return kD(r);case"GCPCloudBuild":return FD()}}async function GD(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 HD(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 VD(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await HD(r,e,n,o,t)}else if(t.gitlabProjectPath)return await GD(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Il(r,e,t){let n=await BD(t),o=await zD(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 VD(r,e,i);return{...n,...o,...a}}import{randomUUID as jD}from"crypto";import Pn from"fs";import Pl from"path";import Ol from"yaml";function mv({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Jn(r)}.${Xe.TEST}`,l=Pl.join(o,a);if(Pn.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:qe.MOBILE_TEST,id:jD(),description:e,schemaVersion:ba,settings:n,steps:t},s=Ol.stringify(c);return Pn.writeFileSync(l,s,"utf-8"),l}function dm(r,e){let t=Pl.join(e,r);if(!Pn.existsSync(t))throw new Error(`Test file not found: ${t}`);let n=Pn.readFileSync(t,"utf-8").replace(/\r\n|\r/g,`
|
|
4018
|
-
`),
|
|
4019
|
-
`),a=Ol.parse(i),l=cn.parse(a);if(l.fileType!==qe.MOBILE_TEST)throw new Error(`File at '${o}' is not a mobile test (fileType=${l.fileType}).`);let c;e&&(c=(await To({steps:e})).stepsToSave);let s={...l,...c!==void 0?{steps:c}:{},...t!==void 0?{settings:t}:{}},u=Ol.stringify(cn.parse(s));Pn.writeFileSync(o,u,"utf-8")}import{randomUUID as WD}from"crypto";import br from"fs";import On from"path";var gv={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 $D(r,e,t){if(gv[t]){let i=gv[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 hv=new Set([".DS_Store","__MACOSX"]);function fv(r,e,t){let n=WD(),o=r.child({runGroupId:n});br.rmSync(e,{recursive:!0,force:!0});let i=br.readdirSync(t).filter(s=>!hv.has(s)).map(s=>On.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);br.mkdirSync(e,{recursive:!0});let a=On.join(i[0],"metadata.json"),l={...Ei.parse(JSON.parse(br.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=On.join(s,"runs");if(!br.existsSync(u))continue;let d=br.readdirSync(u);for(let g of d){if(hv.has(g))continue;let h=On.join(u,g),f=On.join(e,"runs",g);br.cpSync(h,f,{recursive:!0})}let m=On.join(s,"metadata.json"),p=Ei.parse(JSON.parse(br.readFileSync(m,"utf-8")));o.info({oldRunGroupId:p.id},"Merging metadata from run groups");for(let g in p){if(g==="id")continue;let h=g;l[h]=$D(l,p,h)}}let c=On.join(e,"metadata.json");br.writeFileSync(c,JSON.stringify(l,null,2))}import Ev from"adm-zip";import Sm from"fs";import{z as gm}from"zod";var k="v1",mm="mobile-cli",ea="0.0.17";var qD=9e4,KD=3,YD=1500,XD=15e3,Kt=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function JD(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var pm=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ea&&(e[Qg]=ea),mm&&(e[Zg]=mm),e}async sendRequest(e,t){let{retries:n=KD,requestTimeoutMs:o=qD,initialRetryDelayMs:i=YD,maxRetryDelayMs:a=XD}=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 Kt&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new Ur),l===0)throw s;let m=c-l,p=Math.min(i*Math.pow(2,m-1),a);await new Promise(g=>setTimeout(g,p))}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 JD(s);throw new Kt(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)}}},ur=class extends pm{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Yt=class extends ur{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(`/${k}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return fh.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${k}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return mh.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${k}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return ih.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${k}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${k}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return sh.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${k}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${k}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return lh.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${k}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return oh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${k}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return hh.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${k}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Sh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${k}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Ph.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${k}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${k}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${k}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${k}/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(`/${k}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Eh.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${k}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Bp.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${k}/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(`/${k}/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(`/${k}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return yh.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${k}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${k}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Th.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${k}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return bh.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${k}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return vh.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${k}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Nh.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${k}/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(`/${k}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Si.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${k}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Si.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${k}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Zc.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(`/${k}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Si.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${k}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Si.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${k}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Zc.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${k}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return gm.record(gm.string(),gm.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${k}/quarantine`,{method:"GET"});return Ah.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${k}/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(`/${k}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${k}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return wh.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${k}/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(`/${k}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Rh.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${k}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${k}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ch.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${k}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function hm(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(w.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),w.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return w.debug("Got auth info from API"),n}var Ll=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Po=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 QD,en as ZD}from"@faker-js/faker";var Oo="v1",Lo=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 QD({locale:ZD}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Oo}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Kt?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Oo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Oo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Oo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Oo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Oo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as e0}from"zod";var Ln=class extends ur{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(`/${k}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return jp.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${k}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ea,...e},signal:t.abortSignal});return Vp.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${k}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return e0.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(`/${k}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return rh.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(`/${k}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Yc.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return th.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(`/${k}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Yc.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${k}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return eh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${k}/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(`/${k}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return uc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${k}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return nh.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${k}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return lc.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return vp.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${k}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return hc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${k}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return eg.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${k}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ep.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${k}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return bp.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${k}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Tp.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${k}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return $m.parse(n)}};var No=class extends ur{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${k}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return qm.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function Sv(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Nl=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await Sv(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 Do=class extends ur{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return rg.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return ig.parse(o)}};function Dl({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new Xa:new fm(r,e,t,n)}var fm=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Xc(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&&cy({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await To({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import kl from"path";function t0(r){let e=new Ev,t=kl.join(r,"metadata.json"),n=Ei.parse(JSON.parse(Sm.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Sm.readdirSync(kl.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Ev(kl.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(kl.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Ul(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Sm.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Nl(e);try{let{runGroupId:i,buffer:a}=t0(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 r0 from"adm-zip";import Et from"fs";import Xt from"path";var ta=class r{constructor(e){this.filePath=e;Et.rmSync(this.filePath,{recursive:!0,force:!0}),Et.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Xt.join(this.filePath,e))}mkdir(e){Et.mkdirSync(Xt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Xt.join(this.filePath,e);if(Et.existsSync(t))return Et.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.filePath,t);try{Et.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Em(Xt.join(this.filePath,"runs"),e)}},Em=class{constructor(e,t){this.filePath=e;this.tempPath=Xt.join(e,`.${t}`),this.finalPath=Xt.join(e,`${t}.zip`),Et.rmSync(this.tempPath,{recursive:!0,force:!0}),Et.rmSync(this.finalPath,{recursive:!0,force:!0}),Et.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Xt.join(this.tempPath,e);if(Et.existsSync(t))return Et.readFileSync(t)}mkdir(e){Et.mkdirSync(Xt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ta(Xt.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.tempPath,t);Et.writeFileSync(o,n)}close(){let e=new r0;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Et.writeFileSync(this.finalPath,t),Et.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Wl from"fs";import Iv from"body-parser";import E0 from"cors";import y0 from"dedent";import{Router as a0}from"express";import bt from"fs";import{globSync as s0}from"glob";import Qe from"path";import Tm from"fs";import n0 from"path";var o0=new el(30,60*1e3),Am="https://api.momentic.ai",bm,Tv=r=>{Am=r},wm=()=>Am,Rm=()=>bm;var ko,vm,yv,bv=async r=>{if(bm&&ko&&yv)return ko;let e=new Yt({baseUrl:Am,apiKey:r,logger:w});bm=e;try{let t=await e.getAuthInfo();return ko=t.orgId,vm=t.userId,yv=r,ko}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ra=()=>{if(!ko)throw new Error("Your organization ID is invalid.");return ko},Fl=()=>{if(!vm)throw new Error("Your user ID is invalid.");return vm};var Cm,ym,vv=(r,e)=>{Cm=r,ym?.abort(),ym=new AbortController;let t=ym.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=n0.resolve(r.rootDir,o.envFile);try{if(Tm.lstatSync(i).isSymbolicLink())return;Tm.existsSync(i)&&n.push(i)}catch(a){w.warn({err:a},`Failed to check if env file ${i} exists`)}});try{i0({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){w.error({err:o},"Failed to start config file watchers")}},yt=()=>Cm;function i0({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Tm.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(o0.increment("setLocalProject")&&w.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.`),Cm=e(n.configFilePath))})})}function Tt(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var oa=a0();function na(r){let e=yt(),t=Qe.dirname(e.configFilePath);return Qe.join(t,...r)}function l0(r){let e=yt(),t=Qe.dirname(e.configFilePath),n=Qe.relative(t,r);return n?n.split(Qe.sep):[]}function c0(r,e){let t=bt.statSync(r),n=l0(r);return Vc.parse({name:e,absolutePath:r,relativePath:n.join(Qe.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}oa.post("/",Tt(async(r,e,t)=>{let n;try{n=Gg.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=na(n);if(!bt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Qe.sep)}`});return}if(!bt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Qe.sep)}`});return}let a=yt(),l=Array.from(a.config.exclude??[]).concat(Va),s=s0("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=Qe.join(o,d);return c0(m,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));oa.put("/",Tt(async(r,e,t)=>{let n;try{n=Hg.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=na(n);if(bt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Qe.sep)}`,pathSegments:n});return}bt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Qe.sep)}`,pathSegments:n};e.status(201).json(i)}));oa.patch("/",Tt(async(r,e,t)=>{let n,o;try{let s=Vg.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=na(n),a=na(o);if(!bt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Qe.sep)}`});return}if(bt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Qe.sep)}`});return}let l=Qe.dirname(a);bt.existsSync(l)||bt.mkdirSync(l,{recursive:!0}),bt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Qe.sep)} to ${o.join(Qe.sep)}`,pathSegments:o};e.status(200).json(c)}));oa.delete("/",Tt(async(r,e,t)=>{let n,o=!0;try{let c=jg.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=na(n);if(!bt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Qe.sep)}`,pathSegments:n});return}if(!bt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Qe.sep)}`});return}if(o)bt.rmSync(i,{recursive:!0,force:!0});else{if(bt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}bt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var xm=oa;import T0 from"events";import Pv,{Router as b0}from"express";import v0 from"http";import A0 from"path";var Bl=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 Av=new Bl;import{Router as m0}from"express";import{existsSync as p0}from"fs";import g0 from"path";import{hostname as u0}from"os";var d0="0.0.17",vr=Al({app:"mobile-desktop-server",hostname:u0(),disableConsoleLogs:!0}).child({cliVersion:d0});var _m=m0();_m.get("/",Tt(async(r,e)=>{let t=Rm();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));_m.post("/upload-url",Tt(async(r,e)=>{let t;try{t=Yg.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Rm();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=g0.resolve(t.filePath);if(!p0(o)){e.status(400).json({error:`File not found: ${o}`});return}await ca({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vr}),e.sendStatus(204)}));var wv=_m;import{Router as h0}from"express";var Rv=h0();Rv.get("/",Tt(async(r,e)=>{let t=yt(),n=_l(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 Cv=Rv;import{Router as f0}from"express";var xv=f0();xv.get("/",(r,e)=>{e.status(200).json({userId:Fl(),orgId:ra()})});var _v=xv;import{Router as S0}from"express";import Mm from"path";var zl=S0();zl.patch("/:testPath",Tt(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Kg.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});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=yt(),i=t.endsWith(`.${Xe.TEST}`)?t:`${t}.${Xe.TEST}`;await pv({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir});let a={message:"ok"};e.status(200).json(a)}));zl.post("/",Tt((r,e)=>{let t;try{t=qg.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}let{name:n,description:o,steps:i,settings:a,pathSegments:l}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{xc(n)}catch(h){e.status(400).json({error:h.message});return}let c=yt(),s=Mm.join(c.rootDir,...l),u=mv({name:n,description:o,steps:i,settings:a,folder:s}),d=Mm.basename(u),m=dm(d,s),p=Mm.relative(c.rootDir,u),g={id:m.id,fileName:d,fullPath:u,relativeFilePath:p};e.status(201).json(g)}));zl.get("/:fileName",Tt((r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(`.${Xe.TEST}`)?t:`${t}.${Xe.TEST}`,o=yt(),a=dm(n,o.rootDir);e.status(200).json(a)}));var Mv=zl;var Gl=class extends Po{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=yt();return xl(t,o,w)}};var Ov="10mb";async function Lv(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,logLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&Tv(n),await bv(t);let s=ra(),u=Fl(),d=r.logger.child({orgId:s,userId:u});vv(i,R=>Zi({configFilePath:R}));let m=Pv();m.use(E0()),m.use(Iv.json({limit:Ov})),m.use(Iv.urlencoded({extended:!1,limit:Ov}));let p=b0();if(p.use("/folders",xm),p.use("/entities",Cv),p.use("/identify",_v),p.use("/mobile-tests",Mv),p.use("/assets",wv),m.use("/api",p),m.use((R,b,x)=>{w.debug({url:R.url,path:R.path,query:R.query,method:R.method,body:R.body,headers:R.rawHeaders,client:R.ip},"Incoming request on mobile-desktop-server"),b.on("close",()=>{b.statusCode>=400&&(w.error({url:R.url,method:R.method,statusCode:b.statusCode},"Request completed in error on mobile-desktop-server"),vr.error({url:R.url,method:R.method,statusCode:b.statusCode},"Request completed in error on mobile-desktop-server"))}),x()}),m.use((R,b,x,N)=>{if(R instanceof Error&&R.message.includes("BadRequestError: request aborted")){x.status(400).send("Client disconnected");return}w.error({stack:R.stack,msg:R.message,err:R,url:b.url,method:b.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vr.error({stack:R.stack,msg:R.message,err:R,url:b.url,method:b.method},"Unhandled exception leading to 500 on mobile-desktop-server"),x.status(500).send(`Internal Server Error: ${R.message}`)}),o){let R=Pv.static(o,{setHeaders:b=>{b.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(R),m.use("*",(b,x)=>{x.sendFile(A0.join(o,"index.html"))})}let g=v0.createServer(m),h=`http://localhost:${e}`;await new Promise(R=>{try{g.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),R()})}catch(b){b.message.includes("EADDRINUSE")?w0(e):w.error(`An unexpected error occurred while starting the server: ${b.message}`),process.exit(1)}});let y={type:"API_KEY",baseUrl:wm(),apiKey:t,logger:d},T=new Yt(y),{dispose:v}=Gb({baseServer:g,logger:d,authorization:y,globalStateManager:Av,getOrgId:()=>ra(),androidDriverFactory:async({socket:R,logger:b,creationOpts:x})=>{let N=Math.floor(Math.random()*1e4)+4e4,D=await Cl(N,"appium");return la({logger:b,logLevel:a,apiClient:T,creationOpts:x,socket:R,appiumPort:D,onStatusUpdate:$=>{R.emit("connectionStatusUpdate",{message:$})}})},mobileGeneratorFactory:async R=>new Do({baseUrl:wm(),apiKey:t,logger:d}),browserGeneratorFactory:async R=>new Ln({},y),browserEnricherFactory:async R=>new No(y,new Ln({},y)),storageFactory:async R=>new Gl(T,R),cacheStorageFactory:async R=>{let b=yt(),x=await Il(d,T,b);return Dl({orgId:R,client:T,gitMetadata:x,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new Lo({httpClient:T,fakerSeed:void 0}),keepSessionAlive:R=>T.extendAndroidEmulatorTtl(R),settingsFactory:async()=>({emulator:yt().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await v(),await nt.flush()}catch(R){w.error({err:R},"Error during session dispose on SIGUSR2")}try{g.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{w.info("SIGTERM in Momentic mobile app received");try{await v(),await nt.flush()}finally{g.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{w.info("SIGINT in Momentic mobile app received");try{await v(),await nt.flush()}finally{g.close(()=>process.exit(0))}})}T0.setMaxListeners(50);process.on("warning",r=>{vr.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vr.error({err:r},"Uncaught exception on mobile-desktop-server"),w.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vr.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),w.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function w0(r){w.error(y0`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
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.
|
|
4020
3970
|
Using Bash on MacOS or Linux:
|
|
4021
3971
|
lsof -t -i :58888 | xargs kill -9
|
|
4022
3972
|
|
|
4023
3973
|
Using Command Prompt on Windows:
|
|
4024
3974
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4025
|
-
`)}import
|
|
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:
|
|
4026
3976
|
- ${r.join(`
|
|
4027
3977
|
- `)}
|
|
4028
|
-
`),r.forEach(m=>{if(!Hl.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=Hl.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=sa.resolve(m);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(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.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=sa.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Hl.readFileSync(u,"utf-8").replace(/\r\n|\r/g,`
|
|
4029
|
-
`),p=cn.parse(I0.parse(d));M0(p.schemaVersion,ba)&&a.warn(`Test ${u} has schema version ${p.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);let g=sa.relative(t.rootDir,u),h=e.mobileTests[p.id]?.name??sa.basename(u,sa.extname(u));return{id:p.id,name:h,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:g,quarantined:p.id in l,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 P0}from"lodash-es";async function Hv(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:P0(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(d.loggerBindings||{}),p=1+(c.settings?.retries??1);try{for(let g=0;g<p;g++){let h=new Date,f=await O0({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:g,totalAttempts:p},fixtures:{...t,logger:m},inputs:e,options:o}),y=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:y}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(g!==p-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:y}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,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 O0(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:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:y,project:T,envOverride:v}=a,{alwaysSaveCache:R,noCache:b,logLevel:x}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let N={...a.project.config.emulator,...t.settings?.emulator},D=Dl({orgId:u,client:m,gitMetadata:d,alwaysSaveCache:R,noCache:b}),$=new Po(m,u),De=new Do(m),ee={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p},oe=new Ln({},ee),lt=new No(ee,oe),_=new Lo({httpClient:m,fakerSeed:void 0}),V=Math.floor(Math.random()*1e4)+4e4,te=await Cl(V,"appium"),_e=await la({apiClient:m,logger:p,logLevel:x,creationOpts:{apkToInstall:f?{channel:f,tag:y}:void 0,region:N.region},onStatusUpdate:Bo=>{p.debug({status:Bo},"Limbar emulator status update")},appiumPort:te}),ve=await e.startAttempt({emulatorName:_e.emulatorName}),Ct=p.child(ve.loggerBindings||{}),ct=v||t.settings?.defaultEnv,Ae;ct&&(Ae=xl(ct,T,Ct).variables);let Ve=new Qn({variablesFromEnvironment:Ae??{},envName:ct,testName:t.name}),Xr=await xo.init({driver:_e.driver,generator:De,logger:Ct,orgId:u,adbPort:_e.adbTunnelPort,options:{emulator:N},fixtures:{storage:$,browserEnricher:lt,browserGenerator:oe,localCodeEvalTools:_,testContext:Ve}}),dr;try{dr=await yl({fixtures:{controller:Xr,logger:Ct,cacheStorage:D,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:ve})}finally{await _e.cleanup()}return await ve.finish({logger:Ct,results:dr.results,status:dr.status}),dr}import{randomUUID as L0}from"crypto";import{debounce as N0}from"ts-debounce";var Uo="0.0.17";var Vl="assets";function D0(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 k0(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Fm=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.commandTracer=new oo("command")}children=[];commandTracer;finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Vl}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Vl}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:k0(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 Fo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Fo=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(`${Vl}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Fm(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:D0(e.status),finishedAt:e.finishedAt}))))}},Bm=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:bl(o,t),beforeResults:i?bl(i,t):void 0,afterResults:a?bl(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 Fo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Fo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Fo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Vl}/${t}.jpeg`)}},zm=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=L0(),o={id:n,schemaVersion:Wn,runAttemptSchemaVersion:Hh,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=N0(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Bm(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},jl=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:Dt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Uo,labels:a??[]},c=new ta(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:Uo,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 zm(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function Vv(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 jv(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:m}=e;F0(d)&&w.warn(`Output directory ${d} already exists, removing before test execution...`);let p=await Vv(l,a,e.ignoreQuarantine),g=_l(i),h=await Gv({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:w,quarantinedTestReasons:p}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),y=await jl.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),T=[],v=new Date,R=new Set,b=async()=>B0({runResults:T,startTime:v,ranTests:R,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],N=async()=>{w.warn("SIGINT received. Stopping tests and printing latest results..."),await y.finish({logger:f,status:"CANCELLED"}),await b(),await Promise.allSettled(x.map(ee=>ee())),process.exit(1)};process.once("SIGINT",N);let D={};for(let ee=0;ee<h.length;ee++){let oe=Object.values(D);oe.length===m&&await Promise.race(oe.map(V=>V.promise));let lt=h[ee],_=`test-${ee}`;D[_]={done:!1,promise:(async({testDefinition:V})=>{R.add(_);let te=V.relativeFilePath.includes("..")?V.fullFilePath:V.relativeFilePath;Xi({status:"START",testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length});let Re=setInterval(()=>Xi({status:"RUN",testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),5*60*1e3),_e=U0(),ve=f.child({testId:V.id,runId:_e}),Ct=new Xs({logger:ve,reporter:new Ll(a),runType:"mobile-test-run",runId:_e,testMetadata:V,suiteMetadata:void 0});try{let ct=await Hv({metadata:{...o,runId:_e},fixtures:{...t,tracer:y,logger:ve,usageTracker:Ct},inputs:{...n,project:i,testDefinition:V,channel:n.channel??V.settings?.defaultChannel,tag:n.tag??V.settings?.defaultTag,logUpdate:(Ae,Ve)=>Xi({status:Ae,testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length,additionalText:Ve}),runSigIntHandlers:x},options:e});Xi({status:ct.status,testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),T.push(ct)}catch(ct){let Ae=`Encountered unexpected fatal error when running test '${V.name}': ${ct.message}`;w.error(Ae),ve.error(Ae)}finally{clearInterval(Re),D[_].done=!0,delete D[_]}await Ct.flush(l)})({testDefinition:lt})}}await Promise.allSettled(Object.values(D).map(ee=>ee.promise));let De=T.some(ee=>ee.status==="FAILED"&&!ee.quarantined)?"FAILED":"PASSED";return await y.finish({logger:f,status:De}),process.off("SIGINT",N),b()}async function B0({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=Yb({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${Zd}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return w.log(""),o?(w.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Ul({client:n,consoleLogger:w,resultsPath:i})):w.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 Gm(){Xh(),tv("Chromium")||(qi?(await wl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Rl({rawBrowsers:["chromium"],force:!1,all:!1})):(w.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)))}sy({serviceName:"mobile-cli"});St.setApp("mobile-cli");var Yr=new z0;Yr.name("momentic-mobile").description("Momentic Mobile CLI").version(Uo);var W0=Yr.command("assets").description("Manage mobile testing assets");W0.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(ia).addOption(aa).addOption(Dm).addOption(kv).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=$l.resolve(r);Wl.existsSync(a)||(w.error(`File not found: ${a}`),process.exit(1));let l=new Yt({baseUrl:n,apiKey:t,logger:w});/\.apk$/i.test(a)||(w.error(`File is not an APK file: ${a}`),process.exit(1)),await ca({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:w})});Yr.command("app").addOption(ia).addOption(aa).addOption(Om).addOption(Pm).addOption(Um).addOption(Lm).addOption(Nm).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=tm(r.logLevel);St.setApp("mobile-desktop-server");let l=new Yt({baseUrl:t,apiKey:e,logger:St});await hm({client:l,skipPrompts:n}),w.debug("API key check complete");let c=j0(import.meta.url),s=$l.dirname(c),u=$l.resolve(s,"..","static");await Gm(),w.debug({appiumHome:yi},"Resolved resource paths");let d=Zi({configFilePath:r.config}),m=Nv;await Lv({momenticServerUrl:t,serverPort:m,apiKey:e,staticDir:u,initialProject:d,logLevel:a,logger:St,noCache:o,alwaysSaveCache:i});let p=`http://localhost:${m}`;w.info(`Local app started on: ${p}`),await V0(p)});var Wv=Yr.command("results").description("Merge and upload test results.");Wv.command("merge").description("Merge test results files.").addOption(km).addArgument(new Hm("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(w.error("Output directory is required."),process.exit(1)),Wl.existsSync(r)||(w.warn("Results path does not exist, skipping merge."),process.exit(0)),Wl.existsSync(t)&&w.warn(`Output directory ${t} already exists, removing before merging...`),fv(St,t,r),await nt.flush()});var $0=new Hm("<results>","Path to the results archive.").argRequired();Wv.command("upload").description("Upload test results to Momentic cloud.").addOption(ia).addOption(aa).addArgument($0).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=St,i=new Yt({baseUrl:n,apiKey:t,logger:o});await Ul({consoleLogger:w,resultsPath:r,client:i}),await nt.flush(),process.exit(0)});var q0=Yr.command("run").alias("test").description("Run tests on the local machine");q0.addOption(ia).addOption(aa).addOption(Pm).addOption(Om).addOption(Fv).addOption(Um).addOption(Lm).addOption(Nm).addOption(km).addOption(Bv).addOption(zv).addOption(Dm).addOption(Dv).addOption(Uv).addArgument(new Hm("<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=tm(e.logLevel);await Gm(),w.debug({appiumHome:yi},"Resolved resource paths");let c=Zi({configFilePath:e.config}),s=a??c.config.outputDir??uv,u=e.parallel??c.config.parallel??1;w.debug("Checking API key and dependencies");let d=new Yt({baseUrl:n,apiKey:t,logger:w}),{orgId:m,userId:p}=await hm({client:d,skipPrompts:e.yes});w.debug("API key check and browser installation complete");let g=H0(),h=St.child({runGroupId:g,orgId:m,userId:p,cliVersion:Uo}),f=await Il(St,d,c);h.debug(f,"Got local git metadata");try{let y=await jv({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:m}});await nt.flush(),y.failed>0?process.exit(1):process.exit(0)}catch(y){await nt.flush(),w.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),w.error(y),St.error({err:y},"Failed to run tests locally"),process.exit(1)}});Yr.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new G0("--name <name>","Name of the project")).action(async r=>{w.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4030
|
-
`),w.info("This wizard will help you bootstrap a new Momentic project."),Wl.existsSync(Io)&&(w.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 Jb("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:im};cv(t,Io),w.success(`Initialized Momentic project file at ${$l.resolve(Io)}`)});Yr.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: ${rm.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(w.error("No browsers specified"),process.exit(1)),await Rl({rawBrowsers:r,force:e.force,all:e.all})});async function K0(){try{await Yr.parseAsync(process.argv)}catch(r){St.error({err:r},"Uncaught error in CLI"),St.flush(),await nt.flush(),w.error(r),process.exit(1)}}K0();
|
|
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();
|
|
4031
3980
|
//# sourceMappingURL=cli.js.map
|